__all__ = ['Distribution']

import re
from distutils.core import Distribution as _Distribution
from setuptools.depends import Require
from setuptools.command.install import install
from setuptools.command.sdist import sdist
from setuptools.command.install_lib import install_lib
from distutils.errors import DistutilsOptionError, DistutilsPlatformError
from distutils.errors import DistutilsSetupError
import setuptools, pkg_resources, distutils.core, distutils.dist, distutils.cmd
import os, distutils.log

def _get_unpatched(cls):
    """Protect against re-patching the distutils if reloaded

    Also ensures that no other distutils extension monkeypatched the distutils
    first.
    """
    while cls.__module__.startswith('setuptools'):
        cls, = cls.__bases__
    if not cls.__module__.startswith('distutils'):
        raise AssertionError(
            "distutils has already been patched by %r" % cls
        )
    return cls

_Distribution = _get_unpatched(_Distribution)

sequence = tuple, list

def check_importable(dist, attr, value):
    try:
        ep = pkg_resources.EntryPoint.parse('x='+value)
        assert not ep.extras
    except (TypeError,ValueError,AttributeError,AssertionError):
        raise DistutilsSetupError(
            "%r must be importable 'module:attrs' string (got %r)"
            % (attr,value)
        )

def assert_string_list(dist, attr, value):
    """Verify that value is a string list or None"""
    try:
        assert ''.join(value)!=value
    except (TypeError,ValueError,AttributeError,AssertionError):
        raise DistutilsSetupError(
            "%r must be a list of strings (got %r)" % (attr,value)
        )

def check_nsp(dist, attr, value):
    """Verify that namespace packages are valid"""
    assert_string_list(dist,attr,value)
    for nsp in value:
        if not dist.has_contents_for(nsp):
            raise DistutilsSetupError(
                "Distribution contains no modules or packages for " +
                "namespace package %r" % nsp
            )
        if '.' in nsp:
            parent = '.'.join(nsp.split('.')[:-1])
            if parent not in value:
                distutils.log.warn(
                    "%r is declared as a package namespace, but %r is not:"
                    " please correct this in setup.py", nsp, parent
                )

def check_extras(dist, attr, value):
    """Verify that extras_require mapping is valid"""
    try:
        for k,v in value.items():
            list(pkg_resources.parse_requirements(v))
    except (TypeError,ValueError,AttributeError):
        raise DistutilsSetupError(
            "'extras_require' must be a dictionary whose values are "
            "strings or lists of strings containing valid project/version "
            "requirement specifiers."
        )

def assert_bool(dist, attr, value):
    """Verify that value is True, False, 0, or 1"""
    if bool(value) != value:
        raise DistutilsSetupError(
            "%r must be a boolean value (got %r)" % (attr,value)
        )
def check_requirements(dist, attr, value):
    """Verify that install_requires is a valid requirements list"""
    try:
        list(pkg_resources.parse_requirements(value))
    except (TypeError,ValueError):
        raise DistutilsSetupError(
            "%r must be a string or list of strings "
            "containing valid project/version requirement specifiers" % (attr,)
        )
def check_entry_points(dist, attr, value):
    """Verify that entry_points map is parseable"""
    try:
        pkg_resources.EntryPoint.parse_map(value)
    except ValueError, e:
        raise DistutilsSetupError(e)

def check_test_suite(dist, attr, value):
    if not isinstance(value,basestring):
        raise DistutilsSetupError("test_suite must be a string")

def check_package_data(dist, attr, value):
    """Verify that value is a dictionary of package names to glob lists"""
    if isinstance(value,dict):
        for k,v in value.items():
            if not isinstance(k,str): break
            try: iter(v)
            except TypeError:
                break
        else:
            return
    raise DistutilsSetupError(
        attr+" must be a dictionary mapping package names to lists of "
        "wildcard patterns"
    )

