def vim_quickfix_file():<EOL><INDENT>t = tempfile.NamedTemporaryFile()<EOL>t.write('<STR_LIT>' % (filename,linenum,column,msg))<EOL>t.flush()<EOL>return t<EOL><DEDENT>if os.path.basename(self.editor) != '<STR_LIT>':<EOL><INDENT>self.hooks.editor(filename,linenum)<EOL>return<EOL><DEDENT>t = vim_quickfix_file()<EOL>try:<EOL><INDENT>if os.system('<STR_LIT>' + t.name):<EOL><INDENT>raise TryNext()<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>t.close()<EOL><DEDENT>

Open the editor at the given filename, linenumber, column and
    show an error message. This is used for correcting syntax errors.
    The current implementation only has special support for the VIM editor,
    and falls back on the 'editor' hook if VIM is not used.

    Call ip.set_hook('fix_error_editor',youfunc) to use your own function,


<EOL>return line<EOL>

Default input prefilter

    This returns the line as unchanged, so that the interpreter
    knows that nothing was done and proceeds with "classic" prefiltering
    (%magics, !shell commands etc.).

    Note that leading whitespace is not passed to this hook. Prefilter
    can't alter indentation.


<EOL>return<EOL>

default shutdown hook

    Typically, shotdown hooks should raise TryNext so all shutdown ops are done


<EOL>

Executed after ipython has been constructed and configured


<EOL>raise TryNext<EOL>


return None<EOL>

Run before displaying the next prompt

    Use this e.g. to display output from asynchronous operations (in order
    to not mess up text entry)


return None<EOL>

Executed before running the (prefiltered) code in IPython


from IPython.lib.clipboard import (<EOL>osx_clipboard_get, tkinter_clipboard_get,<EOL>win32_clipboard_get<EOL>)<EOL>if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>chain = [win32_clipboard_get, tkinter_clipboard_get]<EOL><DEDENT>elif sys.platform == '<STR_LIT>':<EOL><INDENT>chain = [osx_clipboard_get, tkinter_clipboard_get]<EOL><DEDENT>else:<EOL><INDENT>chain = [tkinter_clipboard_get]<EOL><DEDENT>dispatcher = CommandChainDispatcher()<EOL>for func in chain:<EOL><INDENT>dispatcher.add(func)<EOL><DEDENT>text = dispatcher()<EOL>return text<EOL>


last_exc = TryNext()<EOL>for prio,cmd in self.chain:<EOL><INDENT>try:<EOL><INDENT>return cmd(*args, **kw)<EOL><DEDENT>except TryNext as exc:<EOL><INDENT>last_exc = exc<EOL><DEDENT><DEDENT>raise last_exc<EOL>

Command chain is called just like normal func.

        This will call all funcs in chain with the same args as were given to
        this function, and return the result of first func that didn't raise
        TryNext


def add(self, func, priority=<NUM_LIT:0>):

self.chain.append((priority, func))<EOL>self.chain.sort(key=lambda x: x[<NUM_LIT:0>])<EOL>

Add a func to the cmd chain with given priority


return iter(self.chain)<EOL>

Return all objects in chain.

        Handy if the objects are not callable.


def page(strng, start=<NUM_LIT:0>, screen_lines=<NUM_LIT:0>, pager_cmd=None,<EOL>html=None, auto_html=False):

<EOL>start = max(<NUM_LIT:0>, start)<EOL>shell = InteractiveShell.instance()<EOL>if auto_html:<EOL><INDENT>try:<EOL><INDENT>defaults = {'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:1>}<EOL>html = publish_string(strng, writer_name='<STR_LIT:html>',<EOL>settings_overrides=defaults)<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>payload = dict(<EOL>source='<STR_LIT>',<EOL>text=strng,<EOL>html=html,<EOL>start_line_number=start<EOL>)<EOL>shell.payload_manager.write_payload(payload)<EOL>

Print a string, piping through a pager.

    This version ignores the screen_lines and pager_cmd arguments and uses
    IPython's payload system instead.

    Parameters
    ----------
    strng : str
      Text to page.

    start : int
      Starting line at which to place the display.

    html : str, optional
      If given, an html string to send as well.

    auto_html : bool, optional
      If true, the input string is assumed to be valid reStructuredText and is
      converted to HTML with docutils.  Note that if docutils is not found,
      this option is silently ignored.

    Note
    ----

    Only one of the ``html`` and ``auto_html`` options can be given, not
    both.


from IPython.core import page as corepage<EOL>corepage.page = page<EOL>

Install this version of page as IPython.core.page.page.


hash_digest = hashlib.md5(code.encode("<STR_LIT:utf-8>")).hexdigest()<EOL>return '<STR_LIT>'.format(number, hash_digest[:<NUM_LIT:12>])<EOL>

Compute a (probably) unique name for code for caching.

    This now expects code to be unicode.


def ast_parse(self, source, filename='<STR_LIT>', symbol='<STR_LIT>'):

return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, <NUM_LIT:1>)<EOL>

Parse code to an AST with the current compiler flags active.

        Arguments are exactly the same as ast.parse (in the standard library),
        and are passed to the built-in compile function.


<EOL>self.flags = codeop.PyCF_DONT_IMPLY_DEDENT<EOL>


return self.flags<EOL>

Flags currently active in the compilation process.


def cache(self, code, number=<NUM_LIT:0>):

name = code_name(code, number)<EOL>entry = (len(code), time.time(),<EOL>[line+'<STR_LIT:\n>' for line in code.splitlines()], name)<EOL>linecache.cache[name] = entry<EOL>linecache._ipython_cache[name] = entry<EOL>return name<EOL>

Make a name for a block of code, and cache the code.

        Parameters
        ----------
        code : str
          The Python source code to cache.
        number : int
          A number which forms part of the code's name. Used for the execution
          counter.

        Returns
        -------
        The name of the cached code (as a string). Pass this as the filename
        argument to compilation, so that tracebacks are correctly hooked up.


<EOL>linecache._checkcache_ori(*args)<EOL>linecache.cache.update(linecache._ipython_cache)<EOL>

Call linecache.checkcache() safely protecting our cached values.


self.crash_handler = self.crash_handler_class(self)<EOL>sys.excepthook = self.excepthook<EOL>def unset_crashhandler():<EOL><INDENT>sys.excepthook = sys.__excepthook__<EOL><DEDENT>atexit.register(unset_crashhandler)<EOL>

Create a crash handler, typically setting sys.excepthook to it.


def excepthook(self, etype, evalue, tb):

if self.verbose_crash:<EOL><INDENT>return self.crash_handler(etype, evalue, tb)<EOL><DEDENT>else:<EOL><INDENT>return crashhandler.crash_handler_lite(etype, evalue, tb)<EOL><DEDENT>

this is sys.excepthook after init_crashhandler

        set self.verbose_crash=True to use our full crashhandler, instead of
        a regular traceback with a short message (crash_handler_lite)


self.log.debug("<STR_LIT>", self.config_file_paths)<EOL>base_config = '<STR_LIT>'<EOL>self.log.debug("<STR_LIT>" %<EOL>base_config)<EOL>try:<EOL><INDENT>Application.load_config_file(<EOL>self,<EOL>base_config,<EOL>path=self.config_file_paths<EOL>)<EOL><DEDENT>except ConfigFileNotFound:<EOL><INDENT>self.log.debug("<STR_LIT>", base_config)<EOL>pass<EOL><DEDENT>if self.config_file_name == base_config:<EOL><INDENT>return<EOL><DEDENT>self.log.debug("<STR_LIT>" %<EOL>self.config_file_name)<EOL>try:<EOL><INDENT>Application.load_config_file(<EOL>self,<EOL>self.config_file_name,<EOL>path=self.config_file_paths<EOL>)<EOL><DEDENT>except ConfigFileNotFound:<EOL><INDENT>if self.config_file_specified:<EOL><INDENT>msg = self.log.warn<EOL><DEDENT>else:<EOL><INDENT>msg = self.log.debug<EOL><DEDENT>msg("<STR_LIT>", self.config_file_name)<EOL><DEDENT>except:<EOL><INDENT>if not suppress_errors:<EOL><INDENT>raise<EOL><DEDENT>self.log.warn("<STR_LIT>" %<EOL>self.config_file_name, exc_info=True)<EOL><DEDENT>

Load the config file.

        By default, errors in loading config are handled, and a warning
        printed on screen. For testing, the suppress_errors option is set
        to False, so errors will make tests fail.


try:<EOL><INDENT>location = self.config.ProfileDir.location<EOL><DEDENT>except AttributeError:<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>if self.auto_create or self.profile=='<STR_LIT:default>':<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>self.log.fatal("<STR_LIT>"%self.profile)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%p.location)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.fatal("<STR_LIT>"%self.profile)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%p.location)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.find_profile_dir(location, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>if self.auto_create:<EOL><INDENT>try:<EOL><INDENT>p = ProfileDir.create_profile_dir(location, self.config)<EOL><DEDENT>except ProfileDirError:<EOL><INDENT>self.log.fatal("<STR_LIT>"%location)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%location)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.fatal("<STR_LIT>"%location)<EOL>self.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"%location)<EOL><DEDENT><DEDENT>self.profile_dir = p<EOL>self.config_file_paths.append(p.location)<EOL>


<EOL>path = self.builtin_profile_dir<EOL>if self.copy_config_files:<EOL><INDENT>src = self.profile<EOL>cfg = self.config_file_name<EOL>if path and os.path.exists(os.path.join(path, cfg)):<EOL><INDENT>self.log.warn("<STR_LIT>"%(<EOL>cfg, src, self.profile_dir.location, self.overwrite)<EOL>)<EOL>self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)<EOL><DEDENT>else:<EOL><INDENT>self.stage_default_config_file()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>files = glob.glob(os.path.join(path, '<STR_LIT>'))<EOL>for fullpath in files:<EOL><INDENT>cfg = os.path.basename(fullpath)<EOL>if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):<EOL><INDENT>self.log.warn("<STR_LIT>"%(<EOL>cfg, self.profile, self.profile_dir.location)<EOL>)<EOL><DEDENT><DEDENT><DEDENT>

[optionally] copy default config files into profile dir.


s = self.generate_config_file()<EOL>fname = os.path.join(self.profile_dir.location, self.config_file_name)<EOL>if self.overwrite or not os.path.exists(fname):<EOL><INDENT>self.log.warn("<STR_LIT>"%(fname))<EOL>with open(fname, '<STR_LIT:w>') as f:<EOL><INDENT>f.write(s)<EOL><DEDENT><DEDENT>

auto generate default config file, and stage it into the profile.


bdict = __builtin__.__dict__<EOL>orig = bdict.get(key, BuiltinUndefined)<EOL>if value is HideBuiltin:<EOL><INDENT>if orig is not BuiltinUndefined: <EOL><INDENT>self._orig_builtins[key] = orig<EOL>del bdict[key]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._orig_builtins[key] = orig<EOL>bdict[key] = value<EOL><DEDENT>


if orig is BuiltinUndefined:<EOL><INDENT>del __builtin__.__dict__[key]<EOL><DEDENT>else:<EOL><INDENT>__builtin__.__dict__[key] = orig<EOL><DEDENT>

Remove an added builtin and re-set the original.


add_builtin = self.add_builtin<EOL>for name, func in self.auto_builtins.iteritems():<EOL><INDENT>add_builtin(name, func)<EOL><DEDENT>

Store ipython references in the __builtin__ namespace.


remove_builtin = self.remove_builtin<EOL>for key, val in self._orig_builtins.iteritems():<EOL><INDENT>remove_builtin(key, val)<EOL><DEDENT>self._orig_builtins.clear()<EOL>self._builtins_added = False<EOL>

Remove any builtins which might have been added by add_builtins, or
        restore overwritten ones to their previous values.


<EOL>if s.count('<STR_LIT:">') % <NUM_LIT:2>:<EOL><INDENT>return '<STR_LIT:">'<EOL><DEDENT>elif s.count("<STR_LIT:'>") % <NUM_LIT:2>:<EOL><INDENT>return "<STR_LIT:'>"<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Return whether a string has open quotes.

    This simply counts whether the number of quote characters of either type in
    the string is odd.

    Returns
    -------
    If there is an open quote, the quote character is returned.  Else, return
    False.


return "<STR_LIT>".join([(ch in PROTECTABLES and '<STR_LIT:\\>' + ch or ch)<EOL>for ch in s])<EOL>

Escape a string to protect certain characters.


<EOL>tilde_expand = False<EOL>tilde_val = '<STR_LIT>'<EOL>newpath = path<EOL>if path.startswith('<STR_LIT>'):<EOL><INDENT>tilde_expand = True<EOL>rest = len(path)-<NUM_LIT:1><EOL>newpath = os.path.expanduser(path)<EOL>if rest:<EOL><INDENT>tilde_val = newpath[:-rest]<EOL><DEDENT>else:<EOL><INDENT>tilde_val = newpath<EOL><DEDENT><DEDENT>return newpath, tilde_expand, tilde_val<EOL>

Expand '~'-style usernames in strings.

    This is similar to :func:`os.path.expanduser`, but it computes and returns
    extra information that will be useful if the input was being used in
    computing completions, and you wish to return the completions with the
    original '~' instead of its expanded value.

    Parameters
    ----------
    path : str
      String to be expanded.  If no ~ is present, the output is the same as the
      input.

    Returns
    -------
    newpath : str
      Result of ~ expansion in the input path.
    tilde_expand : bool
      Whether any expansion was performed or not.
    tilde_val : str
      The value that ~ was replaced with.


def compress_user(path, tilde_expand, tilde_val):

if tilde_expand:<EOL><INDENT>return path.replace(tilde_val, '<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return path<EOL><DEDENT>

Does the opposite of expand_user, with its outputs.


try:<EOL><INDENT>words = getattr(obj, '<STR_LIT>')<EOL><DEDENT>except:<EOL><INDENT>return []<EOL><DEDENT>return [w for w in words if isinstance(w, basestring)]<EOL>

returns the strings in the __all__ attribute


return self._delims<EOL>

Return the string of delimiter characters.


expr = '<STR_LIT:[>' + '<STR_LIT>'.join('<STR_LIT:\\>'+ c for c in delims) + '<STR_LIT:]>'<EOL>self._delim_re = re.compile(expr)<EOL>self._delims = delims<EOL>self._delim_expr = expr<EOL>


def split_line(self, line, cursor_pos=None):

l = line if cursor_pos is None else line[:cursor_pos]<EOL>return self._delim_re.split(l)[-<NUM_LIT:1>]<EOL>

Split a line of text with a cursor at the given position.


def __init__(self, namespace=None, global_namespace=None, config=None, **kwargs):

<EOL>if namespace is None:<EOL><INDENT>self.use_main_ns = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>self.use_main_ns = <NUM_LIT:0><EOL>self.namespace = namespace<EOL><DEDENT>if global_namespace is None:<EOL><INDENT>self.global_namespace = {}<EOL><DEDENT>else:<EOL><INDENT>self.global_namespace = global_namespace<EOL><DEDENT>super(Completer, self).__init__(config=config, **kwargs)<EOL>

Create a new completer for the command line.

        Completer(namespace=ns,global_namespace=ns2) -> completer instance.

        If unspecified, the default namespace where completions are performed
        is __main__ (technically, __main__.__dict__). Namespaces should be
        given as dictionaries.

        An optional second namespace can be given.  This allows the completer
        to handle cases where both the local and global scopes need to be
        distinguished.

        Completer instances should be used as the completion mechanism of
        readline via the set_completer() call:

        readline.set_completer(Completer(my_namespace).complete)


if self.use_main_ns:<EOL><INDENT>self.namespace = __main__.__dict__<EOL><DEDENT>if state == <NUM_LIT:0>:<EOL><INDENT>if "<STR_LIT:.>" in text:<EOL><INDENT>self.matches = self.attr_matches(text)<EOL><DEDENT>else:<EOL><INDENT>self.matches = self.global_matches(text)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>return self.matches[state]<EOL><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT>

Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.


<EOL>matches = []<EOL>match_append = matches.append<EOL>n = len(text)<EOL>for lst in [keyword.kwlist,<EOL>__builtin__.__dict__.keys(),<EOL>self.namespace.keys(),<EOL>self.global_namespace.keys()]:<EOL><INDENT>for word in lst:<EOL><INDENT>if word[:n] == text and word != "<STR_LIT>":<EOL><INDENT>match_append(word)<EOL><DEDENT><DEDENT><DEDENT>return matches<EOL>

Compute matches when text is a simple name.

        Return a list of all keywords, built-in functions and names currently
        defined in self.namespace or self.global_namespace that match.


<EOL>m = re.match(r"<STR_LIT>", text)<EOL>if m:<EOL><INDENT>expr, attr = m.group(<NUM_LIT:1>, <NUM_LIT:3>)<EOL><DEDENT>elif self.greedy:<EOL><INDENT>m2 = re.match(r"<STR_LIT>", self.line_buffer)<EOL>if not m2:<EOL><INDENT>return []<EOL><DEDENT>expr, attr = m2.group(<NUM_LIT:1>,<NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT>try:<EOL><INDENT>obj = eval(expr, self.namespace)<EOL><DEDENT>except:<EOL><INDENT>try:<EOL><INDENT>obj = eval(expr, self.global_namespace)<EOL><DEDENT>except:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>if self.limit_to__all__ and hasattr(obj, '<STR_LIT>'):<EOL><INDENT>words = get__all__entries(obj)<EOL><DEDENT>else: <EOL><INDENT>words = dir2(obj)<EOL><DEDENT>try:<EOL><INDENT>words = generics.complete_object(obj, words)<EOL><DEDENT>except TryNext:<EOL><INDENT>pass<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT>n = len(attr)<EOL>res = ["<STR_LIT>" % (expr, w) for w in words if w[:n] == attr ]<EOL>return res<EOL>

Compute matches when text contains a dot.

        Assuming the text is of the form NAME.NAME....[NAME], and is
        evaluatable in self.namespace or self.global_namespace, it will be
        evaluated and its attributes (as revealed by dir()) are used as
        possible completions.  (For class instances, class members are are
        also considered.)

        WARNING: this can still invoke arbitrary C code, if an object
        with a __getattr__ hook is evaluated.


def _greedy_changed(self, name, old, new):

if new:<EOL><INDENT>self.splitter.delims = GREEDY_DELIMS<EOL><DEDENT>else:<EOL><INDENT>self.splitter.delims = DELIMS<EOL><DEDENT>if self.readline:<EOL><INDENT>self.readline.set_completer_delims(self.splitter.delims)<EOL><DEDENT>

update the splitter and readline delims when greedy is changed


def __init__(self, shell=None, namespace=None, global_namespace=None,<EOL>alias_table=None, use_readline=True,<EOL>config=None, **kwargs):

self.magic_escape = ESC_MAGIC<EOL>self.splitter = CompletionSplitter()<EOL>if use_readline:<EOL><INDENT>import IPython.utils.rlineimpl as readline<EOL>self.readline = readline<EOL><DEDENT>else:<EOL><INDENT>self.readline = None<EOL><DEDENT>Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,<EOL>config=config, **kwargs)<EOL>self.matches = []<EOL>self.shell = shell<EOL>if alias_table is None:<EOL><INDENT>alias_table = {}<EOL><DEDENT>self.alias_table = alias_table<EOL>self.space_name_re = re.compile(r'<STR_LIT>')<EOL>self.glob = glob.glob<EOL>term = os.environ.get('<STR_LIT>','<STR_LIT>')<EOL>self.dumb_terminal = term in ['<STR_LIT>','<STR_LIT>']<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>self.clean_glob = self._clean_glob_win32<EOL><DEDENT>else:<EOL><INDENT>self.clean_glob = self._clean_glob<EOL><DEDENT>self.matchers = [self.python_matches,<EOL>self.file_matches,<EOL>self.magic_matches,<EOL>self.alias_matches,<EOL>self.python_func_kw_matches,<EOL>]<EOL>

IPCompleter() -> completer

        Return a completer object suitable for use by the readline library
        via readline.set_completer().

        Inputs:

        - shell: a pointer to the ipython shell itself.  This is needed
        because this completer knows about magic functions, and those can
        only be accessed via the ipython instance.

        - namespace: an optional dict where completions are performed.

        - global_namespace: secondary optional dict for completions, to
        handle cases (such as IPython embedded inside functions) where
        both Python scopes are visible.

        - If alias_table is supplied, it should be a dictionary of aliases
        to complete.

        use_readline : bool, optional
          If true, use the readline library.  This completer can still function
          without readline, though in that case callers must provide some extra
          information on each call about the current line.


return self.complete(text)[<NUM_LIT:1>]<EOL>

Wrapper around the complete method for the benefit of emacs
and pydb.


<EOL>if text.startswith('<STR_LIT:!>'):<EOL><INDENT>text = text[<NUM_LIT:1>:]<EOL>text_prefix = '<STR_LIT:!>'<EOL><DEDENT>else:<EOL><INDENT>text_prefix = '<STR_LIT>'<EOL><DEDENT>text_until_cursor = self.text_until_cursor<EOL>open_quotes = has_open_quotes(text_until_cursor)<EOL>if '<STR_LIT:(>' in text_until_cursor or '<STR_LIT:[>' in text_until_cursor:<EOL><INDENT>lsplit = text<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>lsplit = arg_split(text_until_cursor)[-<NUM_LIT:1>]<EOL><DEDENT>except ValueError:<EOL><INDENT>if open_quotes:<EOL><INDENT>lsplit = text_until_cursor.split(open_quotes)[-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>except IndexError:<EOL><INDENT>lsplit = "<STR_LIT>"<EOL><DEDENT><DEDENT>if not open_quotes and lsplit != protect_filename(lsplit):<EOL><INDENT>has_protectables = True<EOL>text0,text = text,lsplit<EOL><DEDENT>else:<EOL><INDENT>has_protectables = False<EOL>text = os.path.expanduser(text)<EOL><DEDENT>if text == "<STR_LIT>":<EOL><INDENT>return [text_prefix + protect_filename(f) for f in self.glob("<STR_LIT:*>")]<EOL><DEDENT>m0 = self.clean_glob(text.replace('<STR_LIT:\\>','<STR_LIT>'))<EOL>if has_protectables:<EOL><INDENT>len_lsplit = len(lsplit)<EOL>matches = [text_prefix + text0 +<EOL>protect_filename(f[len_lsplit:]) for f in m0]<EOL><DEDENT>else:<EOL><INDENT>if open_quotes:<EOL><INDENT>matches = m0<EOL><DEDENT>else:<EOL><INDENT>matches = [text_prefix +<EOL>protect_filename(f) for f in m0]<EOL><DEDENT><DEDENT>matches = [x+'<STR_LIT:/>' if os.path.isdir(x) else x for x in matches]<EOL>return matches<EOL>

Match filenames, expanding ~USER type strings.

        Most of the seemingly convoluted logic in this completer is an
        attempt to handle filenames with spaces in them.  And yet it's not
        quite perfect, because Python's readline doesn't expose all of the
        GNU readline details needed for this to be done correctly.

        For a filename with a space in it, the printed completions will be
        only the parts after what's already been typed (instead of the
        full completions, as is normally done).  I don't think with the
        current (as of Python 2.3) Python readline it's possible to do
        better.


<EOL>lsm = self.shell.magics_manager.lsmagic()<EOL>line_magics = lsm['<STR_LIT>']<EOL>cell_magics = lsm['<STR_LIT>']<EOL>pre = self.magic_escape<EOL>pre2 = pre+pre<EOL>bare_text = text.lstrip(pre)<EOL>comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]<EOL>if not text.startswith(pre2):<EOL><INDENT>comp += [ pre+m for m in line_magics if m.startswith(bare_text)]<EOL><DEDENT>return comp<EOL>


<EOL>main_text = self.text_until_cursor.lstrip()<EOL>if '<STR_LIT:U+0020>' in main_text and not main_text.startswith('<STR_LIT>'):<EOL><INDENT>return []<EOL><DEDENT>text = os.path.expanduser(text)<EOL>aliases =  self.alias_table.keys()<EOL>if text == '<STR_LIT>':<EOL><INDENT>return aliases<EOL><DEDENT>else:<EOL><INDENT>return [a for a in aliases if a.startswith(text)]<EOL><DEDENT>


<EOL>if "<STR_LIT:.>" in text:<EOL><INDENT>try:<EOL><INDENT>matches = self.attr_matches(text)<EOL>if text.endswith('<STR_LIT:.>') and self.omit__names:<EOL><INDENT>if self.omit__names == <NUM_LIT:1>:<EOL><INDENT>no__name = (lambda txt:<EOL>re.match(r'<STR_LIT>',txt) is None)<EOL><DEDENT>else:<EOL><INDENT>no__name = (lambda txt:<EOL>re.match(r'<STR_LIT>',txt) is None)<EOL><DEDENT>matches = filter(no__name, matches)<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>matches = []<EOL><DEDENT><DEDENT>else:<EOL><INDENT>matches = self.global_matches(text)<EOL><DEDENT>return matches<EOL>