class Distribution(_Distribution):
    """Distribution with support for features, tests, and package data

    This is an enhanced version of 'distutils.dist.Distribution' that
    effectively adds the following new optional keyword arguments to 'setup()':

     'install_requires' -- a string or sequence of strings specifying project
        versions that the distribution requires when installed, in the format
        used by 'pkg_resources.require()'.  They will be installed
        automatically when the package is installed.  If you wish to use
        packages that are not available in PyPI, or want to give your users an
        alternate download location, you can add a 'find_links' option to the
        '[easy_install]' section of your project's 'setup.cfg' file, and then
        setuptools will scan the listed web pages for links that satisfy the
        requirements.

     'extras_require' -- a dictionary mapping names of optional "extras" to the
        additional requirement(s) that using those extras incurs. For example,
        this::

            extras_require = dict(reST = ["docutils>=0.3", "reSTedit"])

        indicates that the distribution can optionally provide an extra
        capability called "reST", but it can only be used if docutils and
        reSTedit are installed.  If the user installs your package using
        EasyInstall and requests one of your extras, the corresponding
        additional requirements will be installed if needed.

     'features' -- a dictionary mapping option names to 'setuptools.Feature'
        objects.  Features are a portion of the distribution that can be
        included or excluded based on user options, inter-feature dependencies,
        and availability on the current system.  Excluded features are omitted
        from all setup commands, including source and binary distributions, so
        you can create multiple distributions from the same source tree.
        Feature names should be valid Python identifiers, except that they may
        contain the '-' (minus) sign.  Features can be included or excluded
        via the command line options '--with-X' and '--without-X', where 'X' is
        the name of the feature.  Whether a feature is included by default, and
        whether you are allowed to control this from the command line, is
        determined by the Feature object.  See the 'Feature' class for more
        information.

     'test_suite' -- the name of a test suite to run for the 'test' command.
        If the user runs 'python setup.py test', the package will be installed,
        and the named test suite will be run.  The format is the same as
        would be used on a 'unittest.py' command line.  That is, it is the
        dotted name of an object to import and call to generate a test suite.

     'package_data' -- a dictionary mapping package names to lists of filenames
        or globs to use to find data files contained in the named packages.
        If the dictionary has filenames or globs listed under '""' (the empty
        string), those names will be searched for in every package, in addition
        to any names for the specific package.  Data files found using these
        names/globs will be installed along with the package, in the same
        location as the package.  Note that globs are allowed to reference
        the contents of non-package subdirectories, as long as you use '/' as
        a path separator.  (Globs are automatically converted to
        platform-specific paths at runtime.)

    In addition to these new keywords, this class also has several new methods
    for manipulating the distribution's contents.  For example, the 'include()'
    and 'exclude()' methods can be thought of as in-place add and subtract
    commands that add or remove packages, modules, extensions, and so on from
    the distribution.  They are used by the feature subsystem to configure the
    distribution for the included and excluded features.
    """

    _patched_dist = None

    def patch_missing_pkg_info(self, attrs):
        # Fake up a replacement for the data that would normally come from
        # PKG-INFO, but which might not yet be built if this is a fresh
        # checkout.
        #
        if not attrs or 'name' not in attrs or 'version' not in attrs:
            return
        key = pkg_resources.safe_name(str(attrs['name'])).lower()
        dist = pkg_resources.working_set.by_key.get(key)
        if dist is not None and not dist.has_metadata('PKG-INFO'):
            dist._version = pkg_resources.safe_version(str(attrs['version']))
            self._patched_dist = dist

    def __init__ (self, attrs=None):
        have_package_data = hasattr(self, "package_data")
        if not have_package_data:
            self.package_data = {}
        self.require_features = []
        self.features = {}
        self.dist_files = []
        self.src_root = attrs and attrs.pop("src_root", None)
        self.patch_missing_pkg_info(attrs)
        # Make sure we have any eggs needed to interpret 'attrs'
        if attrs is not None:
            self.dependency_links = attrs.pop('dependency_links', [])
            assert_string_list(self,'dependency_links',self.dependency_links)
        if attrs and 'setup_requires' in attrs:
            self.fetch_build_eggs(attrs.pop('setup_requires'))
        for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
            if not hasattr(self,ep.name):
                setattr(self,ep.name,None)
        _Distribution.__init__(self,attrs)
        if isinstance(self.metadata.version, (int,long,float)):
            # Some people apparently take "version number" too literally :)
            self.metadata.version = str(self.metadata.version)

    def parse_command_line(self):
        """Process features after parsing command line options"""
        result = _Distribution.parse_command_line(self)
        if self.features:
            self._finalize_features()
        return result

    def _feature_attrname(self,name):
        """Convert feature name to corresponding option attribute name"""
        return 'with_'+name.replace('-','_')

    def fetch_build_eggs(self, requires):
        """Resolve pre-setup requirements"""
        from pkg_resources import working_set, parse_requirements
        for dist in working_set.resolve(
            parse_requirements(requires), installer=self.fetch_build_egg,
            replace_conflicting=True
        ):
            working_set.add(dist, replace=True)

    def finalize_options(self):
        _Distribution.finalize_options(self)
        if self.features:
            self._set_global_opts_from_features()

        for ep in pkg_resources.iter_entry_points('distutils.setup_keywords'):
            value = getattr(self,ep.name,None)
            if value is not None:
                ep.require(installer=self.fetch_build_egg)
                ep.load()(self, ep.name, value)
        if getattr(self, 'convert_2to3_doctests', None):
            # XXX may convert to set here when we can rely on set being builtin
            self.convert_2to3_doctests = [os.path.abspath(p) for p in self.convert_2to3_doctests]
        else:
            self.convert_2to3_doctests = []

    def fetch_build_egg(self, req):
        """Fetch an egg needed for building"""

        try:
            cmd = self._egg_fetcher
            cmd.package_index.to_scan = []
        except AttributeError:
            from setuptools.command.easy_install import easy_install
            dist = self.__class__({'script_args':['easy_install']})
            dist.parse_config_files()
            opts = dist.get_option_dict('easy_install')
            keep = (
                'find_links', 'site_dirs', 'index_url', 'optimize',
                'site_dirs', 'allow_hosts'
            )
            for key in opts.keys():
                if key not in keep:
                    del opts[key]   # don't use any other settings
            if self.dependency_links:
                links = self.dependency_links[:]
                if 'find_links' in opts:
                    links = opts['find_links'][1].split() + links
                opts['find_links'] = ('setup', links)
            cmd = easy_install(
                dist, args=["x"], install_dir=os.curdir, exclude_scripts=True,
                always_copy=False, build_directory=None, editable=False,
                upgrade=False, multi_version=True, no_report=True, user=False
            )
            cmd.ensure_finalized()
            self._egg_fetcher = cmd
        return cmd.easy_install(req)

    def _set_global_opts_from_features(self):
        """Add --with-X/--without-X options based on optional features"""

        go = []
        no = self.negative_opt.copy()

        for name,feature in self.features.items():
            self._set_feature(name,None)
            feature.validate(self)

            if feature.optional:
                descr = feature.description
                incdef = ' (default)'
                excdef=''
                if not feature.include_by_default():
                    excdef, incdef = incdef, excdef

                go.append(('with-'+name, None, 'include '+descr+incdef))
                go.append(('without-'+name, None, 'exclude '+descr+excdef))
                no['without-'+name] = 'with-'+name

        self.global_options = self.feature_options = go + self.global_options
        self.negative_opt = self.feature_negopt = no

    def _finalize_features(self):
        """Add/remove features and resolve dependencies between them"""

        # First, flag all the enabled items (and thus their dependencies)
        for name,feature in self.features.items():
            enabled = self.feature_is_included(name)
            if enabled or (enabled is None and feature.include_by_default()):
                feature.include_in(self)
                self._set_feature(name,1)

        # Then disable the rest, so that off-by-default features don't
        # get flagged as errors when they're required by an enabled feature
        for name,feature in self.features.items():
            if not self.feature_is_included(name):
                feature.exclude_from(self)
                self._set_feature(name,0)

    def get_command_class(self, command):
        """Pluggable version of get_command_class()"""
        if command in self.cmdclass:
            return self.cmdclass[command]

        for ep in pkg_resources.iter_entry_points('distutils.commands',command):
            ep.require(installer=self.fetch_build_egg)
            self.cmdclass[command] = cmdclass = ep.load()
            return cmdclass
        else:
            return _Distribution.get_command_class(self, command)

    def print_commands(self):
        for ep in pkg_resources.iter_entry_points('distutils.commands'):
            if ep.name not in self.cmdclass:
                cmdclass = ep.load(False) # don't require extras, we're not running
                self.cmdclass[ep.name] = cmdclass
        return _Distribution.print_commands(self)

    def _set_feature(self,name,status):
        """Set feature's inclusion status"""
        setattr(self,self._feature_attrname(name),status)

    def feature_is_included(self,name):
        """Return 1 if feature is included, 0 if excluded, 'None' if unknown"""
        return getattr(self,self._feature_attrname(name))

    def include_feature(self,name):
        """Request inclusion of feature named 'name'"""

        if self.feature_is_included(name)==0:
            descr = self.features[name].description
            raise DistutilsOptionError(
               descr + " is required, but was excluded or is not available"
           )
        self.features[name].include_in(self)
        self._set_feature(name,1)

    def include(self,**attrs):
        """Add items to distribution that are named in keyword arguments

        For example, 'dist.exclude(py_modules=["x"])' would add 'x' to
        the distribution's 'py_modules' attribute, if it was not already
        there.

        Currently, this method only supports inclusion for attributes that are
        lists or tuples.  If you need to add support for adding to other
        attributes in this or a subclass, you can add an '_include_X' method,
        where 'X' is the name of the attribute.  The method will be called with
        the value passed to 'include()'.  So, 'dist.include(foo={"bar":"baz"})'
        will try to call 'dist._include_foo({"bar":"baz"})', which can then
        handle whatever special inclusion logic is needed.
        """
        for k,v in attrs.items():
            include = getattr(self, '_include_'+k, None)
            if include:
                include(v)
            else:
                self._include_misc(k,v)

    def exclude_package(self,package):
        """Remove packages, modules, and extensions in named package"""

        pfx = package+'.'
        if self.packages:
            self.packages = [
                p for p in self.packages
                    if p != package and not p.startswith(pfx)
            ]

        if self.py_modules:
            self.py_modules = [
                p for p in self.py_modules
                    if p != package and not p.startswith(pfx)
            ]

        if self.ext_modules:
            self.ext_modules = [
                p for p in self.ext_modules
                    if p.name != package and not p.name.startswith(pfx)
            ]

    def has_contents_for(self,package):
        """Return true if 'exclude_package(package)' would do something"""

        pfx = package+'.'

        for p in self.iter_distribution_names():
            if p==package or p.startswith(pfx):
                return True

    def _exclude_misc(self,name,value):
        """Handle 'exclude()' for list/tuple attrs without a special handler"""
        if not isinstance(value,sequence):
            raise DistutilsSetupError(
                "%s: setting must be a list or tuple (%r)" % (name, value)
            )
        try:
            old = getattr(self,name)
        except AttributeError:
            raise DistutilsSetupError(
                "%s: No such distribution setting" % name
            )
        if old is not None and not isinstance(old,sequence):
            raise DistutilsSetupError(
                name+": this setting cannot be changed via include/exclude"
            )
        elif old:
            setattr(self,name,[item for item in old if item not in value])

    def _include_misc(self,name,value):
        """Handle 'include()' for list/tuple attrs without a special handler"""

        if not isinstance(value,sequence):
            raise DistutilsSetupError(
                "%s: setting must be a list (%r)" % (name, value)
            )
        try:
            old = getattr(self,name)
        except AttributeError:
            raise DistutilsSetupError(
                "%s: No such distribution setting" % name
            )
        if old is None:
            setattr(self,name,value)
        elif not isinstance(old,sequence):
            raise DistutilsSetupError(
                name+": this setting cannot be changed via include/exclude"
            )
        else:
            setattr(self,name,old+[item for item in value if item not in old])

    def exclude(self,**attrs):
        """Remove items from distribution that are named in keyword arguments

        For example, 'dist.exclude(py_modules=["x"])' would remove 'x' from
        the distribution's 'py_modules' attribute.  Excluding packages uses
        the 'exclude_package()' method, so all of the package's contained
        packages, modules, and extensions are also excluded.

        Currently, this method only supports exclusion from attributes that are
        lists or tuples.  If you need to add support for excluding from other
        attributes in this or a subclass, you can add an '_exclude_X' method,
        where 'X' is the name of the attribute.  The method will be called with
        the value passed to 'exclude()'.  So, 'dist.exclude(foo={"bar":"baz"})'
        will try to call 'dist._exclude_foo({"bar":"baz"})', which can then
        handle whatever special exclusion logic is needed.
        """
        for k,v in attrs.items():
            exclude = getattr(self, '_exclude_'+k, None)
            if exclude:
                exclude(v)
            else:
                self._exclude_misc(k,v)

    def _exclude_packages(self,packages):
        if not isinstance(packages,sequence):
            raise DistutilsSetupError(
                "packages: setting must be a list or tuple (%r)" % (packages,)
            )
        map(self.exclude_package, packages)

    def _parse_command_opts(self, parser, args):
        # Remove --with-X/--without-X options when processing command args
        self.global_options = self.__class__.global_options
        self.negative_opt = self.__class__.negative_opt

        # First, expand any aliases
        command = args[0]
        aliases = self.get_option_dict('aliases')
        while command in aliases:
            src,alias = aliases[command]
            del aliases[command]    # ensure each alias can expand only once!
            import shlex
            args[:1] = shlex.split(alias,True)
            command = args[0]

        nargs = _Distribution._parse_command_opts(self, parser, args)

        # Handle commands that want to consume all remaining arguments
        cmd_class = self.get_command_class(command)
        if getattr(cmd_class,'command_consumes_arguments',None):
            self.get_option_dict(command)['args'] = ("command line", nargs)
            if nargs is not None:
                return []

        return nargs

    def get_cmdline_options(self):
        """Return a '{cmd: {opt:val}}' map of all command-line options

        Option names are all long, but do not include the leading '--', and
        contain dashes rather than underscores.  If the option doesn't take
        an argument (e.g. '--quiet'), the 'val' is 'None'.

        Note that options provided by config files are intentionally excluded.
        """

        d = {}

        for cmd,opts in self.command_options.items():

            for opt,(src,val) in opts.items():

                if src != "command line":
                    continue

                opt = opt.replace('_','-')

                if val==0:
                    cmdobj = self.get_command_obj(cmd)
                    neg_opt = self.negative_opt.copy()
                    neg_opt.update(getattr(cmdobj,'negative_opt',{}))
                    for neg,pos in neg_opt.items():
                        if pos==opt:
                            opt=neg
                            val=None
                            break
                    else:
                        raise AssertionError("Shouldn't be able to get here")

                elif val==1:
                    val = None

                d.setdefault(cmd,{})[opt] = val

        return d

    def iter_distribution_names(self):
        """Yield all packages, modules, and extension names in distribution"""

        for pkg in self.packages or ():
            yield pkg

        for module in self.py_modules or ():
            yield module

        for ext in self.ext_modules or ():
            if isinstance(ext,tuple):
                name, buildinfo = ext
            else:
                name = ext.name
            if name.endswith('module'):
                name = name[:-6]
            yield name

    def handle_display_options(self, option_order):
        """If there were any non-global "display-only" options
        (--help-commands or the metadata display options) on the command
        line, display the requested info and return true; else return
        false.
        """
        import sys

        if sys.version_info < (3,) or self.help_commands:
            return _Distribution.handle_display_options(self, option_order)

        # Stdout may be StringIO (e.g. in tests)
        import io
        if not isinstance(sys.stdout, io.TextIOWrapper):
            return _Distribution.handle_display_options(self, option_order)

        # Don't wrap stdout if utf-8 is already the encoding. Provides
        #  workaround for #334.
        if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):
            return _Distribution.handle_display_options(self, option_order)

        # Print metadata in UTF-8 no matter the platform
        encoding = sys.stdout.encoding
        errors = sys.stdout.errors
        newline = sys.platform != 'win32' and '\n' or None
        line_buffering = sys.stdout.line_buffering

        sys.stdout = io.TextIOWrapper(
            sys.stdout.detach(), 'utf-8', errors, newline, line_buffering)
        try:
            return _Distribution.handle_display_options(self, option_order)
        finally:
            sys.stdout = io.TextIOWrapper(
                sys.stdout.detach(), encoding, errors, newline, line_buffering)