if not (inspect.isfunction(obj) or inspect.ismethod(obj)):<EOL><INDENT>if inspect.isclass(obj):<EOL><INDENT>obj = (getattr(obj,'<STR_LIT>',None) or<EOL>getattr(obj,'<STR_LIT>',None))<EOL><DEDENT>elif hasattr(obj, '<STR_LIT>'):<EOL><INDENT>obj = obj.__call__<EOL><DEDENT><DEDENT>try:<EOL><INDENT>args,_,_1,defaults = inspect.getargspec(obj)<EOL>if defaults:<EOL><INDENT>return args[-len(defaults):]<EOL><DEDENT><DEDENT>except TypeError: pass<EOL>return []<EOL>

Return the list of default arguments of obj if it is callable,
        or empty list otherwise.


if "<STR_LIT:.>" in text: <EOL><INDENT>return []<EOL><DEDENT>try: regexp = self.__funcParamsRegex<EOL>except AttributeError:<EOL><INDENT>regexp = self.__funcParamsRegex = re.compile(r'''<STR_LIT>''', re.VERBOSE | re.DOTALL)<EOL><DEDENT>tokens = regexp.findall(self.text_until_cursor)<EOL>tokens.reverse()<EOL>iterTokens = iter(tokens); openPar = <NUM_LIT:0><EOL>for token in iterTokens:<EOL><INDENT>if token == '<STR_LIT:)>':<EOL><INDENT>openPar -= <NUM_LIT:1><EOL><DEDENT>elif token == '<STR_LIT:(>':<EOL><INDENT>openPar += <NUM_LIT:1><EOL>if openPar > <NUM_LIT:0>:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT>ids = []<EOL>isId = re.compile(r'<STR_LIT>').match<EOL>while True:<EOL><INDENT>try:<EOL><INDENT>ids.append(iterTokens.next())<EOL>if not isId(ids[-<NUM_LIT:1>]):<EOL><INDENT>ids.pop(); break<EOL><DEDENT>if not iterTokens.next() == '<STR_LIT:.>':<EOL><INDENT>break<EOL><DEDENT><DEDENT>except StopIteration:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if len(ids) == <NUM_LIT:1>:<EOL><INDENT>callableMatches = self.global_matches(ids[<NUM_LIT:0>])<EOL><DEDENT>else:<EOL><INDENT>callableMatches = self.attr_matches('<STR_LIT:.>'.join(ids[::-<NUM_LIT:1>]))<EOL><DEDENT>argMatches = []<EOL>for callableMatch in callableMatches:<EOL><INDENT>try:<EOL><INDENT>namedArgs = self._default_arguments(eval(callableMatch,<EOL>self.namespace))<EOL><DEDENT>except:<EOL><INDENT>continue<EOL><DEDENT>for namedArg in namedArgs:<EOL><INDENT>if namedArg.startswith(text):<EOL><INDENT>argMatches.append("<STR_LIT>" %namedArg)<EOL><DEDENT><DEDENT><DEDENT>return argMatches<EOL>

Match named parameters (kwargs) of the last open function


def complete(self, text=None, line_buffer=None, cursor_pos=None):

<EOL>if cursor_pos is None:<EOL><INDENT>cursor_pos = len(line_buffer) if text is None else len(text)<EOL><DEDENT>if not text:<EOL><INDENT>text = self.splitter.split_line(line_buffer, cursor_pos)<EOL><DEDENT>if line_buffer is None:<EOL><INDENT>line_buffer = text<EOL><DEDENT>self.line_buffer = line_buffer<EOL>self.text_until_cursor = self.line_buffer[:cursor_pos]<EOL>self.matches[:] = []<EOL>custom_res = self.dispatch_custom_completer(text)<EOL>if custom_res is not None:<EOL><INDENT>self.matches = custom_res<EOL><DEDENT>else:<EOL><INDENT>if self.merge_completions:<EOL><INDENT>self.matches = []<EOL>for matcher in self.matchers:<EOL><INDENT>try:<EOL><INDENT>self.matches.extend(matcher(text))<EOL><DEDENT>except:<EOL><INDENT>sys.excepthook(*sys.exc_info())<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for matcher in self.matchers:<EOL><INDENT>self.matches = matcher(text)<EOL>if self.matches:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.matches = sorted(set(self.matches))<EOL>return text, self.matches<EOL>

Find completions for the given text and line context.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        Note that both the text and the line_buffer are optional, but at least
        one of them must be given.

        Parameters
        ----------
          text : string, optional
            Text to perform the completion on.  If not given, the line buffer
            is split using the instance's CompletionSplitter object.

          line_buffer : string, optional
            If not given, the completer attempts to obtain the current line
            buffer via readline.  This keyword allows clients which are
            requesting for text completions in non-readline contexts to inform
            the completer of the entire text.

          cursor_pos : int, optional
            Index of the cursor in the full line buffer.  Should be provided by
            remote frontends where kernel has no access to frontend state.

        Returns
        -------
        text : str
          Text that was actually used in the completion.

        matches : list
          A list of completion matches.


if state==<NUM_LIT:0>:<EOL><INDENT>self.line_buffer = line_buffer = self.readline.get_line_buffer()<EOL>cursor_pos = self.readline.get_endidx()<EOL>if not (self.dumb_terminal or line_buffer.strip()):<EOL><INDENT>self.readline.insert_text('<STR_LIT:\t>')<EOL>sys.stdout.flush()<EOL>return None<EOL><DEDENT>DEBUG = False<EOL>if DEBUG:<EOL><INDENT>try:<EOL><INDENT>self.complete(text, line_buffer, cursor_pos)<EOL><DEDENT>except:<EOL><INDENT>import traceback; traceback.print_exc()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.complete(text, line_buffer, cursor_pos)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>return self.matches[state]<EOL><DEDENT>except IndexError:<EOL><INDENT>return None<EOL><DEDENT>

Return the state-th possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        Parameters
        ----------
          text : string
            Text to perform the completion on.

          state : int
            Counter used by readline.


if sys.path[<NUM_LIT:0>] != '<STR_LIT>':<EOL><INDENT>sys.path.insert(<NUM_LIT:0>, '<STR_LIT>')<EOL><DEDENT>

Add current working directory, '', to sys.path


if self.gui or self.pylab:<EOL><INDENT>shell = self.shell<EOL>try:<EOL><INDENT>if self.pylab:<EOL><INDENT>gui, backend = pylabtools.find_gui_and_backend(self.pylab)<EOL>self.log.info("<STR_LIT>"<EOL>"<STR_LIT>" % (gui, self.pylab))<EOL>shell.enable_pylab(gui, import_all=self.pylab_import_all)<EOL><DEDENT>else:<EOL><INDENT>self.log.info("<STR_LIT>"<EOL>"<STR_LIT>" % self.gui)<EOL>shell.enable_gui(self.gui)<EOL><DEDENT><DEDENT>except Exception:<EOL><INDENT>self.log.warn("<STR_LIT>")<EOL>self.shell.showtraceback()<EOL><DEDENT><DEDENT>

Enable GUI event loop integration, taking pylab into account.


try:<EOL><INDENT>self.log.debug("<STR_LIT>")<EOL>extensions = self.default_extensions + self.extensions<EOL>for ext in extensions:<EOL><INDENT>try:<EOL><INDENT>self.log.info("<STR_LIT>" % ext)<EOL>self.shell.extension_manager.load_extension(ext)<EOL><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>" % ext +<EOL>"<STR_LIT>" % self.profile_dir.location<EOL>)<EOL>self.shell.showtraceback()<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>")<EOL>self.shell.showtraceback()<EOL><DEDENT>

Load all IPython extensions in IPythonApp.extensions.

        This uses the :meth:`ExtensionManager.load_extensions` to load all
        the extensions listed in ``self.extensions``.


run the pre-flight code, specified via exec_lines


if not self.exec_lines:<EOL><INDENT>return<EOL><DEDENT>try:<EOL><INDENT>self.log.debug("<STR_LIT>")<EOL>for line in self.exec_lines:<EOL><INDENT>try:<EOL><INDENT>self.log.info("<STR_LIT>" %<EOL>line)<EOL>self.shell.run_cell(line, store_history=False)<EOL><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>"<EOL>"<STR_LIT>" % line)<EOL>self.shell.showtraceback()<EOL><DEDENT><DEDENT><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>")<EOL>self.shell.showtraceback()<EOL><DEDENT>

Run lines of code in IPythonApp.exec_lines in the user's namespace.


startup_dir = self.profile_dir.startup_dir<EOL>startup_files = glob.glob(os.path.join(startup_dir, '<STR_LIT>'))<EOL>startup_files += glob.glob(os.path.join(startup_dir, '<STR_LIT>'))<EOL>if not startup_files:<EOL><INDENT>return<EOL><DEDENT>self.log.debug("<STR_LIT>", startup_dir)<EOL>try:<EOL><INDENT>for fname in sorted(startup_files):<EOL><INDENT>self._exec_file(fname)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>")<EOL>self.shell.showtraceback()<EOL><DEDENT>

Run files from profile startup directory


if not self.exec_files:<EOL><INDENT>return<EOL><DEDENT>self.log.debug("<STR_LIT>")<EOL>try:<EOL><INDENT>for fname in self.exec_files:<EOL><INDENT>self._exec_file(fname)<EOL><DEDENT><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>")<EOL>self.shell.showtraceback()<EOL><DEDENT>


if self.code_to_run:<EOL><INDENT>line = self.code_to_run<EOL>try:<EOL><INDENT>self.log.info("<STR_LIT>" %<EOL>line)<EOL>self.shell.run_cell(line, store_history=False)<EOL><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>" %<EOL>line)<EOL>self.shell.showtraceback()<EOL><DEDENT><DEDENT>elif self.file_to_run:<EOL><INDENT>fname = self.file_to_run<EOL>try:<EOL><INDENT>self._exec_file(fname)<EOL><DEDENT>except:<EOL><INDENT>self.log.warn("<STR_LIT>" %<EOL>fname)<EOL>self.shell.showtraceback()<EOL><DEDENT><DEDENT>

Run code or file specified at the command-line


if self.module_to_run:<EOL><INDENT>save_argv = sys.argv<EOL>sys.argv = [sys.executable] + self.extra_args<EOL>try:<EOL><INDENT>self.shell.safe_run_module(self.module_to_run,<EOL>self.shell.user_ns)<EOL><DEDENT>finally:<EOL><INDENT>sys.argv = save_argv<EOL><DEDENT><DEDENT>

Run module specified at the command-line.


from IPython.core import page<EOL>page.page(gui_reference, auto_html=True)<EOL>

Show a basic reference about the GUI Console.


def format_display_data(obj, include=None, exclude=None):

from IPython.core.interactiveshell import InteractiveShell<EOL>InteractiveShell.instance().display_formatter.format(<EOL>obj,<EOL>include,<EOL>exclude<EOL>)<EOL>

Return a format data dict for an object.

    By default all format types will be computed.

    The following MIME types are currently implemented:

    * text/plain
    * text/html
    * text/latex
    * application/json
    * application/javascript
    * image/png
    * image/jpeg
    * image/svg+xml

    Parameters
    ----------
    obj : object
        The Python object whose format data will be computed.

    Returns
    -------
    format_dict : dict
        A dictionary of key/value pairs, one or each format that was
        generated for the object. The keys are the format types, which
        will usually be MIME type strings and the values and JSON'able
        data structure containing the raw data for the representation in
        that format.
    include : list or tuple, optional
        A list of format type strings (MIME types) to include in the
        format data dict. If this is set *only* the format types included
        in this list will be computed.
    exclude : list or tuple, optional
        A list of format type string (MIME types) to exclue in the format
        data dict. If this is set all format types will be computed,
        except for those included in this argument.


formatter_classes = [<EOL>PlainTextFormatter,<EOL>HTMLFormatter,<EOL>SVGFormatter,<EOL>PNGFormatter,<EOL>JPEGFormatter,<EOL>LatexFormatter,<EOL>JSONFormatter,<EOL>JavascriptFormatter<EOL>]<EOL>d = {}<EOL>for cls in formatter_classes:<EOL><INDENT>f = cls(config=self.config)<EOL>d[f.format_type] = f<EOL><DEDENT>return d<EOL>


def format(self, obj, include=None, exclude=None):