# Install it throughout the distutils
for module in distutils.dist, distutils.core, distutils.cmd:
    module.Distribution = Distribution

class Feature:
    """A subset of the distribution that can be excluded if unneeded/wanted

    Features are created using these keyword arguments:

      'description' -- a short, human readable description of the feature, to
         be used in error messages, and option help messages.

      'standard' -- if true, the feature is included by default if it is
         available on the current system.  Otherwise, the feature is only
         included if requested via a command line '--with-X' option, or if
         another included feature requires it.  The default setting is 'False'.

      'available' -- if true, the feature is available for installation on the
         current system.  The default setting is 'True'.

      'optional' -- if true, the feature's inclusion can be controlled from the
         command line, using the '--with-X' or '--without-X' options.  If
         false, the feature's inclusion status is determined automatically,
         based on 'availabile', 'standard', and whether any other feature
         requires it.  The default setting is 'True'.

      'require_features' -- a string or sequence of strings naming features
         that should also be included if this feature is included.  Defaults to
         empty list.  May also contain 'Require' objects that should be
         added/removed from the distribution.

      'remove' -- a string or list of strings naming packages to be removed
         from the distribution if this feature is *not* included.  If the
         feature *is* included, this argument is ignored.  This argument exists
         to support removing features that "crosscut" a distribution, such as
         defining a 'tests' feature that removes all the 'tests' subpackages
         provided by other features.  The default for this argument is an empty
         list.  (Note: the named package(s) or modules must exist in the base
         distribution when the 'setup()' function is initially called.)

      other keywords -- any other keyword arguments are saved, and passed to
         the distribution's 'include()' and 'exclude()' methods when the
         feature is included or excluded, respectively.  So, for example, you
         could pass 'packages=["a","b"]' to cause packages 'a' and 'b' to be
         added or removed from the distribution as appropriate.

    A feature must include at least one 'requires', 'remove', or other
    keyword argument.  Otherwise, it can't affect the distribution in any way.
    Note also that you can subclass 'Feature' to create your own specialized
    feature types that modify the distribution in other ways when included or
    excluded.  See the docstrings for the various methods here for more detail.
    Aside from the methods, the only feature attributes that distributions look
    at are 'description' and 'optional'.
    """
    def __init__(self, description, standard=False, available=True,
        optional=True, require_features=(), remove=(), **extras
    ):

        self.description = description
        self.standard = standard
        self.available = available
        self.optional = optional
        if isinstance(require_features,(str,Require)):
            require_features = require_features,

        self.require_features = [
            r for r in require_features if isinstance(r,str)
        ]
        er = [r for r in require_features if not isinstance(r,str)]
        if er: extras['require_features'] = er

        if isinstance(remove,str):
            remove = remove,
        self.remove = remove
        self.extras = extras

        if not remove and not require_features and not extras:
            raise DistutilsSetupError(
                "Feature %s: must define 'require_features', 'remove', or at least one"
                " of 'packages', 'py_modules', etc."
            )

    def include_by_default(self):
        """Should this feature be included by default?"""
        return self.available and self.standard

    def include_in(self,dist):

        """Ensure feature and its requirements are included in distribution

        You may override this in a subclass to perform additional operations on
        the distribution.  Note that this method may be called more than once
        per feature, and so should be idempotent.

        """

        if not self.available:
            raise DistutilsPlatformError(
                self.description+" is required,"
                "but is not available on this platform"
            )

        dist.include(**self.extras)

        for f in self.require_features:
            dist.include_feature(f)

    def exclude_from(self,dist):

        """Ensure feature is excluded from distribution

        You may override this in a subclass to perform additional operations on
        the distribution.  This method will be called at most once per
        feature, and only after all included features have been asked to
        include themselves.
        """

        dist.exclude(**self.extras)

        if self.remove:
            for item in self.remove:
                dist.exclude_package(item)

    def validate(self,dist):

        """Verify that feature makes sense in context of distribution

        This method is called by the distribution just before it parses its
        command line.  It checks to ensure that the 'remove' attribute, if any,
        contains only valid package/module names that are present in the base
        distribution when 'setup()' is called.  You may override it in a
        subclass to perform any other required validation of the feature
        against a target distribution.
        """

        for item in self.remove:
            if not dist.has_contents_for(item):
                raise DistutilsSetupError(
                    "%s wants to be able to remove %s, but the distribution"
                    " doesn't contain any packages or modules under %s"
                    % (self.description, item, item)
                )

def check_packages(dist, attr, value):
    for pkgname in value:
        if not re.match(r'\w+(\.\w+)*', pkgname):
            distutils.log.warn(
                "WARNING: %r not a valid package name; please use only"
                ".-separated package names in setup.py", pkgname
            )


"""Analysis of text input into executable blocks.

The main class in this module, :class:`InputSplitter`, is designed to break
input from either interactive, line-by-line environments or block-based ones,
into standalone blocks that can be executed by Python as 'single' statements
(thus triggering sys.displayhook).

A companion, :class:`IPythonInputSplitter`, provides the same functionality but
with full support for the extended IPython syntax (magics, system calls, etc).

For more details, see the class docstring below.

Syntax Transformations
----------------------

One of the main jobs of the code in this file is to apply all syntax
transformations that make up 'the IPython language', i.e. magics, shell
escapes, etc.  All transformations should be implemented as *fully stateless*
entities, that simply take one line as their input and return a line.
Internally for implementation purposes they may be a normal function or a
callable object, but the only input they receive will be a single line and they
should only return a line, without holding any data-dependent state between
calls.

As an example, the EscapedTransformer is a class so we can more clearly group
together the functionality of dispatching to individual functions based on the
starting escape character, but the only method for public use is its call
method.

ToDo
----

- Should we make push() actually raise an exception once push_accepts_more()
  returns False?

- Naming cleanups.  The tr_* names aren't the most elegant, though now they are
  at least just attributes of a class so not really very exposed.

- Think about the best way to support dynamic things: automagic, autocall,
  macros, etc.

- Think of a better heuristic for the application of the transforms in
  IPythonInputSplitter.push() than looking at the buffer ending in ':'.  Idea:
  track indentation change events (indent, dedent, nothing) and apply them only
  if the indentation went up, but not otherwise.

- Think of the cleanest way for supporting user-specified transformations (the
  user prefilters we had before).

Authors
-------

* Fernando Perez
* Brian Granger
"""
#-----------------------------------------------------------------------------
#  Copyright (C) 2010  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# stdlib
import ast
import codeop
import re
import sys
import tokenize
from StringIO import StringIO

# IPython modules
from IPython.core.splitinput import split_user_input, LineInfo
from IPython.utils.py3compat import cast_unicode

#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------

# The escape sequences that define the syntax transformations IPython will
# apply to user input.  These can NOT be just changed here: many regular
# expressions and other parts of the code may use their hardcoded values, and
# for all intents and purposes they constitute the 'IPython syntax', so they
# should be considered fixed.

ESC_SHELL  = '!'     # Send line to underlying system shell
ESC_SH_CAP = '!!'    # Send line to system shell and capture output
ESC_HELP   = '?'     # Find information about object
ESC_HELP2  = '??'    # Find extra-detailed information about object
ESC_MAGIC  = '%'     # Call magic function
ESC_MAGIC2 = '%%'    # Call cell-magic function
ESC_QUOTE  = ','     # Split args on whitespace, quote each as string and call
ESC_QUOTE2 = ';'     # Quote all args as a single string, call
ESC_PAREN  = '/'     # Call first argument with rest of line as arguments

ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
                 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
                 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]

#-----------------------------------------------------------------------------
# Utilities
#-----------------------------------------------------------------------------

# FIXME: These are general-purpose utilities that later can be moved to the
# general ward.  Kept here for now because we're being very strict about test
# coverage with this code, and this lets us ensure that we keep 100% coverage
# while developing.

# compiled regexps for autoindent management
dedent_re = re.compile('|'.join([
    r'^\s+raise(\s.*)?$', # raise statement (+ space + other stuff, maybe)
    r'^\s+raise\([^\)]*\).*$', # wacky raise with immediate open paren
    r'^\s+return(\s.*)?$', # normal return (+ space + other stuff, maybe)
    r'^\s+return\([^\)]*\).*$', # wacky return with immediate open paren
    r'^\s+pass\s*$' # pass (optionally followed by trailing spaces)
]))
ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')

# regexp to match pure comment lines so we don't accidentally insert 'if 1:'
# before pure comments
comment_line_re = re.compile('^\s*\#')

def num_ini_spaces(s):
    """Return the number of initial spaces in a string.

    Note that tabs are counted as a single space.  For now, we do *not* support
    mixing of tabs and spaces in the user's input.

    Parameters
    ----------
    s : string

    Returns
    -------
    n : int
    """

    ini_spaces = ini_spaces_re.match(s)
    if ini_spaces:
        return ini_spaces.end()
    else:
        return 0

def last_blank(src):
    """Determine if the input source ends in a blank.

    A blank is either a newline or a line consisting of whitespace.

    Parameters
    ----------
    src : string
      A single or multiline string.
    """
    if not src: return False
    ll  = src.splitlines()[-1]
    return (ll == '') or ll.isspace()

last_two_blanks_re = re.compile(r'\n\s*\n\s*$', re.MULTILINE)
last_two_blanks_re2 = re.compile(r'.+\n\s*\n\s+$', re.MULTILINE)

def last_two_blanks(src):
    """Determine if the input source ends in two blanks.

    A blank is either a newline or a line consisting of whitespace.

    Parameters
    ----------
    src : string
      A single or multiline string.
    """
    if not src: return False
    # The logic here is tricky: I couldn't get a regexp to work and pass all
    # the tests, so I took a different approach: split the source by lines,
    # grab the last two and prepend '###\n' as a stand-in for whatever was in
    # the body before the last two lines.  Then, with that structure, it's
    # possible to analyze with two regexps.  Not the most elegant solution, but
    # it works.  If anyone tries to change this logic, make sure to validate
    # the whole test suite first!
    new_src = '\n'.join(['###\n'] + src.splitlines()[-2:])
    return (bool(last_two_blanks_re.match(new_src)) or
            bool(last_two_blanks_re2.match(new_src)) )

def remove_comments(src):
    """Remove all comments from input source.

    Note: comments are NOT recognized inside of strings!

    Parameters
    ----------
    src : string
      A single or multiline input string.

    Returns
    -------
    String with all Python comments removed.
    """

    return re.sub('#.*', '', src)

def has_comment(src):
    """Indicate whether an input line has (i.e. ends in, or is) a comment.

    This uses tokenize, so it can distinguish comments from # inside strings.

    Parameters
    ----------
    src : string
      A single line input string.

    Returns
    -------
    Boolean: True if source has a comment.
    """
    readline = StringIO(src).readline
    toktypes = set()
    try:
        for t in tokenize.generate_tokens(readline):
            toktypes.add(t[0])
    except tokenize.TokenError:
        pass
    return(tokenize.COMMENT in toktypes)

def get_input_encoding():
    """Return the default standard input encoding.

    If sys.stdin has no encoding, 'ascii' is returned."""
    # There are strange environments for which sys.stdin.encoding is None. We
    # ensure that a valid encoding is returned.
    encoding = getattr(sys.stdin, 'encoding', None)
    if encoding is None:
        encoding = 'ascii'
    return encoding

#-----------------------------------------------------------------------------
# Classes and functions for normal Python syntax handling
#-----------------------------------------------------------------------------