format_dict = {}<EOL>if self.plain_text_only:<EOL><INDENT>formatter = self.formatters['<STR_LIT>']<EOL>try:<EOL><INDENT>data = formatter(obj)<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>if data is not None:<EOL><INDENT>format_dict['<STR_LIT>'] = data<EOL><DEDENT>return format_dict<EOL><DEDENT>for format_type, formatter in self.formatters.items():<EOL><INDENT>if include is not None:<EOL><INDENT>if format_type not in include:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>if exclude is not None:<EOL><INDENT>if format_type in exclude:<EOL><INDENT>continue<EOL><DEDENT><DEDENT>try:<EOL><INDENT>data = formatter(obj)<EOL><DEDENT>except:<EOL><INDENT>raise<EOL><DEDENT>if data is not None:<EOL><INDENT>format_dict[format_type] = data<EOL><DEDENT><DEDENT>return format_dict<EOL>

Return a format data dict for an object.

        By default all format types will be computed.

        The following MIME types are currently implemented:

        * text/plain
        * text/html
        * text/latex
        * application/json
        * application/javascript
        * image/png
        * image/jpeg
        * image/svg+xml

        Parameters
        ----------
        obj : object
            The Python object whose format data will be computed.
        include : list or tuple, optional
            A list of format type strings (MIME types) to include in the
            format data dict. If this is set *only* the format types included
            in this list will be computed.
        exclude : list or tuple, optional
            A list of format type string (MIME types) to exclue in the format
            data dict. If this is set all format types will be computed,
            except for those included in this argument.

        Returns
        -------
        format_dict : dict
            A dictionary of key/value pairs, one or each format that was
            generated for the object. The keys are the format types, which
            will usually be MIME type strings and the values and JSON'able
            data structure containing the raw data for the representation in
            that format.


return self.formatters.keys()<EOL>

Return the format types (MIME types) of the active formatters.


try:<EOL><INDENT>return repr(obj)<EOL><DEDENT>except TypeError:<EOL><INDENT>return None<EOL><DEDENT>

Return a JSON'able representation of the object.

        If the object cannot be formatted by this formatter, then return None


if self.enabled:<EOL><INDENT>obj_id = id(obj)<EOL>try:<EOL><INDENT>obj_class = getattr(obj, '<STR_LIT>', None) or type(obj)<EOL>try:<EOL><INDENT>printer = self.singleton_printers[obj_id]<EOL><DEDENT>except (TypeError, KeyError):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return printer(obj)<EOL><DEDENT>for cls in pretty._get_mro(obj_class):<EOL><INDENT>if cls in self.type_printers:<EOL><INDENT>return self.type_printers[cls](obj)<EOL><DEDENT>else:<EOL><INDENT>printer = self._in_deferred_types(cls)<EOL>if printer is not None:<EOL><INDENT>return printer(obj)<EOL><DEDENT><DEDENT><DEDENT>if hasattr(obj_class, self.print_method):<EOL><INDENT>printer = getattr(obj_class, self.print_method)<EOL>return printer(obj)<EOL><DEDENT>return None<EOL><DEDENT>except Exception:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>


oldfunc = self.type_printers.get(typ, None)<EOL>if func is not None:<EOL><INDENT>self.type_printers[typ] = func<EOL><DEDENT>return oldfunc<EOL>

Add a format function for a given type.

        Parameters
        -----------
        typ : class
            The class of the object that will be formatted using `func`.
        func : callable
            The callable that will be called to compute the format data. The
            call signature of this function is simple, it must take the
            object to be formatted and return the raw data for the given
            format. Subclasses may use a different call signature for the
            `func` argument.


def for_type_by_name(self, type_module, type_name, func):

key = (type_module, type_name)<EOL>oldfunc = self.deferred_printers.get(key, None)<EOL>if func is not None:<EOL><INDENT>self.deferred_printers[key] = func<EOL><DEDENT>return oldfunc<EOL>

Add a format function for a type specified by the full dotted
        module and name of the type, rather than the type of the object.

        Parameters
        ----------
        type_module : str
            The full dotted name of the module the type is defined in, like
            ``numpy``.
        type_name : str
            The name of the type (the class name), like ``dtype``
        func : callable
            The callable that will be called to compute the format data. The
            call signature of this function is simple, it must take the
            object to be formatted and return the raw data for the given
            format. Subclasses may use a different call signature for the
            `func` argument.


mod = getattr(cls, '<STR_LIT>', None)<EOL>name = getattr(cls, '<STR_LIT>', None)<EOL>key = (mod, name)<EOL>printer = None<EOL>if key in self.deferred_printers:<EOL><INDENT>printer = self.deferred_printers.pop(key)<EOL>self.type_printers[cls] = printer<EOL><DEDENT>return printer<EOL>

Check if the given class is specified in the deferred type registry.

Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use.


def _float_precision_changed(self, name, old, new):

if '<STR_LIT:%>' in new:<EOL><INDENT>fmt = new<EOL>try:<EOL><INDENT>fmt%<NUM_LIT><EOL><DEDENT>except Exception:<EOL><INDENT>raise ValueError("<STR_LIT>"%new)<EOL><DEDENT><DEDENT>elif new:<EOL><INDENT>try:<EOL><INDENT>i = int(new)<EOL>assert i >= <NUM_LIT:0><EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>"%new)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise ValueError("<STR_LIT>"%i)<EOL><DEDENT>fmt = '<STR_LIT>'%i<EOL>if '<STR_LIT>' in sys.modules:<EOL><INDENT>import numpy<EOL>numpy.set_printoptions(precision=i)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>fmt = '<STR_LIT>'<EOL>if '<STR_LIT>' in sys.modules:<EOL><INDENT>import numpy<EOL>numpy.set_printoptions(precision=<NUM_LIT:8>)<EOL><DEDENT><DEDENT>self.float_format = fmt<EOL>

float_precision changed, set float_format accordingly.

        float_precision can be set by int or str.
        This will set float_format, after interpreting input.
        If numpy has been imported, numpy print precision will also be set.

        integer `n` sets format to '%.nf', otherwise, format set directly.

        An empty string returns to defaults (repr for float, 8 for numpy).

        This parameter can be set via the '%precision' magic.


if not self.pprint:<EOL><INDENT>try:<EOL><INDENT>return repr(obj)<EOL><DEDENT>except TypeError:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>stream = StringIO()<EOL>printer = pretty.RepresentationPrinter(stream, self.verbose,<EOL>self.max_width, unicode_to_str(self.newline),<EOL>singleton_pprinters=self.singleton_printers,<EOL>type_pprinters=self.type_printers,<EOL>deferred_pprinters=self.deferred_printers)<EOL>printer.pretty(obj)<EOL>printer.flush()<EOL>return stream.getvalue()<EOL><DEDENT>

Compute the pretty representation of the object.


kwds = getattr(magic_func, '<STR_LIT>', {})<EOL>if '<STR_LIT:description>' not in kwds:<EOL><INDENT>kwds['<STR_LIT:description>'] = getattr(magic_func, '<STR_LIT>', None)<EOL><DEDENT>arg_name = real_name(magic_func)<EOL>parser = MagicArgumentParser(arg_name, **kwds)<EOL>group = None<EOL>for deco in magic_func.decorators[::-<NUM_LIT:1>]:<EOL><INDENT>result = deco.add_to_parser(parser, group)<EOL>if result is not None:<EOL><INDENT>group = result<EOL><DEDENT><DEDENT>help_text = parser.format_help()<EOL>if help_text.startswith('<STR_LIT>'):<EOL><INDENT>help_text = help_text.replace('<STR_LIT>', '<STR_LIT:%>', <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>help_text = '<STR_LIT:%>' + help_text<EOL><DEDENT>magic_func.__doc__ = help_text<EOL>return parser<EOL>

Construct an argument parser using the function decorations.


return magic_func.parser.parse_argstring(argstring)<EOL>

Parse the string of arguments for the given magic function.


magic_name = magic_func.__name__<EOL>if magic_name.startswith('<STR_LIT>'):<EOL><INDENT>magic_name = magic_name[len('<STR_LIT>'):]<EOL><DEDENT>return getattr(magic_func, '<STR_LIT>', magic_name)<EOL>


raise UsageError(message)<EOL>

Raise a catchable error instead of exiting.


argv = arg_split(argstring)<EOL>return self.parse_args(argv)<EOL>

Split a string into an argument list and parse that argument list.


pass<EOL>

Add this object's information to the parser, if necessary.


if group is not None:<EOL><INDENT>parser = group<EOL><DEDENT>parser.add_argument(*self.args, **self.kwds)<EOL>return None<EOL>

Add this object's information to the parser.


return parser.add_argument_group(*self.args, **self.kwds)<EOL>


files = os.listdir(path)<EOL>profiles = []<EOL>for f in files:<EOL><INDENT>full_path = os.path.join(path, f)<EOL>if os.path.isdir(full_path) and f.startswith('<STR_LIT>'):<EOL><INDENT>profiles.append(f.split('<STR_LIT:_>',<NUM_LIT:1>)[-<NUM_LIT:1>])<EOL><DEDENT><DEDENT>return profiles<EOL>


path = os.path.join(get_ipython_package_dir(), '<STR_LIT>', '<STR_LIT>')<EOL>files = os.listdir(path)<EOL>profiles = []<EOL>for profile in files:<EOL><INDENT>full_path = os.path.join(path, profile)<EOL>if os.path.isdir(full_path) and profile != "<STR_LIT>":<EOL><INDENT>profiles.append(profile)<EOL><DEDENT><DEDENT>return profiles<EOL>

list profiles that are bundled with IPython.


for profile in profiles:<EOL><INDENT>print('<STR_LIT>' % profile)<EOL><DEDENT>


<EOL>if os.name == '<STR_LIT>':<EOL><INDENT>default_aliases = [('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL>if sys.platform.startswith('<STR_LIT>'):<EOL><INDENT>ls_aliases = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>else:<EOL><INDENT>ls_aliases = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>default_aliases = default_aliases + ls_aliases<EOL><DEDENT>elif os.name in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>default_aliases = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'), ('<STR_LIT>', '<STR_LIT>'),<EOL>]<EOL><DEDENT>else:<EOL><INDENT>default_aliases = []<EOL><DEDENT>return default_aliases<EOL>

Return list of shell aliases to auto-define.


try:<EOL><INDENT>self.define_alias(name, cmd)<EOL><DEDENT>except AliasError as e:<EOL><INDENT>error("<STR_LIT>" % e)<EOL><DEDENT>

Define an alias, but don't raise on an AliasError.


nargs = self.validate_alias(name, cmd)<EOL>self.alias_table[name] = (nargs, cmd)<EOL>

Define a new alias after validating it.

        This will raise an :exc:`AliasError` if there are validation
        problems.


if name in self.no_alias:<EOL><INDENT>raise InvalidAliasError("<STR_LIT>"<EOL>"<STR_LIT>" % name)<EOL><DEDENT>if not (isinstance(cmd, str)):<EOL><INDENT>raise InvalidAliasError("<STR_LIT>"<EOL>"<STR_LIT>" % cmd)<EOL><DEDENT>nargs = cmd.count('<STR_LIT:%s>')<EOL>if nargs><NUM_LIT:0> and cmd.find('<STR_LIT>')>=<NUM_LIT:0>:<EOL><INDENT>raise InvalidAliasError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>return nargs<EOL>

Validate an alias and return the its number of arguments.


def call_alias(self, alias, rest='<STR_LIT>'):

cmd = self.transform_alias(alias, rest)<EOL>try:<EOL><INDENT>self.shell.system(cmd)<EOL><DEDENT>except:<EOL><INDENT>self.shell.showtraceback()<EOL><DEDENT>

Call an alias given its name and the rest of the line.


nargs, cmd = self.alias_table[alias]<EOL>if '<STR_LIT:U+0020>' in cmd and os.path.isfile(cmd):<EOL><INDENT>cmd = '<STR_LIT>' % cmd<EOL><DEDENT>if cmd.find('<STR_LIT>') >= <NUM_LIT:0>:<EOL><INDENT>cmd = cmd.replace('<STR_LIT>', rest)<EOL>rest = '<STR_LIT>'<EOL><DEDENT>if nargs==<NUM_LIT:0>:<EOL><INDENT>cmd = '<STR_LIT>' % (cmd, rest)<EOL><DEDENT>else:<EOL><INDENT>args = rest.split(None, nargs)<EOL>if len(args) < nargs:<EOL><INDENT>raise AliasError('<STR_LIT>' %<EOL>(alias, nargs, len(args)))<EOL><DEDENT>cmd = '<STR_LIT>' % (cmd % tuple(args[:nargs]),'<STR_LIT:U+0020>'.join(args[nargs:]))<EOL><DEDENT>return cmd<EOL>

Transform alias to system command string.


pre,_,fn,rest = split_user_input(line)<EOL>res = pre + self.expand_aliases(fn, rest)<EOL>return res<EOL>

Expand an alias in the command line

        Returns the provided command line, possibly with the first word
        (command) translated according to alias expansion rules.

        [ipython]|16> _ip.expand_aliases("np myfile.txt")
                 <16> 'q:/opt/np/notepad++.exe myfile.txt'


line = fn + "<STR_LIT:U+0020>" + rest<EOL>done = set()<EOL>while <NUM_LIT:1>:<EOL><INDENT>pre,_,fn,rest = split_user_input(line, shell_line_split)<EOL>if fn in self.alias_table:<EOL><INDENT>if fn in done:<EOL><INDENT>warn("<STR_LIT>" % fn)<EOL>return "<STR_LIT>"<EOL><DEDENT>done.add(fn)<EOL>l2 = self.transform_alias(fn, rest)<EOL>if l2 == line:<EOL><INDENT>break<EOL><DEDENT>if l2.split(None,<NUM_LIT:1>)[<NUM_LIT:0>] == line.split(None,<NUM_LIT:1>)[<NUM_LIT:0>]:<EOL><INDENT>line = l2<EOL>break<EOL><DEDENT>line=l2<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return line<EOL>

Expand multiple levels of aliases:

        if:

        alias foo bar /tmp
        alias baz foo

        then:

        baz huhhahhei -> bar /tmp huhhahhei


from IPython.core.interactiveshell import InteractiveShell<EOL>return InteractiveShell.instance()<EOL>

Get the global InteractiveShell instance.


from matplotlib._pylab_helpers import Gcf<EOL>if not fig_nums:<EOL><INDENT>fig_managers = Gcf.get_all_fig_managers()<EOL>return [fm.canvas.figure for fm in fig_managers]<EOL><DEDENT>else:<EOL><INDENT>figs = []<EOL>for num in fig_nums:<EOL><INDENT>f = Gcf.figs.get(num)<EOL>if f is None:<EOL><INDENT>print(('<STR_LIT>' % num))<EOL><DEDENT>else:<EOL><INDENT>figs.append(f.canvas.figure)<EOL><DEDENT><DEDENT>return figs<EOL><DEDENT>

Get a list of matplotlib figures by figure numbers.

    If no arguments are given, all available figures are returned.  If the
    argument list contains references to invalid figures, a warning is printed
    but the function continues pasting further figures.

    Parameters
    ----------
    figs : tuple
        A tuple of ints giving the figure numbers of the figures to return.


import matplotlib<EOL>matplotlib.rcParams['<STR_LIT>'] = [sizex, sizey]<EOL>

Set the default figure size to be [sizex, sizey].

    This is just an easy to remember, convenience wrapper that sets::

      matplotlib.rcParams['figure.figsize'] = [sizex, sizey]


<EOL>if not fig.axes and not fig.lines:<EOL><INDENT>return<EOL><DEDENT>fc = fig.get_facecolor()<EOL>ec = fig.get_edgecolor()<EOL>fig.set_facecolor('<STR_LIT>')<EOL>fig.set_edgecolor('<STR_LIT>')<EOL>try:<EOL><INDENT>bytes_io = BytesIO()<EOL>fig.canvas.print_figure(bytes_io, format=fmt, bbox_inches='<STR_LIT>')<EOL>data = bytes_io.getvalue()<EOL><DEDENT>finally:<EOL><INDENT>fig.set_facecolor(fc)<EOL>fig.set_edgecolor(ec)<EOL><DEDENT>return data<EOL>

Convert a figure to svg or png for inline display.


def mpl_execfile(fname,*where,**kw):<EOL><INDENT>"""<STR_LIT>"""<EOL>import matplotlib<EOL>import matplotlib.pylab as pylab<EOL>is_interactive = matplotlib.rcParams['<STR_LIT>']<EOL>matplotlib.interactive(False)<EOL>safe_execfile(fname,*where,**kw)<EOL>matplotlib.interactive(is_interactive)<EOL>if pylab.draw_if_interactive.called:<EOL><INDENT>pylab.draw()<EOL>pylab.draw_if_interactive.called = False<EOL><DEDENT><DEDENT>return mpl_execfile<EOL>

Factory to return a matplotlib-enabled runner for %run.

    Parameters
    ----------
    safe_execfile : function
      This must be a function with the same interface as the
      :meth:`safe_execfile` method of IPython.

    Returns
    -------
    A function suitable for use as the ``runner`` argument of the %run magic
    function.


from matplotlib.figure import Figure<EOL>from IPython.zmq.pylab import backend_inline<EOL>svg_formatter = shell.display_formatter.formatters['<STR_LIT>']<EOL>png_formatter = shell.display_formatter.formatters['<STR_LIT>']<EOL>if fmt=='<STR_LIT>':<EOL><INDENT>svg_formatter.type_printers.pop(Figure, None)<EOL>png_formatter.for_type(Figure, lambda fig: print_figure(fig, '<STR_LIT>'))<EOL><DEDENT>elif fmt=='<STR_LIT>':<EOL><INDENT>png_formatter.type_printers.pop(Figure, None)<EOL>svg_formatter.for_type(Figure, lambda fig: print_figure(fig, '<STR_LIT>'))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>"%fmt)<EOL><DEDENT>backend_inline._figure_format = fmt<EOL>

Select figure format for inline backend, either 'png' or 'svg'.

    Using this method ensures only one figure format is active at a time.


import matplotlib<EOL>if gui and gui != '<STR_LIT>':<EOL><INDENT>backend = backends[gui]<EOL><DEDENT>else:<EOL><INDENT>backend = matplotlib.rcParams['<STR_LIT>']<EOL>gui = backend2gui.get(backend, None)<EOL><DEDENT>return gui, backend<EOL>

Given a gui string return the gui and mpl backend.

    Parameters
    ----------
    gui : str
        Can be one of ('tk','gtk','wx','qt','qt4','inline').

    Returns
    -------
    A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
    'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').