class InputSplitter(object):
    """An object that can accumulate lines of Python source before execution.

    This object is designed to be fed python source line-by-line, using
       :meth:`push`. It will return on each push whether the currently pushed
       code could be executed already. In addition, it provides a method called
       :meth:`push_accepts_more` that can be used to query whether more input
       can be pushed into a single interactive block.

    This is a simple example of how an interactive terminal-based client can use
    this tool::

        isp = InputSplitter()
        while isp.push_accepts_more():
            indent = ' '*isp.indent_spaces
            prompt = '>>> ' + indent
            line = indent + raw_input(prompt)
            isp.push(line)
        print 'Input source was:\n', isp.source_reset(),
    """
    # Number of spaces of indentation computed from input that has been pushed
    # so far.  This is the attributes callers should query to get the current
    # indentation level, in order to provide auto-indent facilities.
    indent_spaces = 0
    # String, indicating the default input encoding.  It is computed by default
    # at initialization time via get_input_encoding(), but it can be reset by a
    # client with specific knowledge of the encoding.
    encoding = ''
    # String where the current full source input is stored, properly encoded.
    # Reading this attribute is the normal way of querying the currently pushed
    # source code, that has been properly encoded.
    source = ''
    # Code object corresponding to the current source.  It is automatically
    # synced to the source, so it can be queried at any time to obtain the code
    # object; it will be None if the source doesn't compile to valid Python.
    code = None
    # Input mode
    input_mode = 'line'

    # Private attributes

    # List with lines of input accumulated so far
    _buffer = None
    # Command compiler
    _compile = None
    # Mark when input has changed indentation all the way back to flush-left
    _full_dedent = False
    # Boolean indicating whether the current block is complete
    _is_complete = None

    def __init__(self, input_mode=None):
        """Create a new InputSplitter instance.

        Parameters
        ----------
        input_mode : str

          One of ['line', 'cell']; default is 'line'.

       The input_mode parameter controls how new inputs are used when fed via
       the :meth:`push` method:

       - 'line': meant for line-oriented clients, inputs are appended one at a
         time to the internal buffer and the whole buffer is compiled.

       - 'cell': meant for clients that can edit multi-line 'cells' of text at
          a time.  A cell can contain one or more blocks that can be compile in
          'single' mode by Python.  In this mode, each new input new input
          completely replaces all prior inputs.  Cell mode is thus equivalent
          to prepending a full reset() to every push() call.
        """
        self._buffer = []
        self._compile = codeop.CommandCompiler()
        self.encoding = get_input_encoding()
        self.input_mode = InputSplitter.input_mode if input_mode is None \
                          else input_mode

    def reset(self):
        """Reset the input buffer and associated state."""
        self.indent_spaces = 0
        self._buffer[:] = []
        self.source = ''
        self.code = None
        self._is_complete = False
        self._full_dedent = False

    def source_reset(self):
        """Return the input source and perform a full reset.
        """
        out = self.source
        self.reset()
        return out

    def push(self, lines):
        """Push one or more lines of input.

        This stores the given lines and returns a status code indicating
        whether the code forms a complete Python block or not.

        Any exceptions generated in compilation are swallowed, but if an
        exception was produced, the method returns True.

        Parameters
        ----------
        lines : string
          One or more lines of Python input.

        Returns
        -------
        is_complete : boolean
          True if the current input source (the result of the current input
          plus prior inputs) forms a complete Python execution block.  Note that
          this value is also stored as a private attribute (``_is_complete``), so it
          can be queried at any time.
        """
        if self.input_mode == 'cell':
            self.reset()

        self._store(lines)
        source = self.source

        # Before calling _compile(), reset the code object to None so that if an
        # exception is raised in compilation, we don't mislead by having
        # inconsistent code/source attributes.
        self.code, self._is_complete = None, None

        # Honor termination lines properly
        if source.rstrip().endswith('\\'):
            return False

        self._update_indent(lines)
        try:
            self.code = self._compile(source, symbol="exec")
        # Invalid syntax can produce any of a number of different errors from
        # inside the compiler, so we have to catch them all.  Syntax errors
        # immediately produce a 'ready' block, so the invalid Python can be
        # sent to the kernel for evaluation with possible ipython
        # special-syntax conversion.
        except (SyntaxError, OverflowError, ValueError, TypeError,
                MemoryError):
            self._is_complete = True
        else:
            # Compilation didn't produce any exceptions (though it may not have
            # given a complete code object)
            self._is_complete = self.code is not None

        return self._is_complete

    def push_accepts_more(self):
        """Return whether a block of interactive input can accept more input.

        This method is meant to be used by line-oriented frontends, who need to
        guess whether a block is complete or not based solely on prior and
        current input lines.  The InputSplitter considers it has a complete
        interactive block and will not accept more input only when either a
        SyntaxError is raised, or *all* of the following are true:

        1. The input compiles to a complete statement.

        2. The indentation level is flush-left (because if we are indented,
           like inside a function definition or for loop, we need to keep
           reading new input).

        3. There is one extra line consisting only of whitespace.

        Because of condition #3, this method should be used only by
        *line-oriented* frontends, since it means that intermediate blank lines
        are not allowed in function definitions (or any other indented block).

        If the current input produces a syntax error, this method immediately
        returns False but does *not* raise the syntax error exception, as
        typically clients will want to send invalid syntax to an execution
        backend which might convert the invalid syntax into valid Python via
        one of the dynamic IPython mechanisms.
        """

        # With incomplete input, unconditionally accept more
        if not self._is_complete:
            return True

        # If we already have complete input and we're flush left, the answer
        # depends.  In line mode, if there hasn't been any indentation,
        # that's it. If we've come back from some indentation, we need
        # the blank final line to finish.
        # In cell mode, we need to check how many blocks the input so far
        # compiles into, because if there's already more than one full
        # independent block of input, then the client has entered full
        # 'cell' mode and is feeding lines that each is complete.  In this
        # case we should then keep accepting. The Qt terminal-like console
        # does precisely this, to provide the convenience of terminal-like
        # input of single expressions, but allowing the user (with a
        # separate keystroke) to switch to 'cell' mode and type multiple
        # expressions in one shot.
        if self.indent_spaces==0:
            if self.input_mode=='line':
                if not self._full_dedent:
                    return False
            else:
                try:
                    code_ast = ast.parse(u''.join(self._buffer))
                except Exception:
                    return False
                else:
                    if len(code_ast.body) == 1:
                        return False

        # When input is complete, then termination is marked by an extra blank
        # line at the end.
        last_line = self.source.splitlines()[-1]
        return bool(last_line and not last_line.isspace())

    #------------------------------------------------------------------------
    # Private interface
    #------------------------------------------------------------------------

    def _find_indent(self, line):
        """Compute the new indentation level for a single line.

        Parameters
        ----------
        line : str
          A single new line of non-whitespace, non-comment Python input.

        Returns
        -------
        indent_spaces : int
          New value for the indent level (it may be equal to self.indent_spaces
        if indentation doesn't change.

        full_dedent : boolean
          Whether the new line causes a full flush-left dedent.
        """
        indent_spaces = self.indent_spaces
        full_dedent = self._full_dedent

        inisp = num_ini_spaces(line)
        if inisp < indent_spaces:
            indent_spaces = inisp
            if indent_spaces <= 0:
                #print 'Full dedent in text',self.source # dbg
                full_dedent = True

        if line.rstrip()[-1] == ':':
            indent_spaces += 4
        elif dedent_re.match(line):
            indent_spaces -= 4
            if indent_spaces <= 0:
                full_dedent = True

        # Safety
        if indent_spaces < 0:
            indent_spaces = 0
            #print 'safety' # dbg

        return indent_spaces, full_dedent

    def _update_indent(self, lines):
        for line in remove_comments(lines).splitlines():
            if line and not line.isspace():
                self.indent_spaces, self._full_dedent = self._find_indent(line)

    def _store(self, lines, buffer=None, store='source'):
        """Store one or more lines of input.

        If input lines are not newline-terminated, a newline is automatically
        appended."""

        if buffer is None:
            buffer = self._buffer

        if lines.endswith('\n'):
            buffer.append(lines)
        else:
            buffer.append(lines+'\n')
        setattr(self, store, self._set_source(buffer))

    def _set_source(self, buffer):
        return u''.join(buffer)

#-----------------------------------------------------------------------------
# Functions and classes for IPython-specific syntactic support
#-----------------------------------------------------------------------------

# The escaped translators ALL receive a line where their own escape has been
# stripped.  Only '?' is valid at the end of the line, all others can only be
# placed at the start.

# Transformations of the special syntaxes that don't rely on an explicit escape
# character but instead on patterns on the input line

# The core transformations are implemented as standalone functions that can be
# tested and validated in isolation.  Each of these uses a regexp, we
# pre-compile these and keep them close to each function definition for clarity

_assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
                               r'\s*=\s*!\s*(?P<cmd>.*)')

def transform_assign_system(line):
    """Handle the `files = !ls` syntax."""
    m = _assign_system_re.match(line)
    if m is not None:
        cmd = m.group('cmd')
        lhs = m.group('lhs')
        new_line = '%s = get_ipython().getoutput(%r)' % (lhs, cmd)
        return new_line
    return line

_assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
                               r'\s*=\s*%\s*(?P<cmd>.*)')

def transform_assign_magic(line):
    """Handle the `a = %who` syntax."""
    m = _assign_magic_re.match(line)
    if m is not None:
        cmd = m.group('cmd')
        lhs = m.group('lhs')
        new_line = '%s = get_ipython().magic(%r)' % (lhs, cmd)
        return new_line
    return line

_classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')

def transform_classic_prompt(line):
    """Handle inputs that start with '>>> ' syntax."""

    if not line or line.isspace():
        return line
    m = _classic_prompt_re.match(line)
    if m:
        return line[len(m.group(0)):]
    else:
        return line

_ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')

def transform_ipy_prompt(line):
    """Handle inputs that start classic IPython prompt syntax."""

    if not line or line.isspace():
        return line
    #print 'LINE:  %r' % line # dbg
    m = _ipy_prompt_re.match(line)
    if m:
        #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
        return line[len(m.group(0)):]
    else:
        return line

def _make_help_call(target, esc, lspace, next_input=None):
    """Prepares a pinfo(2)/psearch call from a target name and the escape
    (i.e. ? or ??)"""
    method  = 'pinfo2' if esc == '??' \
                else 'psearch' if '*' in target \
                else 'pinfo'
    arg = " ".join([method, target])
    if next_input is None:
        return '%sget_ipython().magic(%r)' % (lspace, arg)
    else:
        return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
           (lspace, next_input, arg)

_initial_space_re = re.compile(r'\s*')

_help_end_re = re.compile(r"""(%{0,2}
                              [a-zA-Z_*][\w*]*        # Variable name
                              (\.[a-zA-Z_*][\w*]*)*   # .etc.etc
                              )
                              (\?\??)$                # ? or ??""",
                              re.VERBOSE)

def transform_help_end(line):
    """Translate lines with ?/?? at the end"""
    m = _help_end_re.search(line)
    if m is None or has_comment(line):
        return line
    target = m.group(1)
    esc = m.group(3)
    lspace = _initial_space_re.match(line).group(0)

    # If we're mid-command, put it back on the next prompt for the user.
    next_input = line.rstrip('?') if line.strip() != m.group(0) else None

    return _make_help_call(target, esc, lspace, next_input)

class EscapedTransformer(object):
    """Class to transform lines that are explicitly escaped out."""

    def __init__(self):
        tr = { ESC_SHELL  : self._tr_system,
               ESC_SH_CAP : self._tr_system2,
               ESC_HELP   : self._tr_help,
               ESC_HELP2  : self._tr_help,
               ESC_MAGIC  : self._tr_magic,
               ESC_QUOTE  : self._tr_quote,
               ESC_QUOTE2 : self._tr_quote2,
               ESC_PAREN  : self._tr_paren }
        self.tr = tr

    # Support for syntax transformations that use explicit escapes typed by the
    # user at the beginning of a line
    @staticmethod
    def _tr_system(line_info):
        "Translate lines escaped with: !"
        cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
        return '%sget_ipython().system(%r)' % (line_info.pre, cmd)

    @staticmethod
    def _tr_system2(line_info):
        "Translate lines escaped with: !!"
        cmd = line_info.line.lstrip()[2:]
        return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)

    @staticmethod
    def _tr_help(line_info):
        "Translate lines escaped with: ?/??"
        # A naked help line should just fire the intro help screen
        if not line_info.line[1:]:
            return 'get_ipython().show_usage()'

        return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)

    @staticmethod
    def _tr_magic(line_info):
        "Translate lines escaped with: %"
        tpl = '%sget_ipython().magic(%r)'
        cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
        return tpl % (line_info.pre, cmd)

    @staticmethod
    def _tr_quote(line_info):
        "Translate lines escaped with: ,"
        return '%s%s("%s")' % (line_info.pre, line_info.ifun,
                             '", "'.join(line_info.the_rest.split()) )

    @staticmethod
    def _tr_quote2(line_info):
        "Translate lines escaped with: ;"
        return '%s%s("%s")' % (line_info.pre, line_info.ifun,
                               line_info.the_rest)

    @staticmethod
    def _tr_paren(line_info):
        "Translate lines escaped with: /"
        return '%s%s(%s)' % (line_info.pre, line_info.ifun,
                             ", ".join(line_info.the_rest.split()))

    def __call__(self, line):
        """Class to transform lines that are explicitly escaped out.

        This calls the above _tr_* static methods for the actual line
        translations."""

        # Empty lines just get returned unmodified
        if not line or line.isspace():
            return line

        # Get line endpoints, where the escapes can be
        line_info = LineInfo(line)

        if not line_info.esc in self.tr:
            # If we don't recognize the escape, don't modify the line
            return line

        return self.tr[line_info.esc](line_info)

# A function-looking object to be used by the rest of the code.  The purpose of
# the class in this case is to organize related functionality, more than to
# manage state.
transform_escaped = EscapedTransformer()

class IPythonInputSplitter(InputSplitter):
    """An input splitter that recognizes all of IPython's special syntax."""

    # String with raw, untransformed input.
    source_raw = ''

    # Flag to track when we're in the middle of processing a cell magic, since
    # the logic has to change.  In that case, we apply no transformations at
    # all.
    processing_cell_magic = False

    # Storage for all blocks of input that make up a cell magic
    cell_magic_parts = []

    # Private attributes

    # List with lines of raw input accumulated so far.
    _buffer_raw = None

    def __init__(self, input_mode=None):
        super(IPythonInputSplitter, self).__init__(input_mode)
        self._buffer_raw = []
        self._validate = True

    def reset(self):
        """Reset the input buffer and associated state."""
        super(IPythonInputSplitter, self).reset()
        self._buffer_raw[:] = []
        self.source_raw = ''
        self.cell_magic_parts = []
        self.processing_cell_magic = False

    def source_raw_reset(self):
        """Return input and raw source and perform a full reset.
        """
        out = self.source
        out_r = self.source_raw
        self.reset()
        return out, out_r

    def push_accepts_more(self):
        if self.processing_cell_magic:
            return not self._is_complete
        else:
            return super(IPythonInputSplitter, self).push_accepts_more()

    def _handle_cell_magic(self, lines):
        """Process lines when they start with %%, which marks cell magics.
        """
        self.processing_cell_magic = True
        first, _, body = lines.partition('\n')
        magic_name, _, line = first.partition(' ')
        magic_name = magic_name.lstrip(ESC_MAGIC)
        # We store the body of the cell and create a call to a method that
        # will use this stored value. This is ugly, but it's a first cut to
        # get it all working, as right now changing the return API of our
        # methods would require major refactoring.
        self.cell_magic_parts = [body]
        tpl = 'get_ipython()._run_cached_cell_magic(%r, %r)'
        tlines = tpl % (magic_name, line)
        self._store(tlines)
        self._store(lines, self._buffer_raw, 'source_raw')
        # We can actually choose whether to allow for single blank lines here
        # during input for clients that use cell mode to decide when to stop
        # pushing input (currently only the Qt console).
        # My first implementation did that, and then I realized it wasn't
        # consistent with the terminal behavior, so I've reverted it to one
        # line.  But I'm leaving it here so we can easily test both behaviors,
        # I kind of liked having full blank lines allowed in the cell magics...
        #self._is_complete = last_two_blanks(lines)
        self._is_complete = last_blank(lines)
        return self._is_complete

    def _line_mode_cell_append(self, lines):
        """Append new content for a cell magic in line mode.
        """
        # Only store the raw input.  Lines beyond the first one are only only
        # stored for history purposes; for execution the caller will grab the
        # magic pieces from cell_magic_parts and will assemble the cell body
        self._store(lines, self._buffer_raw, 'source_raw')
        self.cell_magic_parts.append(lines)
        # Find out if the last stored block has a whitespace line as its
        # last line and also this line is whitespace, case in which we're
        # done (two contiguous blank lines signal termination).  Note that
        # the storage logic *enforces* that every stored block is
        # newline-terminated, so we grab everything but the last character
        # so we can have the body of the block alone.
        last_block = self.cell_magic_parts[-1]
        self._is_complete = last_blank(last_block) and lines.isspace()
        return self._is_complete

    def transform_cell(self, cell):
        """Process and translate a cell of input.
        """
        self.reset()
        self.push(cell)
        return self.source_reset()

    def push(self, lines):
        """Push one or more lines of IPython input.

        This stores the given lines and returns a status code indicating
        whether the code forms a complete Python block or not, after processing
        all input lines for special IPython syntax.

        Any exceptions generated in compilation are swallowed, but if an
        exception was produced, the method returns True.

        Parameters
        ----------
        lines : string
          One or more lines of Python input.

        Returns
        -------
        is_complete : boolean
          True if the current input source (the result of the current input
        plus prior inputs) forms a complete Python execution block.  Note that
        this value is also stored as a private attribute (_is_complete), so it
        can be queried at any time.
        """
        if not lines:
            return super(IPythonInputSplitter, self).push(lines)

        # We must ensure all input is pure unicode
        lines = cast_unicode(lines, self.encoding)

        # If the entire input block is a cell magic, return after handling it
        # as the rest of the transformation logic should be skipped.
        if lines.startswith('%%') and not \
          (len(lines.splitlines()) == 1 and lines.strip().endswith('?')):
            return self._handle_cell_magic(lines)

        # In line mode, a cell magic can arrive in separate pieces
        if self.input_mode == 'line' and self.processing_cell_magic:
            return self._line_mode_cell_append(lines)

        # The rest of the processing is for 'normal' content, i.e. IPython
        # source that we process through our transformations pipeline.
        lines_list = lines.splitlines()

        transforms = [transform_ipy_prompt, transform_classic_prompt,
                      transform_help_end, transform_escaped,
                      transform_assign_system, transform_assign_magic]

        # Transform logic
        #
        # We only apply the line transformers to the input if we have either no
        # input yet, or complete input, or if the last line of the buffer ends
        # with ':' (opening an indented block).  This prevents the accidental
        # transformation of escapes inside multiline expressions like
        # triple-quoted strings or parenthesized expressions.
        #
        # The last heuristic, while ugly, ensures that the first line of an
        # indented block is correctly transformed.
        #
        # FIXME: try to find a cleaner approach for this last bit.

        # If we were in 'block' mode, since we're going to pump the parent
        # class by hand line by line, we need to temporarily switch out to
        # 'line' mode, do a single manual reset and then feed the lines one
        # by one.  Note that this only matters if the input has more than one
        # line.
        changed_input_mode = False

        if self.input_mode == 'cell':
            self.reset()
            changed_input_mode = True
            saved_input_mode = 'cell'
            self.input_mode = 'line'

        # Store raw source before applying any transformations to it.  Note
        # that this must be done *after* the reset() call that would otherwise
        # flush the buffer.
        self._store(lines, self._buffer_raw, 'source_raw')

        try:
            push = super(IPythonInputSplitter, self).push
            buf = self._buffer
            for line in lines_list:
                if self._is_complete or not buf or \
                       (buf and buf[-1].rstrip().endswith((':', ','))):
                    for f in transforms:
                        line = f(line)

                out = push(line)
        finally:
            if changed_input_mode:
                self.input_mode = saved_input_mode
        return out