import matplotlib<EOL>if backend.startswith('<STR_LIT>'):<EOL><INDENT>matplotlib.rcParams['<STR_LIT>'] = backend<EOL><DEDENT>else:<EOL><INDENT>matplotlib.use(backend)<EOL><DEDENT>matplotlib.interactive(True)<EOL>import matplotlib.pylab as pylab<EOL>pylab.show._needmain = False<EOL>pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)<EOL>

Activate the given backend and set interactive to True.


<EOL>s = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>)<EOL>exec(s, user_ns)<EOL>if import_all:<EOL><INDENT>s = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>exec(s, user_ns)<EOL><DEDENT>

Import the standard pylab symbols into user_ns.


def configure_inline_support(shell, backend, user_ns=None):

<EOL>try:<EOL><INDENT>from IPython.zmq.pylab.backend_inline import InlineBackend<EOL><DEDENT>except ImportError:<EOL><INDENT>return<EOL><DEDENT>user_ns = shell.user_ns if user_ns is None else user_ns<EOL>cfg = InlineBackend.instance(config=shell.config)<EOL>cfg.shell = shell<EOL>if cfg not in shell.configurables:<EOL><INDENT>shell.configurables.append(cfg)<EOL><DEDENT>if backend == backends['<STR_LIT>']:<EOL><INDENT>from IPython.zmq.pylab.backend_inline import flush_figures<EOL>from matplotlib import pyplot<EOL>shell.register_post_execute(flush_figures)<EOL>pyplot.rcParams.update(cfg.rc)<EOL>user_ns['<STR_LIT>'] = pyplot.figsize = figsize<EOL><DEDENT>fmt = cfg.figure_format<EOL>select_figure_format(shell, fmt)<EOL>from IPython.core.display import display<EOL>user_ns['<STR_LIT>'] = display<EOL>user_ns['<STR_LIT>'] = getfigs<EOL>

Configure an IPython shell object for matplotlib use.

    Parameters
    ----------
    shell : InteractiveShell instance

    backend : matplotlib backend

    user_ns : dict
      A namespace where all configured variables will be placed.  If not given,
      the `user_ns` attribute of the shell object is used.


def pylab_activate(user_ns, gui=None, import_all=True, shell=None):

gui, backend = find_gui_and_backend(gui)<EOL>activate_matplotlib(backend)<EOL>import_pylab(user_ns, import_all)<EOL>if shell is not None:<EOL><INDENT>configure_inline_support(shell, backend, user_ns)<EOL><DEDENT>print("""<STR_LIT>""" % backend)<EOL>sys.stdout.flush()<EOL>return gui<EOL>