# encoding: utf-8
"""
The IPython Core Notification Center.

See docs/source/development/notification_blueprint.txt for an overview of the
notification module.

Authors:

* Barry Wark
* Brian Granger
"""

#-----------------------------------------------------------------------------
#  Copyright (C) 2008-2011  The IPython Development Team
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------

class NotificationError(Exception):
    pass

class NotificationCenter(object):
    """Synchronous notification center.

    Examples
    --------
    Here is a simple example of how to use this::

        import IPython.util.notification as notification
        def callback(ntype, theSender, args={}):
            print ntype,theSender,args

        notification.sharedCenter.add_observer(callback, 'NOTIFICATION_TYPE', None)
        notification.sharedCenter.post_notification('NOTIFICATION_TYPE', object()) # doctest:+ELLIPSIS
        NOTIFICATION_TYPE ...
    """
    def __init__(self):
        super(NotificationCenter, self).__init__()
        self._init_observers()

    def _init_observers(self):
        """Initialize observer storage"""

        self.registered_types = set() #set of types that are observed
        self.registered_senders = set() #set of senders that are observed
        self.observers = {} #map (type,sender) => callback (callable)

    def post_notification(self, ntype, sender, *args, **kwargs):
        """Post notification to all registered observers.

        The registered callback will be called as::

            callback(ntype, sender, *args, **kwargs)

        Parameters
        ----------
        ntype : hashable
            The notification type.
        sender : hashable
            The object sending the notification.
        *args : tuple
            The positional arguments to be passed to the callback.
        **kwargs : dict
            The keyword argument to be passed to the callback.

        Notes
        -----
        * If no registered observers, performance is O(1).
        * Notificaiton order is undefined.
        * Notifications are posted synchronously.
        """

        if(ntype==None or sender==None):
            raise NotificationError(
                "Notification type and sender are required.")

        # If there are no registered observers for the type/sender pair
        if((ntype not in self.registered_types and
                None not in self.registered_types) or
            (sender not in self.registered_senders and
                None not in self.registered_senders)):
            return

        for o in self._observers_for_notification(ntype, sender):
            o(ntype, sender, *args, **kwargs)

    def _observers_for_notification(self, ntype, sender):
        """Find all registered observers that should recieve notification"""

        keys = (
                   (ntype,sender),
                   (ntype, None),
                   (None, sender),
                   (None,None)
               )

        obs = set()
        for k in keys:
            obs.update(self.observers.get(k, set()))

        return obs

    def add_observer(self, callback, ntype, sender):
        """Add an observer callback to this notification center.

        The given callback will be called upon posting of notifications of
        the given type/sender and will receive any additional arguments passed
        to post_notification.

        Parameters
        ----------
        callback : callable
            The callable that will be called by :meth:`post_notification`
            as ``callback(ntype, sender, *args, **kwargs)
        ntype : hashable
            The notification type. If None, all notifications from sender
            will be posted.
        sender : hashable
            The notification sender. If None, all notifications of ntype
            will be posted.
        """
        assert(callback != None)
        self.registered_types.add(ntype)
        self.registered_senders.add(sender)
        self.observers.setdefault((ntype,sender), set()).add(callback)

    def remove_all_observers(self):
        """Removes all observers from this notification center"""

        self._init_observers()

shared_center = NotificationCenter()


# -*- coding: utf-8 -*-
"""Manage background (threaded) jobs conveniently from an interactive shell.

This module provides a BackgroundJobManager class.  This is the main class
meant for public usage, it implements an object which can create and manage
new background jobs.

It also provides the actual job classes managed by these BackgroundJobManager
objects, see their docstrings below.

This system was inspired by discussions with B. Granger and the
BackgroundCommand class described in the book Python Scripting for
Computational Science, by H. P. Langtangen:

http://folk.uio.no/hpl/scripting

(although ultimately no code from this text was used, as IPython's system is a
separate implementation).

An example notebook is provided in our documentation illustrating interactive
use of the system.
"""

#*****************************************************************************
#       Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
#
#  Distributed under the terms of the BSD License.  The full license is in
#  the file COPYING, distributed as part of this software.
#*****************************************************************************

# Code begins
import sys
import threading

from IPython.core.ultratb import AutoFormattedTB
from IPython.utils.warn import warn, error