Activate pylab mode in the user's namespace.

    Loads and initializes numpy, matplotlib and friends for interactive use.

    Parameters
    ----------
    user_ns : dict
      Namespace where the imports will occur.

    gui : optional, string
      A valid gui name following the conventions of the %gui magic.

    import_all : optional, boolean
      If true, an 'import *' is done from numpy and pylab.

    Returns
    -------
    The actual gui used (if not given as input, it was obtained from matplotlib
    itself, and will be needed next to configure IPython's gui integration.


<EOL>return (identifier in ip.user_nsor identifier in ip.user_global_nsor identifier in ip.ns_table['<STR_LIT>'])<EOL>

Is the given identifier defined in one of the namespaces which shadow
    the alias and magic namespaces?  Note that an identifier is different
    than ifun, because it can not contain a '.' character.


self._transformers = []<EOL>for transformer_cls in _default_transformers:<EOL><INDENT>transformer_cls(<EOL>shell=self.shell, prefilter_manager=self, config=self.config<EOL>)<EOL><DEDENT>


self._transformers.sort(key=lambda x: x.priority)<EOL>

Sort the transformers by priority.

        This must be called after the priority of a transformer is changed.
        The :meth:`register_transformer` method calls this automatically.


return self._transformers<EOL>

Return a list of checkers, sorted by priority.


if transformer not in self._transformers:<EOL><INDENT>self._transformers.append(transformer)<EOL>self.sort_transformers()<EOL><DEDENT>


if transformer in self._transformers:<EOL><INDENT>self._transformers.remove(transformer)<EOL><DEDENT>


self._checkers = []<EOL>for checker in _default_checkers:<EOL><INDENT>checker(<EOL>shell=self.shell, prefilter_manager=self, config=self.config<EOL>)<EOL><DEDENT>


self._checkers.sort(key=lambda x: x.priority)<EOL>

Sort the checkers by priority.

        This must be called after the priority of a checker is changed.
        The :meth:`register_checker` method calls this automatically.


return self._checkers<EOL>


if checker not in self._checkers:<EOL><INDENT>self._checkers.append(checker)<EOL>self.sort_checkers()<EOL><DEDENT>


if checker in self._checkers:<EOL><INDENT>self._checkers.remove(checker)<EOL><DEDENT>


self._handlers = {}<EOL>self._esc_handlers = {}<EOL>for handler in _default_handlers:<EOL><INDENT>handler(<EOL>shell=self.shell, prefilter_manager=self, config=self.config<EOL>)<EOL><DEDENT>


return self._handlers<EOL>


def register_handler(self, name, handler, esc_strings):

self._handlers[name] = handler<EOL>for esc_str in esc_strings:<EOL><INDENT>self._esc_handlers[esc_str] = handler<EOL><DEDENT>

Register a handler instance by name with esc_strings.


def unregister_handler(self, name, handler, esc_strings):

try:<EOL><INDENT>del self._handlers[name]<EOL><DEDENT>except KeyError:<EOL><INDENT>pass<EOL><DEDENT>for esc_str in esc_strings:<EOL><INDENT>h = self._esc_handlers.get(esc_str)<EOL>if h is handler:<EOL><INDENT>del self._esc_handlers[esc_str]<EOL><DEDENT><DEDENT>

Unregister a handler instance by name with esc_strings.


return self._handlers.get(name)<EOL>


return self._esc_handlers.get(esc_str)<EOL>


<EOL>handler = self.find_handler(line_info)<EOL>return handler.handle(line_info)<EOL>

Prefilter a line that has been converted to a LineInfo object.

        This implements the checker/handler part of the prefilter pipe.


for checker in self.checkers:<EOL><INDENT>if checker.enabled:<EOL><INDENT>handler = checker.check(line_info)<EOL>if handler:<EOL><INDENT>return handler<EOL><DEDENT><DEDENT><DEDENT>return self.get_handler_by_name('<STR_LIT>')<EOL>

Find a handler for the line_info by trying checkers.


def transform_line(self, line, continue_prompt):

for transformer in self.transformers:<EOL><INDENT>if transformer.enabled:<EOL><INDENT>line = transformer.transform(line, continue_prompt)<EOL><DEDENT><DEDENT>return line<EOL>

Calls the enabled transformers in order of increasing priority.


def prefilter_line(self, line, continue_prompt=False):

<EOL>self.shell._last_input_line = line<EOL>if not line:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>if not continue_prompt or (continue_prompt and self.multi_line_specials):<EOL><INDENT>line = self.transform_line(line, continue_prompt)<EOL><DEDENT>line_info = LineInfo(line, continue_prompt)<EOL>stripped = line.strip()<EOL>normal_handler = self.get_handler_by_name('<STR_LIT>')<EOL>if not stripped:<EOL><INDENT>if not continue_prompt:<EOL><INDENT>self.shell.displayhook.prompt_count -= <NUM_LIT:1><EOL><DEDENT>return normal_handler.handle(line_info)<EOL><DEDENT>if continue_prompt and not self.multi_line_specials:<EOL><INDENT>return normal_handler.handle(line_info)<EOL><DEDENT>prefiltered = self.prefilter_line_info(line_info)<EOL>return prefiltered<EOL>

Prefilter a single input line as text.

        This method prefilters a single line of text by calling the
        transformers and then the checkers/handlers.


def prefilter_lines(self, lines, continue_prompt=False):

llines = lines.rstrip('<STR_LIT:\n>').split('<STR_LIT:\n>')<EOL>if len(llines) > <NUM_LIT:1>:<EOL><INDENT>out = '<STR_LIT:\n>'.join([self.prefilter_line(line, lnum><NUM_LIT:0>)<EOL>for lnum, line in enumerate(llines) ])<EOL><DEDENT>else:<EOL><INDENT>out = self.prefilter_line(llines[<NUM_LIT:0>], continue_prompt)<EOL><DEDENT>return out<EOL>

Prefilter multiple input lines of text.

        This is the main entry point for prefiltering multiple lines of
        input.  This simply calls :meth:`prefilter_line` for each line of
        input.

        This covers cases where there are multiple lines in the user entry,
        which is the case when the user goes back to a multiline history
        entry and presses enter.


def transform(self, line, continue_prompt):

return None<EOL>

Transform a line, returning the new one.


return None<EOL>

Inspect line_info and return a handler instance or None.


if line_info.line.endswith('<STR_LIT>'):<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Emacs ipython-mode tags certain input lines.


obj = self.shell.user_ns.get(line_info.ifun, None)<EOL>if isinstance(obj, IPyAutocall):<EOL><INDENT>obj.set_ip(self.shell)<EOL>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Instances of IPyAutocall in user_ns get autocalled immediately


<EOL>if line_info.continue_promptand self.prefilter_manager.multi_line_specials:<EOL><INDENT>if line_info.esc == ESC_MAGIC:<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Allow ! and !! in multi-line statements if multi_line_specials is on


if line_info.line[-<NUM_LIT:1>] == ESC_HELPand line_info.esc != ESC_SHELLand line_info.esc != ESC_SH_CAP:<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if line_info.pre:<EOL><INDENT>return None<EOL><DEDENT>return self.prefilter_manager.get_handler_by_esc(line_info.esc)<EOL><DEDENT>

Check for escape character and return either a handler to handle it,
        or None if there is no escape char.


if line_info.the_rest:<EOL><INDENT>if line_info.the_rest[<NUM_LIT:0>] in '<STR_LIT>':<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Check to see if user is assigning to a var for the first time, in
        which case we want to avoid any sort of automagic / autocall games.

        This allows users to assign to either alias or magic names true python
        variables (the magic/alias systems always take second seat to true
        python code).  E.g. ls='hi', or ls,that=1,2


if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):<EOL><INDENT>return None<EOL><DEDENT>if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:<EOL><INDENT>return None<EOL><DEDENT>head = line_info.ifun.split('<STR_LIT:.>',<NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if is_shadowed(head, self.shell):<EOL><INDENT>return None<EOL><DEDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL>

If the ifun is magic, and automagic is on, run it.  Note: normal,
        non-auto magic would already have been triggered via '%' in
        check_esc_chars. This just checks for automagic.  Also, before
        triggering the magic handler, make sure that there is nothing in the
        user namespace which could shadow it.


<EOL>head = line_info.ifun.split('<STR_LIT:.>',<NUM_LIT:1>)[<NUM_LIT:0>]<EOL>if line_info.ifun not in self.shell.alias_manageror head not in self.shell.alias_manageror is_shadowed(head, self.shell):<EOL><INDENT>return None<EOL><DEDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL>

Check if the initital identifier on the line is an alias.


if line_info.the_rest and line_info.the_rest[<NUM_LIT:0>] in '<STR_LIT>':<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

If the 'rest' of the line begins with a function call or pretty much
        any python operator, we should simply execute the line (regardless of
        whether or not there's a possible autocall expansion).  This avoids
        spurious (and very confusing) geattr() accesses.


if not self.shell.autocall:<EOL><INDENT>return None<EOL><DEDENT>oinfo = line_info.ofind(self.shell) <EOL>if not oinfo['<STR_LIT>']:<EOL><INDENT>return None<EOL><DEDENT>if callable(oinfo['<STR_LIT>'])and (not self.exclude_regexp.match(line_info.the_rest))and self.function_name_regexp.match(line_info.ifun):<EOL><INDENT>return self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Check if the initial word/function is callable and autocall is on.


<EOL>line = line_info.line<EOL>continue_prompt = line_info.continue_prompt<EOL>if (continue_prompt and<EOL>self.shell.autoindent and<EOL>line.isspace() and<EOL><NUM_LIT:0> < abs(len(line) - self.shell.indent_current_nsp) <= <NUM_LIT:2>):<EOL><INDENT>line = '<STR_LIT>'<EOL><DEDENT>return line<EOL>

Handle normal input lines. Use as a template for handlers.


transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)<EOL>line_out = '<STR_LIT>' % (line_info.pre_whitespace, transformed)<EOL>return line_out<EOL>


magic_handler = self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL>line = line_info.line<EOL>if line.lstrip().startswith(ESC_SH_CAP):<EOL><INDENT>new_rest = line.lstrip()[<NUM_LIT:2>:]<EOL>line_info.line = '<STR_LIT>' % (ESC_MAGIC, new_rest)<EOL>line_info.ifun = '<STR_LIT>'<EOL>line_info.the_rest = new_rest<EOL>return magic_handler.handle(line_info)<EOL><DEDENT>else:<EOL><INDENT>cmd = line.lstrip().lstrip(ESC_SHELL)<EOL>line_out = '<STR_LIT>' % (line_info.pre_whitespace, cmd)<EOL><DEDENT>return line_out<EOL>

Execute the line in a shell, empty return value


ifun    = line_info.ifun<EOL>the_rest = line_info.the_rest<EOL>cmd = '<STR_LIT>' % (line_info.pre_whitespace,<EOL>(ifun + "<STR_LIT:U+0020>" + the_rest))<EOL>return cmd<EOL>


line    = line_info.line<EOL>ifun    = line_info.ifun<EOL>the_rest = line_info.the_rest<EOL>pre     = line_info.pre<EOL>esc     = line_info.esc<EOL>continue_prompt = line_info.continue_prompt<EOL>obj = line_info.ofind(self.shell)['<STR_LIT>']<EOL>if continue_prompt:<EOL><INDENT>return line<EOL><DEDENT>force_auto = isinstance(obj, IPyAutocall)<EOL>try:<EOL><INDENT>auto_rewrite = obj.rewrite<EOL><DEDENT>except Exception:<EOL><INDENT>auto_rewrite = True<EOL><DEDENT>if esc == ESC_QUOTE:<EOL><INDENT>newcmd = '<STR_LIT>' % (ifun,'<STR_LIT>'.join(the_rest.split()) )<EOL><DEDENT>elif esc == ESC_QUOTE2:<EOL><INDENT>newcmd = '<STR_LIT>' % (ifun,the_rest)<EOL><DEDENT>elif esc == ESC_PAREN:<EOL><INDENT>newcmd = '<STR_LIT>' % (ifun,"<STR_LIT:U+002C>".join(the_rest.split()))<EOL><DEDENT>else:<EOL><INDENT>if force_auto:<EOL><INDENT>do_rewrite = not the_rest.startswith('<STR_LIT:(>')<EOL><DEDENT>else:<EOL><INDENT>if not the_rest:<EOL><INDENT>do_rewrite = (self.shell.autocall >= <NUM_LIT:2>)<EOL><DEDENT>elif the_rest.startswith('<STR_LIT:[>') and hasattr(obj, '<STR_LIT>'):<EOL><INDENT>do_rewrite = False<EOL><DEDENT>else:<EOL><INDENT>do_rewrite = True<EOL><DEDENT><DEDENT>if do_rewrite:<EOL><INDENT>if the_rest.endswith('<STR_LIT:;>'):<EOL><INDENT>newcmd = '<STR_LIT>' % (ifun.rstrip(),the_rest[:-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>newcmd = '<STR_LIT>' % (ifun.rstrip(), the_rest)                <EOL><DEDENT><DEDENT>else:<EOL><INDENT>normal_handler = self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL>return normal_handler.handle(line_info)<EOL><DEDENT><DEDENT>if auto_rewrite:<EOL><INDENT>self.shell.auto_rewrite_input(newcmd)<EOL><DEDENT>return newcmd<EOL>

Handle lines which can be auto-executed, quoting if requested.


normal_handler = self.prefilter_manager.get_handler_by_name('<STR_LIT>')<EOL>line = line_info.line<EOL>try:<EOL><INDENT>codeop.compile_command(line)<EOL><DEDENT>except SyntaxError:<EOL><INDENT>if line[<NUM_LIT:0>]==ESC_HELP:<EOL><INDENT>line = line[<NUM_LIT:1>:]<EOL><DEDENT>elif line[-<NUM_LIT:1>]==ESC_HELP:<EOL><INDENT>line = line[:-<NUM_LIT:1>]<EOL><DEDENT>if line:<EOL><INDENT>self.shell.magic('<STR_LIT>' % line_info.ifun)<EOL><DEDENT>else:<EOL><INDENT>self.shell.show_usage()<EOL><DEDENT>return '<STR_LIT>' <EOL><DEDENT>except:<EOL><INDENT>raise<EOL>return normal_handler.handle(line_info)<EOL><DEDENT>else:<EOL><INDENT>return normal_handler.handle(line_info)<EOL><DEDENT>

Try to get some help for the object.

        obj? or ?obj   -> basic information.
        obj?? or ??obj -> more details.


<EOL>return line_info.line<EOL>

Handle input lines marked by python-mode.


ini_spaces = ini_spaces_re.match(s)<EOL>if ini_spaces:<EOL><INDENT>return ini_spaces.end()<EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>

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


if not src: return False<EOL>ll  = src.splitlines()[-<NUM_LIT:1>]<EOL>return (ll == '<STR_LIT>') or ll.isspace()<EOL>

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<EOL>new_src = '<STR_LIT:\n>'.join(['<STR_LIT>'] + src.splitlines()[-<NUM_LIT:2>:])<EOL>return (bool(last_two_blanks_re.match(new_src)) or<EOL>bool(last_two_blanks_re2.match(new_src)) )<EOL>

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.


return re.sub('<STR_LIT>', '<STR_LIT>', src)<EOL>

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.


readline = StringIO(src).readline<EOL>toktypes = set()<EOL>try:<EOL><INDENT>for t in tokenize.generate_tokens(readline):<EOL><INDENT>toktypes.add(t[<NUM_LIT:0>])<EOL><DEDENT><DEDENT>except tokenize.TokenError:<EOL><INDENT>pass<EOL><DEDENT>return(tokenize.COMMENT in toktypes)<EOL>

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.


<EOL>encoding = getattr(sys.stdin, '<STR_LIT>', None)<EOL>if encoding is None:<EOL><INDENT>encoding = '<STR_LIT:ascii>'<EOL><DEDENT>return encoding<EOL>

Return the default standard input encoding.

    If sys.stdin has no encoding, 'ascii' is returned.


m = _assign_system_re.match(line)<EOL>if m is not None:<EOL><INDENT>cmd = m.group('<STR_LIT>')<EOL>lhs = m.group('<STR_LIT>')<EOL>new_line = '<STR_LIT>' % (lhs, cmd)<EOL>return new_line<EOL><DEDENT>return line<EOL>


m = _assign_magic_re.match(line)<EOL>if m is not None:<EOL><INDENT>cmd = m.group('<STR_LIT>')<EOL>lhs = m.group('<STR_LIT>')<EOL>new_line = '<STR_LIT>' % (lhs, cmd)<EOL>return new_line<EOL><DEDENT>return line<EOL>


if not line or line.isspace():<EOL><INDENT>return line<EOL><DEDENT>m = _classic_prompt_re.match(line)<EOL>if m:<EOL><INDENT>return line[len(m.group(<NUM_LIT:0>)):]<EOL><DEDENT>else:<EOL><INDENT>return line<EOL><DEDENT>

Handle inputs that start with '>>> ' syntax.


if not line or line.isspace():<EOL><INDENT>return line<EOL><DEDENT>m = _ipy_prompt_re.match(line)<EOL>if m:<EOL><INDENT>return line[len(m.group(<NUM_LIT:0>)):]<EOL><DEDENT>else:<EOL><INDENT>return line<EOL><DEDENT>

Handle inputs that start classic IPython prompt syntax.


def _make_help_call(target, esc, lspace, next_input=None):

method  = '<STR_LIT>' if esc == '<STR_LIT>'else '<STR_LIT>' if '<STR_LIT:*>' in targetelse '<STR_LIT>'<EOL>arg = "<STR_LIT:U+0020>".join([method, target])<EOL>if next_input is None:<EOL><INDENT>return '<STR_LIT>' % (lspace, arg)<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>' %(lspace, next_input, arg)<EOL><DEDENT>

Prepares a pinfo(2)/psearch call from a target name and the escape
    (i.e. ? or ??)


m = _help_end_re.search(line)<EOL>if m is None or has_comment(line):<EOL><INDENT>return line<EOL><DEDENT>target = m.group(<NUM_LIT:1>)<EOL>esc = m.group(<NUM_LIT:3>)<EOL>lspace = _initial_space_re.match(line).group(<NUM_LIT:0>)<EOL>next_input = line.rstrip('<STR_LIT:?>') if line.strip() != m.group(<NUM_LIT:0>) else None<EOL>return _make_help_call(target, esc, lspace, next_input)<EOL>


self._buffer = []<EOL>self._compile = codeop.CommandCompiler()<EOL>self.encoding = get_input_encoding()<EOL>self.input_mode = InputSplitter.input_mode if input_mode is Noneelse input_mode<EOL>

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.indent_spaces = <NUM_LIT:0><EOL>self._buffer[:] = []<EOL>self.source = '<STR_LIT>'<EOL>self.code = None<EOL>self._is_complete = False<EOL>self._full_dedent = False<EOL>

Reset the input buffer and associated state.


out = self.source<EOL>self.reset()<EOL>return out<EOL>

Return the input source and perform a full reset.


if self.input_mode == '<STR_LIT>':<EOL><INDENT>self.reset()<EOL><DEDENT>self._store(lines)<EOL>source = self.source<EOL>self.code, self._is_complete = None, None<EOL>if source.rstrip().endswith('<STR_LIT:\\>'):<EOL><INDENT>return False<EOL><DEDENT>self._update_indent(lines)<EOL>try:<EOL><INDENT>self.code = self._compile(source, symbol="<STR_LIT>")<EOL><DEDENT>except (SyntaxError, OverflowError, ValueError, TypeError,<EOL>MemoryError):<EOL><INDENT>self._is_complete = True<EOL><DEDENT>else:<EOL><INDENT>self._is_complete = self.code is not None<EOL><DEDENT>return self._is_complete<EOL>

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.


<EOL>if not self._is_complete:<EOL><INDENT>return True<EOL><DEDENT>if self.indent_spaces==<NUM_LIT:0>:<EOL><INDENT>if self.input_mode=='<STR_LIT>':<EOL><INDENT>if not self._full_dedent:<EOL><INDENT>return False<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>code_ast = ast.parse(u'<STR_LIT>'.join(self._buffer))<EOL><DEDENT>except Exception:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>if len(code_ast.body) == <NUM_LIT:1>:<EOL><INDENT>return False<EOL><DEDENT><DEDENT><DEDENT><DEDENT>last_line = self.source.splitlines()[-<NUM_LIT:1>]<EOL>return bool(last_line and not last_line.isspace())<EOL>

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.


indent_spaces = self.indent_spaces<EOL>full_dedent = self._full_dedent<EOL>inisp = num_ini_spaces(line)<EOL>if inisp < indent_spaces:<EOL><INDENT>indent_spaces = inisp<EOL>if indent_spaces <= <NUM_LIT:0>:<EOL><INDENT>full_dedent = True<EOL><DEDENT><DEDENT>if line.rstrip()[-<NUM_LIT:1>] == '<STR_LIT::>':<EOL><INDENT>indent_spaces += <NUM_LIT:4><EOL><DEDENT>elif dedent_re.match(line):<EOL><INDENT>indent_spaces -= <NUM_LIT:4><EOL>if indent_spaces <= <NUM_LIT:0>:<EOL><INDENT>full_dedent = True<EOL><DEDENT><DEDENT>if indent_spaces < <NUM_LIT:0>:<EOL><INDENT>indent_spaces = <NUM_LIT:0><EOL><DEDENT>return indent_spaces, full_dedent<EOL>

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.


def _store(self, lines, buffer=None, store='<STR_LIT:source>'):

if buffer is None:<EOL><INDENT>buffer = self._buffer<EOL><DEDENT>if lines.endswith('<STR_LIT:\n>'):<EOL><INDENT>buffer.append(lines)<EOL><DEDENT>else:<EOL><INDENT>buffer.append(lines+'<STR_LIT:\n>')<EOL><DEDENT>setattr(self, store, self._set_source(buffer))<EOL>

Store one or more lines of input.

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


cmd = line_info.line.lstrip().lstrip(ESC_SHELL)<EOL>return '<STR_LIT>' % (line_info.pre, cmd)<EOL>


cmd = line_info.line.lstrip()[<NUM_LIT:2>:]<EOL>return '<STR_LIT>' % (line_info.pre, cmd)<EOL>


<EOL>if not line_info.line[<NUM_LIT:1>:]:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)<EOL>


tpl = '<STR_LIT>'<EOL>cmd = '<STR_LIT:U+0020>'.join([line_info.ifun, line_info.the_rest]).strip()<EOL>return tpl % (line_info.pre, cmd)<EOL>


return '<STR_LIT>' % (line_info.pre, line_info.ifun,<EOL>'<STR_LIT>'.join(line_info.the_rest.split()) )<EOL>


return '<STR_LIT>' % (line_info.pre, line_info.ifun,<EOL>line_info.the_rest)<EOL>


return '<STR_LIT>' % (line_info.pre, line_info.ifun,<EOL>"<STR_LIT:U+002CU+0020>".join(line_info.the_rest.split()))<EOL>


<EOL>if not line or line.isspace():<EOL><INDENT>return line<EOL><DEDENT>line_info = LineInfo(line)<EOL>if not line_info.esc in self.tr:<EOL><INDENT>return line<EOL><DEDENT>return self.tr[line_info.esc](line_info)<EOL>

Class to transform lines that are explicitly escaped out.

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


super(IPythonInputSplitter, self).reset()<EOL>self._buffer_raw[:] = []<EOL>self.source_raw = '<STR_LIT>'<EOL>self.cell_magic_parts = []<EOL>self.processing_cell_magic = False<EOL>


out = self.source<EOL>out_r = self.source_raw<EOL>self.reset()<EOL>return out, out_r<EOL>

Return input and raw source and perform a full reset.


self.processing_cell_magic = True<EOL>first, _, body = lines.partition('<STR_LIT:\n>')<EOL>magic_name, _, line = first.partition('<STR_LIT:U+0020>')<EOL>magic_name = magic_name.lstrip(ESC_MAGIC)<EOL>self.cell_magic_parts = [body]<EOL>tpl = '<STR_LIT>'<EOL>tlines = tpl % (magic_name, line)<EOL>self._store(tlines)<EOL>self._store(lines, self._buffer_raw, '<STR_LIT>')<EOL>self._is_complete = last_blank(lines)<EOL>return self._is_complete<EOL>

Process lines when they start with %%, which marks cell magics.


<EOL>self._store(lines, self._buffer_raw, '<STR_LIT>')<EOL>self.cell_magic_parts.append(lines)<EOL>last_block = self.cell_magic_parts[-<NUM_LIT:1>]<EOL>self._is_complete = last_blank(last_block) and lines.isspace()<EOL>return self._is_complete<EOL>

Append new content for a cell magic in line mode.


self.reset()<EOL>self.push(cell)<EOL>return self.source_reset()<EOL>


if not lines:<EOL><INDENT>return super(IPythonInputSplitter, self).push(lines)<EOL><DEDENT>lines = cast_unicode(lines, self.encoding)<EOL>if lines.startswith('<STR_LIT>') and not(len(lines.splitlines()) == <NUM_LIT:1> and lines.strip().endswith('<STR_LIT:?>')):<EOL><INDENT>return self._handle_cell_magic(lines)<EOL><DEDENT>if self.input_mode == '<STR_LIT>' and self.processing_cell_magic:<EOL><INDENT>return self._line_mode_cell_append(lines)<EOL><DEDENT>lines_list = lines.splitlines()<EOL>transforms = [transform_ipy_prompt, transform_classic_prompt,<EOL>transform_help_end, transform_escaped,<EOL>transform_assign_system, transform_assign_magic]<EOL>changed_input_mode = False<EOL>if self.input_mode == '<STR_LIT>':<EOL><INDENT>self.reset()<EOL>changed_input_mode = True<EOL>saved_input_mode = '<STR_LIT>'<EOL>self.input_mode = '<STR_LIT>'<EOL><DEDENT>self._store(lines, self._buffer_raw, '<STR_LIT>')<EOL>try:<EOL><INDENT>push = super(IPythonInputSplitter, self).push<EOL>buf = self._buffer<EOL>for line in lines_list:<EOL><INDENT>if self._is_complete or not buf or(buf and buf[-<NUM_LIT:1>].rstrip().endswith(('<STR_LIT::>', '<STR_LIT:U+002C>'))):<EOL><INDENT>for f in transforms:<EOL><INDENT>line = f(line)<EOL><DEDENT><DEDENT>out = push(line)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>if changed_input_mode:<EOL><INDENT>self.input_mode = saved_input_mode<EOL><DEDENT><DEDENT>return out<EOL>

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.


ex_colors = ColorSchemeTable()<EOL>C = TermColors <EOL>ex_colors.add_scheme(ColorScheme(<EOL>'<STR_LIT>',<EOL>topline = C.NoColor,<EOL>filename = C.NoColor,<EOL>lineno = C.NoColor,<EOL>name = C.NoColor,<EOL>vName = C.NoColor,<EOL>val = C.NoColor,<EOL>em = C.NoColor,<EOL>normalEm = C.NoColor,<EOL>filenameEm = C.NoColor,<EOL>linenoEm = C.NoColor,<EOL>nameEm = C.NoColor,<EOL>valEm = C.NoColor,<EOL>excName = C.NoColor,<EOL>line = C.NoColor,<EOL>caret = C.NoColor,<EOL>Normal = C.NoColor<EOL>))<EOL>ex_colors.add_scheme(ColorScheme(<EOL>'<STR_LIT>',<EOL>topline = C.LightRed,<EOL>filename = C.Green,<EOL>lineno = C.Green,<EOL>name = C.Purple,<EOL>vName = C.Cyan,<EOL>val = C.Green,<EOL>em = C.LightCyan,<EOL>normalEm = C.LightCyan,<EOL>filenameEm = C.LightGreen,<EOL>linenoEm = C.LightGreen,<EOL>nameEm = C.LightPurple,<EOL>valEm = C.LightBlue,<EOL>excName = C.LightRed,<EOL>line = C.Yellow,<EOL>caret = C.White,<EOL>Normal = C.Normal<EOL>))<EOL>ex_colors.add_scheme(ColorScheme(<EOL>'<STR_LIT>',<EOL>topline = C.Red,<EOL>filename = C.LightGreen,<EOL>lineno = C.LightGreen,<EOL>name = C.LightPurple,<EOL>vName = C.Cyan,<EOL>val = C.LightGreen,<EOL>em = C.Cyan,<EOL>normalEm = C.Cyan,<EOL>filenameEm = C.Green,<EOL>linenoEm = C.Green,<EOL>nameEm = C.Purple,<EOL>valEm = C.Blue,<EOL>excName = C.Red,<EOL>line = C.Red,<EOL>caret = C.Normal,<EOL>Normal = C.Normal,<EOL>))<EOL>return ex_colors<EOL>

Return a color table with fields for exception reporting.

    The table is an instance of ColorSchemeTable with schemes added for
    'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
    in.

    Examples:

    >>> ec = exception_colors()
    >>> ec.active_scheme_name
    ''
    >>> print ec.active_colors
    None

    Now we activate a color scheme:
    >>> ec.set_active_scheme('NoColor')
    >>> ec.active_scheme_name
    'NoColor'
    >>> sorted(ec.active_colors.keys())
    ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
    'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
    'val', 'valEm']


def publish_display_data(source, data, metadata=None):

from IPython.core.interactiveshell import InteractiveShell<EOL>InteractiveShell.instance().display_pub.publish(<EOL>source,<EOL>data,<EOL>metadata<EOL>)<EOL>

Publish data and metadata to all frontends.

    See the ``display_data`` message in the messaging documentation for
    more details about this message type.

    The following MIME types are currently implemented:

    * text/plain
    * text/html
    * text/latex
    * application/json
    * application/javascript
    * image/png
    * image/jpeg
    * image/svg+xml

    Parameters
    ----------
    source : str
        A string that give the function or method that created the data,
        such as 'IPython.core.page'.
    data : dict
        A dictionary having keys that are valid MIME types (like
        'text/plain' or 'image/svg+xml') and values that are the data for
        that MIME type. The data itself must be a JSON'able data
        structure. Minimally all data should have the 'text/plain' data,
        which can be displayed by all frontends. If more than the plain
        text is given, it is up to the frontend to decide which
        representation to use.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


publish_display_data(<EOL>u'<STR_LIT>',<EOL>{'<STR_LIT>':data},<EOL>metadata=metadata<EOL>)<EOL>

Publish raw text data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw text data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


Publish raw HTML data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw HTML data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


Publish raw LaTeX data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw LaTeX data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


Publish raw binary PNG data to all frontends.

    Parameters
    ----------
    data : str/bytes
        The raw binary PNG data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


Publish raw binary JPEG data to all frontends.

    Parameters
    ----------
    data : str/bytes
        The raw binary JPEG data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


Publish raw SVG data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw SVG data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


publish_display_data(<EOL>u'<STR_LIT>',<EOL>{'<STR_LIT:application/json>':data},<EOL>metadata=metadata<EOL>)<EOL>

Publish raw JSON data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw JSON data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


Publish raw Javascript data to all frontends.

    Parameters
    ----------
    data : unicode
        The raw Javascript data to publish.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data.


def _validate_data(self, source, data, metadata=None):

if not isinstance(source, basestring):<EOL><INDENT>raise TypeError('<STR_LIT>' % source)<EOL><DEDENT>if not isinstance(data, dict):<EOL><INDENT>raise TypeError('<STR_LIT>' % data)<EOL><DEDENT>if metadata is not None:<EOL><INDENT>if not isinstance(metadata, dict):<EOL><INDENT>raise TypeError('<STR_LIT>' % data)<EOL><DEDENT><DEDENT>

Validate the display data.

        Parameters
        ----------
        source : str
            The fully dotted name of the callable that created the data, like
            :func:`foo.bar.my_formatter`.
        data : dict
            The formata data dictionary.
        metadata : dict
            Any metadata for the data.


def publish(self, source, data, metadata=None):

<EOL>if data.has_key('<STR_LIT>'):<EOL><INDENT>print(data['<STR_LIT>'], file=io.stdout)<EOL><DEDENT>

Publish data and metadata to all frontends.

        See the ``display_data`` message in the messaging documentation for
        more details about this message type.

        The following MIME types are currently implemented:

        * text/plain
        * text/html
        * text/latex
        * application/json
        * application/javascript
        * image/png
        * image/jpeg
        * image/svg+xml

        Parameters
        ----------
        source : str
            A string that give the function or method that created the data,
            such as 'IPython.core.page'.
        data : dict
            A dictionary having keys that are valid MIME types (like
            'text/plain' or 'image/svg+xml') and values that are the data for
            that MIME type. The data itself must be a JSON'able data
            structure. Minimally all data should have the 'text/plain' data,
            which can be displayed by all frontends. If more than the plain
            text is given, it is up to the frontend to decide which
            representation to use.
        metadata : dict
            A dictionary for metadata related to the data. This can contain
            arbitrary key, value pairs that frontends can use to interpret
            the data.


def clear_output(self, stdout=True, stderr=True, other=True):

if stdout:<EOL><INDENT>print('<STR_LIT>', file=io.stdout, end='<STR_LIT>')<EOL>io.stdout.flush()<EOL><DEDENT>if stderr:<EOL><INDENT>print('<STR_LIT>', file=io.stderr, end='<STR_LIT>')<EOL>io.stderr.flush()<EOL><DEDENT>

Clear the output of the cell receiving output.


<EOL>if path == '<STR_LIT>':<EOL><INDENT>path = '<STR_LIT:.>'<EOL><DEDENT>if os.path.isdir(path):<EOL><INDENT>folder_list = os.listdir(path)<EOL><DEDENT>elif path.endswith('<STR_LIT>'):<EOL><INDENT>try:<EOL><INDENT>folder_list = [f for f in zipimporter(path)._files]<EOL><DEDENT>except:<EOL><INDENT>folder_list = []<EOL><DEDENT><DEDENT>else:<EOL><INDENT>folder_list = []<EOL><DEDENT>if not folder_list:<EOL><INDENT>return []<EOL><DEDENT>isfile = os.path.isfile<EOL>pjoin = os.path.join<EOL>basename = os.path.basename<EOL>def is_importable_file(path):<EOL><INDENT>"""<STR_LIT>"""<EOL>name, extension = os.path.splitext( path )<EOL>return import_re.match(path) and py3compat.isidentifier(name)<EOL><DEDENT>folder_list = [p for p in folder_list<EOL>if isfile(pjoin(path, p,'<STR_LIT>'))<EOL>or is_importable_file(p) ]<EOL>return [basename(p).split('<STR_LIT:.>')[<NUM_LIT:0>] for p in folder_list]<EOL>

Return the list containing the names of the modules available in the given
folder.


ip = get_ipython()<EOL>if '<STR_LIT>' in ip.db:<EOL><INDENT>return ip.db['<STR_LIT>']<EOL><DEDENT>t = time()<EOL>store = False<EOL>modules = list(sys.builtin_module_names)<EOL>for path in sys.path:<EOL><INDENT>modules += module_list(path)<EOL>if time() - t >= TIMEOUT_STORAGE and not store:<EOL><INDENT>store = True<EOL>print("<STR_LIT>")<EOL>print("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>sys.stdout.flush()<EOL><DEDENT>if time() - t > TIMEOUT_GIVEUP:<EOL><INDENT>print("<STR_LIT>")<EOL>ip.db['<STR_LIT>'] = []<EOL>return []<EOL><DEDENT><DEDENT>modules = set(modules)<EOL>if '<STR_LIT>' in modules:<EOL><INDENT>modules.remove('<STR_LIT>')<EOL><DEDENT>modules = list(modules)<EOL>if store:<EOL><INDENT>ip.db['<STR_LIT>'] = modules<EOL><DEDENT>return modules<EOL>

Returns a list containing the names of all the modules available in the
folders of the pythonpath.


if isinstance(completions, basestring):<EOL><INDENT>completions = completions.split()<EOL><DEDENT>def do_complete(self, event):<EOL><INDENT>return completions<EOL><DEDENT>get_ipython().set_hook('<STR_LIT>',do_complete, str_key = cmd)<EOL>

Easily create a trivial completer for a command.

    Takes either a list of completions, or all completions in string (that will
    be split on whitespace).

    Example::

        [d:\ipython]|1> import ipy_completers
        [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
        [d:\ipython]|3> foo b<TAB>
        bar baz
        [d:\ipython]|3> foo ba


words = line.split('<STR_LIT:U+0020>')<EOL>nwords = len(words)<EOL>if nwords == <NUM_LIT:3> and words[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>return ['<STR_LIT>']<EOL><DEDENT>if nwords < <NUM_LIT:3> and (words[<NUM_LIT:0>] in ['<STR_LIT>','<STR_LIT>']) :<EOL><INDENT>if nwords == <NUM_LIT:1>:<EOL><INDENT>return get_root_modules()<EOL><DEDENT>mod = words[<NUM_LIT:1>].split('<STR_LIT:.>')<EOL>if len(mod) < <NUM_LIT:2>:<EOL><INDENT>return get_root_modules()<EOL><DEDENT>completion_list = try_import('<STR_LIT:.>'.join(mod[:-<NUM_LIT:1>]), True)<EOL>return ['<STR_LIT:.>'.join(mod[:-<NUM_LIT:1>] + [el]) for el in completion_list]<EOL><DEDENT>if nwords >= <NUM_LIT:3> and words[<NUM_LIT:0>] == '<STR_LIT>':<EOL><INDENT>mod = words[<NUM_LIT:1>]<EOL>return try_import(mod)<EOL><DEDENT>

Returns a list containing the completion possibilities for an import line.

The line looks like this :
'import xml.d'
'from xml.dom import'


<EOL>return module_completion(event.line)<EOL>

Give completions after user has typed 'import ...' or 'from ...


comps = arg_split(event.line, strict=False)<EOL>relpath = (len(comps) > <NUM_LIT:1> and comps[-<NUM_LIT:1>] or '<STR_LIT>').strip("<STR_LIT>")<EOL>lglob = glob.glob<EOL>isdir = os.path.isdir<EOL>relpath, tilde_expand, tilde_val = expand_user(relpath)<EOL>dirs = [f.replace('<STR_LIT:\\>','<STR_LIT:/>') + "<STR_LIT:/>" for f in lglob(relpath+'<STR_LIT:*>') if isdir(f)]<EOL>if filter(magic_run_re.match, comps):<EOL><INDENT>pys =  [f.replace('<STR_LIT:\\>','<STR_LIT:/>') for f in lglob('<STR_LIT:*>')]<EOL><DEDENT>else:<EOL><INDENT>pys =  [f.replace('<STR_LIT:\\>','<STR_LIT:/>')<EOL>for f in lglob(relpath+'<STR_LIT>') + lglob(relpath+'<STR_LIT>') +<EOL>lglob(relpath + '<STR_LIT>')]<EOL><DEDENT>return [compress_user(p, tilde_expand, tilde_val) for p in dirs+pys]<EOL>

Complete files that end in .py or .ipy for the %run command.


ip = get_ipython()<EOL>relpath = event.symbol<EOL>if event.line.endswith('<STR_LIT>') or '<STR_LIT>' in event.line:<EOL><INDENT>bkms = self.db.get('<STR_LIT>', None)<EOL>if bkms:<EOL><INDENT>return bkms.keys()<EOL><DEDENT>else:<EOL><INDENT>return []<EOL><DEDENT><DEDENT>if event.symbol == '<STR_LIT:->':<EOL><INDENT>width_dh = str(len(str(len(ip.user_ns['<STR_LIT>']) + <NUM_LIT:1>)))<EOL>fmt = '<STR_LIT>' + width_dh +'<STR_LIT>'<EOL>ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['<STR_LIT>'])]<EOL>if len(ents) > <NUM_LIT:1>:<EOL><INDENT>return ents<EOL><DEDENT>return []<EOL><DEDENT>if event.symbol.startswith('<STR_LIT>'):<EOL><INDENT>return ["<STR_LIT>" + os.path.basename(d) for d in ip.user_ns['<STR_LIT>']]<EOL><DEDENT>relpath, tilde_expand, tilde_val = expand_user(relpath)<EOL>relpath = relpath.replace('<STR_LIT:\\>','<STR_LIT:/>')<EOL>found = []<EOL>for d in [f.replace('<STR_LIT:\\>','<STR_LIT:/>') + '<STR_LIT:/>' for f in glob.glob(relpath+'<STR_LIT:*>')<EOL>if os.path.isdir(f)]:<EOL><INDENT>if '<STR_LIT:U+0020>' in d:<EOL><INDENT>raise TryNext<EOL><DEDENT>found.append(d)<EOL><DEDENT>if not found:<EOL><INDENT>if os.path.isdir(relpath):<EOL><INDENT>return [compress_user(relpath, tilde_expand, tilde_val)]<EOL><DEDENT>bks = self.db.get('<STR_LIT>',{}).iterkeys()<EOL>bkmatches = [s for s in bks if s.startswith(event.symbol)]<EOL>if bkmatches:<EOL><INDENT>return bkmatches<EOL><DEDENT>raise TryNext<EOL><DEDENT>return [compress_user(p, tilde_expand, tilde_val) for p in found]<EOL>

Completer function for cd, which only returns directories.


return '<STR_LIT>'.split()<EOL>


if sqlite3 is None:<EOL><INDENT>return []<EOL><DEDENT>else:<EOL><INDENT>return f(*a,**kw)<EOL><DEDENT>

return an empty list in the absence of sqlite