class BackgroundJobManager(object):
    """Class to manage a pool of backgrounded threaded jobs.

    Below, we assume that 'jobs' is a BackgroundJobManager instance.

    Usage summary (see the method docstrings for details):

      jobs.new(...) -> start a new job

      jobs() or jobs.status() -> print status summary of all jobs

      jobs[N] -> returns job number N.

      foo = jobs[N].result -> assign to variable foo the result of job N

      jobs[N].traceback() -> print the traceback of dead job N

      jobs.remove(N) -> remove (finished) job N

      jobs.flush() -> remove all finished jobs

    As a convenience feature, BackgroundJobManager instances provide the
    utility result and traceback methods which retrieve the corresponding
    information from the jobs list:

      jobs.result(N) <--> jobs[N].result
      jobs.traceback(N) <--> jobs[N].traceback()

    While this appears minor, it allows you to use tab completion
    interactively on the job manager instance.
    """

    def __init__(self):
        # Lists for job management, accessed via a property to ensure they're
        # up to date.x
        self._running  = []
        self._completed = []
        self._dead = []
        # A dict of all jobs, so users can easily access any of them
        self.all = {}
        # For reporting
        self._comp_report = []
        self._dead_report = []
        # Store status codes locally for fast lookups
        self._s_created   = BackgroundJobBase.stat_created_c
        self._s_running   = BackgroundJobBase.stat_running_c
        self._s_completed = BackgroundJobBase.stat_completed_c
        self._s_dead      = BackgroundJobBase.stat_dead_c

    @property
    def running(self):
        self._update_status()
        return self._running

    @property
    def dead(self):
        self._update_status()
        return self._dead

    @property
    def completed(self):
        self._update_status()
        return self._completed

    def new(self, func_or_exp, *args, **kwargs):
        """Add a new background job and start it in a separate thread.

        There are two types of jobs which can be created:

        1. Jobs based on expressions which can be passed to an eval() call.
        The expression must be given as a string.  For example:

          job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])

        The given expression is passed to eval(), along with the optional
        global/local dicts provided.  If no dicts are given, they are
        extracted automatically from the caller's frame.

        A Python statement is NOT a valid eval() expression.  Basically, you
        can only use as an eval() argument something which can go on the right
        of an '=' sign and be assigned to a variable.

        For example,"print 'hello'" is not valid, but '2+3' is.

        2. Jobs given a function object, optionally passing additional
        positional arguments:

          job_manager.new(myfunc, x, y)

        The function is called with the given arguments.

        If you need to pass keyword arguments to your function, you must
        supply them as a dict named kw:

          job_manager.new(myfunc, x, y, kw=dict(z=1))

        The reason for this assymmetry is that the new() method needs to
        maintain access to its own keywords, and this prevents name collisions
        between arguments to new() and arguments to your own functions.

        In both cases, the result is stored in the job.result field of the
        background job object.

        You can set `daemon` attribute of the thread by giving the keyword
        argument `daemon`.

        Notes and caveats:

        1. All threads running share the same standard output.  Thus, if your
        background jobs generate output, it will come out on top of whatever
        you are currently writing.  For this reason, background jobs are best
        used with silent functions which simply return their output.

        2. Threads also all work within the same global namespace, and this
        system does not lock interactive variables.  So if you send job to the
        background which operates on a mutable object for a long time, and
        start modifying that same mutable object interactively (or in another
        backgrounded job), all sorts of bizarre behaviour will occur.

        3. If a background job is spending a lot of time inside a C extension
        module which does not release the Python Global Interpreter Lock
        (GIL), this will block the IPython prompt.  This is simply because the
        Python interpreter can only switch between threads at Python
        bytecodes.  While the execution is inside C code, the interpreter must
        simply wait unless the extension module releases the GIL.

        4. There is no way, due to limitations in the Python threads library,
        to kill a thread once it has started."""

        if callable(func_or_exp):
            kw  = kwargs.get('kw',{})
            job = BackgroundJobFunc(func_or_exp,*args,**kw)
        elif isinstance(func_or_exp, basestring):
            if not args:
                frame = sys._getframe(1)
                glob, loc = frame.f_globals, frame.f_locals
            elif len(args)==1:
                glob = loc = args[0]
            elif len(args)==2:
                glob,loc = args
            else:
                raise ValueError(
                      'Expression jobs take at most 2 args (globals,locals)')
            job = BackgroundJobExpr(func_or_exp, glob, loc)
        else:
            raise TypeError('invalid args for new job')

        if kwargs.get('daemon', False):
            job.daemon = True
        job.num = len(self.all)+1 if self.all else 0
        self.running.append(job)
        self.all[job.num] = job
        print 'Starting job # %s in a separate thread.' % job.num
        job.start()
        return job

    def __getitem__(self, job_key):
        num = job_key if isinstance(job_key, int) else job_key.num
        return self.all[num]

    def __call__(self):
        """An alias to self.status(),

        This allows you to simply call a job manager instance much like the
        Unix `jobs` shell command."""

        return self.status()

    def _update_status(self):
        """Update the status of the job lists.

        This method moves finished jobs to one of two lists:
          - self.completed: jobs which completed successfully
          - self.dead: jobs which finished but died.

        It also copies those jobs to corresponding _report lists.  These lists
        are used to report jobs completed/dead since the last update, and are
        then cleared by the reporting function after each call."""

        # Status codes
        srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
        # State lists, use the actual lists b/c the public names are properties
        # that call this very function on access
        running, completed, dead = self._running, self._completed, self._dead

        # Now, update all state lists
        for num, job in enumerate(running):
            stat = job.stat_code
            if stat == srun:
                continue
            elif stat == scomp:
                completed.append(job)
                self._comp_report.append(job)
                running[num] = False
            elif stat == sdead:
                dead.append(job)
                self._dead_report.append(job)
                running[num] = False
        # Remove dead/completed jobs from running list
        running[:] = filter(None, running)

    def _group_report(self,group,name):
        """Report summary for a given job group.

        Return True if the group had any elements."""

        if group:
            print '%s jobs:' % name
            for job in group:
                print '%s : %s' % (job.num,job)
            print
            return True

    def _group_flush(self,group,name):
        """Flush a given job group

        Return True if the group had any elements."""

        njobs = len(group)
        if njobs:
            plural = {1:''}.setdefault(njobs,'s')
            print 'Flushing %s %s job%s.' % (njobs,name,plural)
            group[:] = []
            return True

    def _status_new(self):
        """Print the status of newly finished jobs.

        Return True if any new jobs are reported.

        This call resets its own state every time, so it only reports jobs
        which have finished since the last time it was called."""

        self._update_status()
        new_comp = self._group_report(self._comp_report, 'Completed')
        new_dead = self._group_report(self._dead_report,
                                      'Dead, call jobs.traceback() for details')
        self._comp_report[:] = []
        self._dead_report[:] = []
        return new_comp or new_dead

    def status(self,verbose=0):
        """Print a status of all jobs currently being managed."""

        self._update_status()
        self._group_report(self.running,'Running')
        self._group_report(self.completed,'Completed')
        self._group_report(self.dead,'Dead')
        # Also flush the report queues
        self._comp_report[:] = []
        self._dead_report[:] = []

    def remove(self,num):
        """Remove a finished (completed or dead) job."""

        try:
            job = self.all[num]
        except KeyError:
            error('Job #%s not found' % num)
        else:
            stat_code = job.stat_code
            if stat_code == self._s_running:
                error('Job #%s is still running, it can not be removed.' % num)
                return
            elif stat_code == self._s_completed:
                self.completed.remove(job)
            elif stat_code == self._s_dead:
                self.dead.remove(job)

    def flush(self):
        """Flush all finished jobs (completed and dead) from lists.

        Running jobs are never flushed.

        It first calls _status_new(), to update info. If any jobs have
        completed since the last _status_new() call, the flush operation
        aborts."""

        # Remove the finished jobs from the master dict
        alljobs = self.all
        for job in self.completed+self.dead:
            del(alljobs[job.num])

        # Now flush these lists completely
        fl_comp = self._group_flush(self.completed, 'Completed')
        fl_dead = self._group_flush(self.dead, 'Dead')
        if not (fl_comp or fl_dead):
            print 'No jobs to flush.'

    def result(self,num):
        """result(N) -> return the result of job N."""
        try:
            return self.all[num].result
        except KeyError:
            error('Job #%s not found' % num)

    def _traceback(self, job):
        num = job if isinstance(job, int) else job.num
        try:
            self.all[num].traceback()
        except KeyError:
            error('Job #%s not found' % num)

    def traceback(self, job=None):
        if job is None:
            self._update_status()
            for deadjob in self.dead:
                print "Traceback for: %r" % deadjob
                self._traceback(deadjob)
                print
        else:
            self._traceback(job)

class BackgroundJobBase(threading.Thread):
    """Base class to build BackgroundJob classes.

    The derived classes must implement:

    - Their own __init__, since the one here raises NotImplementedError.  The
    derived constructor must call self._init() at the end, to provide common
    initialization.

    - A strform attribute used in calls to __str__.

    - A call() method, which will make the actual execution call and must
    return a value to be held in the 'result' field of the job object."""

    # Class constants for status, in string and as numerical codes (when
    # updating jobs lists, we don't want to do string comparisons).  This will
    # be done at every user prompt, so it has to be as fast as possible
    stat_created   = 'Created'; stat_created_c = 0
    stat_running   = 'Running'; stat_running_c = 1
    stat_completed = 'Completed'; stat_completed_c = 2
    stat_dead      = 'Dead (Exception), call jobs.traceback() for details'
    stat_dead_c = -1

    def __init__(self):
        raise NotImplementedError, \
              "This class can not be instantiated directly."

    def _init(self):
        """Common initialization for all BackgroundJob objects"""

        for attr in ['call','strform']:
            assert hasattr(self,attr), "Missing attribute <%s>" % attr

        # The num tag can be set by an external job manager
        self.num = None

        self.status    = BackgroundJobBase.stat_created
        self.stat_code = BackgroundJobBase.stat_created_c
        self.finished  = False
        self.result    = '<BackgroundJob has not completed>'

        # reuse the ipython traceback handler if we can get to it, otherwise
        # make a new one
        try:
            make_tb = get_ipython().InteractiveTB.text
        except:
            make_tb = AutoFormattedTB(mode = 'Context',
                                      color_scheme='NoColor',
                                      tb_offset = 1).text
        # Note that the actual API for text() requires the three args to be
        # passed in, so we wrap it in a simple lambda.
        self._make_tb = lambda : make_tb(None, None, None)

        # Hold a formatted traceback if one is generated.
        self._tb = None

        threading.Thread.__init__(self)

    def __str__(self):
        return self.strform

    def __repr__(self):
        return '<BackgroundJob #%d: %s>' % (self.num, self.strform)

    def traceback(self):
        print self._tb

    def run(self):
        try:
            self.status    = BackgroundJobBase.stat_running
            self.stat_code = BackgroundJobBase.stat_running_c
            self.result    = self.call()
        except:
            self.status    = BackgroundJobBase.stat_dead
            self.stat_code = BackgroundJobBase.stat_dead_c
            self.finished  = None
            self.result    = ('<BackgroundJob died, call jobs.traceback() for details>')
            self._tb       = self._make_tb()
        else:
            self.status    = BackgroundJobBase.stat_completed
            self.stat_code = BackgroundJobBase.stat_completed_c
            self.finished  = True

class BackgroundJobExpr(BackgroundJobBase):
    """Evaluate an expression as a background job (uses a separate thread)."""

    def __init__(self, expression, glob=None, loc=None):
        """Create a new job from a string which can be fed to eval().

        global/locals dicts can be provided, which will be passed to the eval
        call."""

        # fail immediately if the given expression can't be compiled
        self.code = compile(expression,'<BackgroundJob compilation>','eval')

        glob = {} if glob is None else glob
        loc = {} if loc is None else loc
        self.expression = self.strform = expression
        self.glob = glob
        self.loc = loc
        self._init()

    def call(self):
        return eval(self.code,self.glob,self.loc)

class BackgroundJobFunc(BackgroundJobBase):
    """Run a function call as a background job (uses a separate thread)."""

    def __init__(self, func, *args, **kwargs):
        """Create a new job from a callable object.

        Any positional arguments and keyword args given to this constructor
        after the initial callable are passed directly to it."""

        if not callable(func):
            raise TypeError(
                'first argument to BackgroundJobFunc must be callable')

        self.func = func
        self.args = args
        self.kwargs = kwargs
        # The string form will only include the function passed, because
        # generating string representations of the arguments is a potentially
        # _very_ expensive operation (e.g. with large arrays).
        self.strform = str(func)
        self._init()

    def call(self):
        return self.func(*self.args, **self.kwargs)