PK[bJȗ.rlipython/.__init__.py.un~VimUnDo'S_GZu*;Ÿ5Q̰U%۬  __version__ = ''Xr_Xn5_"Xn"from .completer import RLCompleter5_Xn"from .completer import RLCompleter5_Xn5_Xn5_Xnfrom 5_Xo"""5_ Xr__version__ = (0,0,1)5_ Xr__version__ = (0,0,15_ Xr__version__ = (0,0,1)5_ Xr version_info = (0,0,1)5_ Xrversion_info = (0,0,1)5_  Xr __version__ = ''5_ Xr __version__ = '.'5_Xr __version__ = '.'.join(version)5_Xr $__version__ = '.'.join(version_info)5_4Xr 5__version__ = '.'.join([str(x) for x in version_info)5PKh^bJ&F00rlipython/.completer.py.swpb0VIM 8.0pX`=1bussonniermatthiasairbears2-10-142-85-52.airbears2.1918.b~bussonniermatthias/dev/rlpython/rlpython/completer.pyutf-8 3210#"! UtpAadAHS=  R Q  A z y . _  a  v)F.i,-- re return None except IndexError: return self.matches[state] try: self.complete(text, line_buffer, cursor_pos) # This method computes the self.matches array # The normal production version is here else: import traceback; traceback.print_exc() except: self.complete(text, line_buffer, cursor_pos) try: if DEBUG: #DEBUG = True # dbg DEBUG = False # automatically detected and is used elsewhere). # flip the value in the first line, as the '# dbg' marker can be # this flag on temporarily by uncommenting the second form (don't # during development you suspect a bug in the completion code, turn # tricky, because readline unconditionally silences them. So if # Note: debugging exceptions that may occur in completion is very return None sys.stdout.flush() self.readline.insert_text('\t') if not (self.dumb_terminal or line_buffer.strip()): # we don't interfere with their own tab-completion mechanism. # don't apply this on 'dumb' terminals, such as emacs buffers, so # completions - is there a way around it? # It should be noted that at least pyreadline still shows file # (as long as autoindent is off). # Incidentally, this enables pasting of tabbed text from an editor # message, just do the right thing and give the user his tab! # the mostly useless 'do you want to see all million completions' # if there is only a tab on a line with only whitespace, instead of # (text, line_buffer, cursor_pos) ) # dbg #io.rprint("\nRLCOMPLETE: %r %r %r" % cursor_pos = self.readline.get_endidx() self.line_buffer = line_buffer = self.readline.get_line_buffer() if state==0: #from there import print """ Counter used by readline. state : int Text to perform the completion on. text : string ---------- Parameters returns None. The completion should begin with 'text'. This is called successively with state == 0, 1, 2, ... until it """Return the state-th possible completion for 'text'. def rlcomplete(self, text, state):class RLCompleter(IPCompleter):from IPython.core.completer import IPCompleterPKZbJ ""rlipython/.completer.py.un~VimUnDoЍT\e_^HLBfBdyzQӅ9GlA.from IPython.core.completer import IPCompleter. Xp_Xm5_$Xm,from IPython.core.completer import COmpleter5_,Xm,from IPython.core.completer import Completer5_#Xm,from IPython.core.completer import Completer5_Xmclass RLCompleter5_Xn  class RLCompleter(IPCompleter)5_Xn3 +5_ 3Xn/+'+ def rlcomplete(self, text, state):?+ """Return the state-th possible completion for 'text'.H+ 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. + """!+ #from there import print++ if state==0:+M+ self.line_buffer = line_buffer = self.readline.get_line_buffer()4+ cursor_pos = self.readline.get_endidx()+2+ #io.rprint("\nRLCOMPLETE: %r %r %r" %?+ # (text, line_buffer, cursor_pos) ) # dbg+P+ # if there is only a tab on a line with only whitespace, instead ofN+ # the mostly useless 'do you want to see all million completions'J+ # message, just do the right thing and give the user his tab!O+ # Incidentally, this enables pasting of tabbed text from an editor.+ # (as long as autoindent is off).+K+ # It should be noted that at least pyreadline still shows file6+ # completions - is there a way around it?+N+ # don't apply this on 'dumb' terminals, such as emacs buffers, soJ+ # we don't interfere with their own tab-completion mechanism.@+ if not (self.dumb_terminal or line_buffer.strip()):0+ self.readline.insert_text('\t')#+ sys.stdout.flush()+ return None+N+ # Note: debugging exceptions that may occur in completion is veryM+ # tricky, because readline unconditionally silences them. So ifP+ # during development you suspect a bug in the completion code, turnN+ # this flag on temporarily by uncommenting the second form (don'tM+ # flip the value in the first line, as the '# dbg' marker can be=+ # automatically detected and is used elsewhere).+ DEBUG = False + #DEBUG = True # dbg+ if DEBUG:5_ 33Xo3 42 if DEBUG:5_ 43Xo35A% - try:5_ 55AXo4 A- self.complete(text, line_buffer, cursor_pos)- except:<- import traceback; traceback.print_exc()- else:8- # The normal production version is here->- # This method computes the self.matches array=- self.complete(text, line_buffer, cursor_pos) - try:'- return self.matches[state]- except IndexError:- return None-5_ .5AXpA.from IPython.core.completer import IPCompleterA5_ ;5AXpA;from IPython.core.completer import IPCompleter, StrDispatch5PKZbJGc"rlipython/.interactiveshell.py.swpb0VIM 8.0pXz`=1bussonniermatthiasairbears2-10-142-85-52.airbears2.1918.b~bussonniermatthias/dev/rlpython/rlpython/interactiveshell.pyutf-8 3210#"! Utp   __kcY-M' Z `8 XMadv |A@L \ 1 e K 1 s U 8 &   | { ` $  \ T B J,`onU1 [N=ml!e4 return False # Returning False will cause exceptions to propagate pass except (AttributeError, IndexError): self.shell.refill_readline_hist() or self.get_readline_tail() != self.readline_tail: if self.current_length() != self.orig_length \ # If it still doesn't match, just reload readline history. self.shell.readline.remove_history_item(self.orig_length) for _ in range(e): if e > 0: e = self.current_length() - self.orig_length try: # Try clipping the end if it's got longer if self._nested_level == 0: self._nested_level -= 1 def __exit__(self, type, value, traceback): self._nested_level += 1 self.orig_length, self.readline_tail = 999999, [] except (AttributeError, IndexError): # Can fail with pyreadline self.readline_tail = self.get_readline_tail() self.orig_length = self.current_length() try: if self._nested_level == 0: def __enter__(self): self._nested_level = 0 self.shell = shell def __init__(self, shell): so that interactive input to the code doesn't appear when pressing up.""" """Context manager to execute some code, then reload readline historyclass ReadlineNoRecord(object):def no_op(*a, **kw): pass@undoc return print('') except EOFError: yield l else: return if l == sentinel: l = py3compat.str_to_unicode(l_input(prompt)) try: while True: prompt = "" else: prompt = ":" % sentinel) print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ if not quiet: """ """ Yield pasted lines until the user enters the given sentinel value.def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): return 'notepad' # same in Windows! else: return 'vi' # the only one guaranteed to be there! if os.name == 'posix': "default editor.") warn("$EDITOR environment variable is not pure ASCII. Using platform " except UnicodeError: pass except KeyError: return ed ed = ed.decode() if not py3compat.PY3: ed = os.environ['EDITOR'] try:def get_default_editor():from traitlets import Integer, CBool, Unicodefrom IPython.utils.text import num_ini_spaces, SList, strip_email_quotesfrom logging import errorfrom warnings import warnfrom IPython.utils.process import abbrev_cwdfrom IPython.utils.terminal import toggle_set_term_title, set_term_titlefrom IPython.utils import py3compatfrom IPython.utils.encoding import get_stream_encfrom IPython.utils.decorators import undocfrom IPython.utils.contexts import NoOpContextfrom IPython.lib.clipboard import ClipboardEmptyfrom IPython.core.magic import Magics, magics_class, line_magicfrom IPython.core.interactiveshell import InteractiveShell, InteractiveShellABCfrom IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGICfrom IPython.core.usage import interactive_usagefrfrom IPython.utils.strdispatch import StrDispatchimport sysimport osimport bdbfrom __future__ import print_function# Distributed under the terms of the Modified BSD License.# Copyright (c) IPython Development Team."""Subclass of InteractiveShell for terminal based frontends."""# -*- coding: utf-8 -*-adCMp%uLK( j I H / " z ] D + *   k ^ * 6  _ B A -  gG9_^CpHInteractiveShellABC.register(TerminalInteractiveShell) "%paste and %cpaste magic functions.") print("If you want to paste code into IPython, try the " if not self.using_paste_magics: super(TerminalInteractiveShell, self).showindentationerror() def showindentationerror(self): self.register_magics(TerminalMagics) super(TerminalInteractiveShell, self).init_magics() def init_magics(self): #------------------------------------------------------------------------- # Things related to magics #------------------------------------------------------------------------- self.ask_exit() else: self.ask_exit() if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): if self.confirm_exit: This method calls the ask_exit callback.""" """Handle interactive exit. def exit(self): self.exit_now = True """ Ask the shell to exit. Can be overiden and used as a callback. """ def ask_exit(self): #------------------------------------------------------------------------- # Things related to exiting #------------------------------------------------------------------------- return True return False warn('Could not open editor') except TryNext: int0(e.lineno),int0(e.offset),e.msg) self.hooks.fix_error_editor(e.filename, try: # always pass integer line and offset values to editor hook return 0 except TypeError: return int(x) try: def int0(x): return False except EOFError: return False '[Y/n] ','y')): not self.ask_yes_no('Return to editor to correct syntax error? ' if (self.autoedit_syntax and try: return False None): '','', if e.filename in ('','','', """Utility routine for edit_syntax_error""" def _should_recompile(self,e): self.showtraceback() except: f.close() finally: sys.displayhook(f.read()) # think it is. # This should be inside a display_trap block and I try: f = open(err.filename) try: else: self.showtraceback()adSMd?w4  g f A  < w v > ^ 1 l T  h){F$V$MwJI+bW94 from IPython.core.com from IPython.core.comp from IPython.core.completer import from IPython.core.completer import IPCompleter """ from IPython.core.comp from IPython.core.completer import IPCompleter from .completer import RLCompleter """ (typically over the network by remote frontends). library), programmatically (such as in test suites) or out-of-process either interactively in-process (typically triggered by the readline This creates completion machinery that can be used by client code, """Initialize the completion machinery. def init_completer(self): self.set_autoindent(self.autoindent) # Configure auto-indent for all platforms self.readline_no_record = ReadlineNoRecord(self) self.refill_readline_hist() readline.set_history_length(self.history_length) # otherwise we end up with a monster history after a while: self.readline_delims = delims # them. # Store these so we can restore them if something like rpy2 modifies readline.set_completer_delims(delims) delims = delims.replace(ESC_MAGIC, '') delims = delims.replace(d, "") for d in self.readline_remove_delims: delims = delims.encode("ascii", "ignore") if not py3compat.PY3: delims = readline.get_completer_delims() # unicode chars, discard them. # Remove some chars from the delimiters list. If we encounter readline.parse_and_bind(rlcommand) for rlcommand in self.readline_parse_and_bind: if self._custom_readline_config: # load IPython config after inputrc if user has customized % inputrc_name) warn('Problems reading readline initialization file <%s>' except: readline.read_init_file(inputrc_name) try: if os.path.isfile(inputrc_name): inputrc_name = os.path.join(self.home_dir, inputrc_name) inputrc_name = '.editrc' if readline.uses_libedit: inputrc_name = '.inputrc' if inputrc_name is None: inputrc_name = os.environ.get('INPUTRC') # Or if libedit is used, load editrc. # Load user's initrc file (readline config) readline.parse_and_bind(rlcommand) for rlcommand in self.readline_parse_and_bind: if not self._custom_readline_config and not readline.uses_libedit: # skip if libedit because parse_and_bind syntax is different # load IPython config before inputrc if default # - IPython config (user customized) # - custom inputrc # - IPython config (default value) # Readline config order: self.readline_startup_hook = readline.set_startup_hook else: self.readline_startup_hook = readline.set_pre_input_hook # platform-dependent check # naming conventions with pyreadline to avoid this # FIXME - check with Frederick to see if we can harmonize if os.name == 'nt': # Platform-specific configuration sys.modules['readline'] = readline self.readline = readline self.has_readline = True else: warn('Readline services not available or not loaded.') if self.readline_use:adl '{zI h65 i 8 7 G ^ ] @ " h ) ( ' l if self.rl_do_indent: It handles auto-indent and text from set_next_input.""" """readline hook to be used at the start of each line. def pre_readline(self): self.readline.set_completer(self.Completer.rlcomplete) self.Completer.readline = self.readline """Reset readline's completer to be our own.""" def set_readline_completer(self): self.set_readline_completer() if self.has_readline: self.init_readline() self.set_hook('complete_command', reset_completer, str_key = '%reset') self.set_hook('complete_command', cd_completer, str_key = '%cd') self.set_hook('complete_command', magic_run_completer, str_key = '%run') self.set_hook('complete_command', module_completer, str_key = '%aimport') self.set_hook('complete_command', module_completer, str_key = 'from') self.set_hook('complete_command', module_completer, str_key = 'import') self.Completer.custom_completers = sdisp self.strdispatchers['complete_command'] = sdisp sdisp = self.strdispatchers.get('complete_command', StrDispatch()) # Add custom completers to the basic ones built into IPCompleter self.configurables.append(self.Completer) ) parent=self, global_namespace=self.user_global_ns, namespace=self.user_ns, self.Completer = RLCompleter(shell=self, magic_run_completer, cd_completer, reset_completer) from IPython.core.completerlib import (module_completer,ad_zB{zykM. ? 3 " ~ p E  ^ Y 4  _ 0 $ S 5 |{k?]|>=[Fg'&gf -------- Examples paste: automatically pull code from clipboard. -------- See also IPython statements (magics, shell escapes) are not supported (yet). will be what was just pasted. Just press enter and type -- (and press enter again) and the block Do not be alarmed by garbled output on Windows (it's a readline bug). '%cpaste -q' suppresses any additional output messages. '%cpaste -r' re-executes the block previously entered by cpaste. dedenting or executing it (preceding >>> and + is still stripped) This assigns the pasted block to variable 'foo' as string, without You can also pass a variable name as an argument, e.g. '%cpaste foo'. later editing with '%edit pasted_block'. executed block is also assigned to variable named 'pasted_block' for doctests (the '...' continuation prompt is also stripped). The ignored, to allow pasting directly from e-mails, diff files and definitions. '>' and '+' characters at the beginning of a line are The block is dedented prior to execution to enable execution of method -s %%' ('%%' is the new sentinel for this operation). alone on the line. You can also provide your own sentinel with '%paste You must terminate the block with '--' (two minus-signs) or Ctrl-D """Paste & execute a pre-formatted code block from clipboard. def cpaste(self, parameter_s=''): @line_magic print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) self.shell.set_autoindent() """Toggle autoindent on/off (if available).""" def autoindent(self, parameter_s = ''): @line_magic self.shell.run_cell(b) print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))) "Variable 'pasted_block' is not a string, can't execute") raise UsageError( if not isinstance(b, py3compat.string_types): raise UsageError('No previous pasted block available') if b is None: # Sanity checks b = self.shell.user_ns.get(name) """ """ Rerun a previously pasted command. def rerun_pasted(self, name='pasted_block'): return strip_email_quotes('\n'.join(lines)) lines = lines[1:] while lines and not lines[0].strip(): lines = block.splitlines() def preclean_input(self, block): self.shell.using_paste_magics = False finally: self.shell.run_cell(b) try: self.shell.using_paste_magics = True self.shell.user_ns['pasted_block'] = b b = self.preclean_input(block) else: print("Block assigned to '%s'" % name) self.shell.user_ns[name] = SList(block.splitlines()) # If storing it for further editing if name: """ """ Execute a block, or store it in a variable, per the user's request. def store_or_execute(self, block, name): self.input_splitter = IPythonInputSplitter() super(TerminalMagics, self).__init__(shell) def __init__(self, shell):class TerminalMagics(Magics):@magics_class return [ghi(x) for x in range(start, end)] ghi = self.shell.readline.get_history_item start = max(end-n, 1) end = self.shell.readline.get_current_history_length() + 1 """Get the last n items in readline history.""" def get_readline_tail(self, n=10): return self.shell.readline.get_current_history_length() def current_length(self):ad cuL>'ed< R Q = b  K k j   [C#pX6$po$n>=p`CBAxg@ # because for the terminal based application, the banner behavior # is called when mainloop/interact are called. The default is False # This display_banner only controls whether or not self.show_banner() ) you can force a direct exit without any confirmation.""", in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', Set to confirm when you try to exit IPython with an EOF (Control-D help=""" confirm_exit = CBool(True, config=True, help="auto editing of files with syntax errors.") autoedit_syntax = CBool(False, config=True,class TerminalInteractiveShell(InteractiveShell): os.system("cls") """ """Clear screen. def cls(self, s): @line_magic if sys.platform == 'win32': # Class-level: add a '%cls' magic only on Windows self.store_or_execute(block, name) write("## -- End pasted text --\n") write('\n') if not block.endswith('\n'): write(self.shell.pycolorize(block)) write = self.shell.write if 'q' not in opts: # By default, echo back to terminal unless quiet mode is requested raise UsageError("The clipboard appears to be empty") except ClipboardEmpty: return error('Could not get text from the clipboard.') else: error(message[0]) if message: message = getattr(clipboard_exc, 'args') except TryNext as clipboard_exc: block = self.shell.hooks.clipboard_get() try: return self.rerun_pasted() if 'r' in opts: opts, name = self.parse_options(parameter_s, 'rq', mode='string') """ cpaste: manually paste code into terminal until you mark its end. -------- See also IPython statements (magics, shell escapes) are not supported (yet). -q: quiet mode: do not echo the pasted text back to the terminal. -r: re-executes the block previously entered by cpaste. Options: executing it (preceding >>> and + is still stripped). This assigns the pasted block to variable 'foo' as string, without You can also pass a variable name as an argument, e.g. '%paste foo'. later editing with '%edit pasted_block'. executed block is also assigned to variable named 'pasted_block' for doctests (the '...' continuation prompt is also stripped). The ignored, to allow pasting directly from e-mails, diff files and definitions. '>' and '+' characters at the beginning of a line are The block is dedented prior to execution to enable execution of method the -q flag is given to force quiet mode). intervention and printed back on the screen before execution (unless The text is pulled directly from the clipboard without user """Paste & execute a pre-formatted code block from clipboard. def paste(self, parameter_s=''): @line_magic self.store_or_execute(block, name) block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet)) sentinel = opts.get('s', u'--') quiet = ('q' in opts) return self.rerun_pasted() if 'r' in opts: opts, name = self.parse_options(parameter_s, 'rqs:', mode='string') """ Hello world! :-- :>>> print " ".join(sorted(a)) :>>> a = ["world!", "Hello"] Pasting code; enter '--' alone on the line to stop. In [8]: %cpaste ::adY\$ml@2 M h  X R + & K 9  p c 6  qRj-,mlO\0U&[=_ self.set_custom_completer = no_op self.set_readline_completer = no_op self.readline_no_record = NoOpContext() # Set a number of methods that depend on readline to be no-op self.readline = None if not self.readline_use or not readline.have_readline: self.rl_do_indent = False self.rl_next_input = None import IPython.utils.rlineimpl as readline if self.readline_use: self.multiline_history = False self.readline_remove_delims = '-/~' '"\C-u": unix-line-discard'] '"\C-k": kill-line', '"\e[B": history-search-forward', '"\e[A": history-search-backward', '"\C-n": history-search-forward', '"\C-p": history-search-backward', '"\C-s": forward-search-history', '"\C-r": reverse-search-history', '"\C-o": tab-insert', 'set show-all-if-ambiguous on', '"\C-l": clear-screen', 'tab: complete', self.readline_parse_and_bind = [ self._custom_readline_config = False self.readline_use = True """Command history completion/saving/reloading.""" def init_readline(self): #------------------------------------------------------------------------- # Things related to readline #------------------------------------------------------------------------- self.display_formatter.active_types = ['text/plain'] # terminal only supports plaintext super(TerminalInteractiveShell, self).init_display_formatter() def init_display_formatter(self): #------------------------------------------------------------------------- # Overrides of init stages #------------------------------------------------------------------------- system = InteractiveShell.system_raw raise UsageError("%s" % e) except ValueError as e: return real_enable_gui(gui, app) try: from IPython.lib.inputhook import enable_gui as real_enable_gui # Deferred import """ """Switch amongst GUI input hooks by name. def enable_gui(gui=None, app=None): @staticmethod # In the terminal, GUI control is done via PyOS_InputHook using_paste_magics = CBool(False) # executed via paste magics functions # This `using_paste_magics` is used to detect whether the code is being usage = Unicode(interactive_usage) ) help="Enable auto setting the terminal title." term_title = CBool(False, config=True, ) default.""", curses support), specify it yourself. Otherwise don't change the internally). If for some reason this isn't working well (it needs change the behavior of the 'print' keyword, it's only triggered time it needs to print certain potentially long strings (this doesn't this is 0, which means IPython will auto-detect your screen size every through a pager instead of directly printed. The default value for long strings. Strings longer than this number of lines will be sent """Number of lines of your screen, used to control printing of very help= screen_length = Integer(0, config=True, help="The shell program to be used for paging.") pager = Unicode('less', config=True, ) help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." editor = Unicode(get_default_editor(), config=True, embedded_active = CBool(False) embedded = CBool(False) display_banner = CBool(False) # This isn't configurable! # is controlled by the application.ad ZY32i l ? * S 9  X 3 2 h o J FlP(jJEDilkwXW while 1: with self.builtin_trap, self.display_trap: """ internally created default banner. If an optional banner argument is given, it will override the """Start the mainloop. def mainloop(self, display_banner=None): #------------------------------------------------------------------------- # Mainloop and code execution logic #------------------------------------------------------------------------- self.alias_manager.soft_define_alias(name, cmd) for name, cmd in aliases: aliases = [] else : ('man', 'man')] aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), if os.name == 'posix': # GUI or web frontend # need direct access to the console in a way that we can't emulate in # Now define aliases that only make sense on the terminal, because they super(TerminalInteractiveShell, self).init_alias() # frontend. # The parent class defines aliases that can be safely used with any def init_alias(self): #------------------------------------------------------------------------- # Things related to aliases #------------------------------------------------------------------------- toggle_set_term_title(False) else: set_term_title('IPython: ' + abbrev_cwd()) toggle_set_term_title(True) if self.term_title: # Enable or disable the terminal title. def init_term_title(self): self.init_term_title() def _term_title_changed(self, name, new_value): return self.screen_length - num_lines_bot num_lines_bot = self.separate_in.count('\n')+1 else: return 0 if self.screen_length == 0: def usable_screen_length(self): @property #------------------------------------------------------------------------- # Things related to the terminal #------------------------------------------------------------------------- "Cell: {!r}").format(e, cell)) "Error: {}\n" warn(("Failed to add string to readline history.\n" # containing null bytes, which readline objects to. # The history DB can get corrupted so it returns strings except (TypeError, ValueError) as e: last_cell = cell stdin_encoding)) self.readline.add_history(py3compat.unicode_to_str(line, for line in cell.splitlines(): else: stdin_encoding)) self.readline.add_history(py3compat.unicode_to_str(cell, if self.multiline_history: try: if cell and (cell != last_cell): cell = cell.rstrip() # Ignore blank lines and consecutive duplicates include_latest=True): for _, _, cell in self.history_manager.get_tail(self.history_load_length, last_cell = u"" stdin_encoding = sys.stdin.encoding or "utf-8" self.readline.clear_history() # Load the last 1000 lines from history def refill_readline_hist(self): self.rl_next_input = None self.readline.insert_text(self.rl_next_input) if self.rl_next_input is not None: self.readline.insert_text(self._indent_current_str())ad`w)h+ ] \ M ) ( x >  K ^  vu6 ^ kB-^]K6];n b pass except KeyboardInterrupt: more = False self._replace_rlhist_multiline(source_raw, hlen_b4_cell) hlen_b4_cell = \ source_raw = self.input_splitter.raw_reset() self.write('\n' + self.get_exception_only()) try: #double-guard against keyboardinterrupts during kbdint handling except KeyboardInterrupt: self.rl_do_indent = False if self.autoindent: break # quick exit on sys.std[in|out] close if self.exit_now: line = self.raw_input(prompt) try: self.showtraceback() except: prompt = self.separate_in + 'In [{}]: '.format(self.execution_count) try: else: self.rl_do_indent = True if self.autoindent: self.showtraceback() except: prompt = ' ...: ' try: if more: self.hooks.pre_prompt_hook() while not self.exit_now: # ask_exit callback. # exit_now is set by a call to %Exit or %Quit, through the hlen_b4_cell = 0 else: hlen_b4_cell = self.readline.get_current_history_length() self.readline_startup_hook(self.pre_readline) if self.has_readline: more = False self.show_banner() elif display_banner: self.show_banner(display_banner) if isinstance(display_banner, py3compat.string_types): display_banner = self.display_banner if display_banner is None: return if self.exit_now: # batch run -> do not interact """Closely emulate the interactive Python console.""" def interact(self, display_banner=None): return self.readline.get_current_history_length() stdin_encoding)) self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(), stdin_encoding = get_stream_enc(sys.stdin, 'utf-8') self.readline.remove_history_item(hlen - i - 1) for i in range(hlen - hlen_before_cell): return hlen_before_cell if hlen == hlen_before_cell: hlen = self.readline.get_current_history_length() # nothing changed do nothing, e.g. when rl removes consecutive dups return hlen_before_cell if not source_raw.rstrip(): # skip empty cells return hlen_before_cell if not hasattr(self.readline, "remove_history_item"): # windows rl has no remove_history_item return hlen_before_cell if not self.has_readline or not self.multiline_history: # do nothing without readline or disabled multiline """Store multiple lines as a single entry in history""" def _replace_rlhist_multiline(self, source_raw, hlen_before_cell): self.write("\nKeyboardInterrupt in interact()\n") # handling seems rather unpredictable... # this should not be necessary, but KeyboardInterrupt except KeyboardInterrupt: break # interact_with_readline above # XXX for testing of a readline-decoupled repl loop, call #self.interact_with_readline() self.interact(display_banner=display_banner) try:adXg. / ? ~ ;  I  Q , n m I   nmN <!u_^uYS[Z S<+ except: self.safe_execfile(err.filename,self.user_ns) # may set last_syntax_error again if a SyntaxError is raised try: return if not self._should_recompile(err): err = self.SyntaxTB.clear_err_state() # copy and clear last_syntax_error while self.SyntaxTB.last_syntax_error: """ Loop until syntax error is fixed or user cancels. """The bottom half of the syntax error handler called in the main loop. def edit_syntax_error(self): #------------------------------------------------------------------------- # Methods to support auto-editing of SyntaxErrors. #------------------------------------------------------------------------- return line self.indent_current_nsp = 0 line = line[self.indent_current_nsp:] if num_ini_spaces(line) > self.indent_current_nsp: if self.autoindent: # spaces, if the user's actual input started itself with whitespace. # than necessary. We do this by trimming out the auto-indent initial # Try to be reasonably smart about not re-indenting pasted input more return "" self.ask_exit() " or sys.stdout.close()!\nExiting IPython!\n") warn("\n********\nYou or a %run:ed script called sys.stdin.close()" except ValueError: line = py3compat.cast_unicode_py2(self.raw_input_original(prompt)) try: prompt = py3compat.cast_bytes_py2(prompt) # raw_input expects str, but we pass it unicode sometimes """ A string to be printed to prompt the user. prompt : str, optional ---------- Parameters When the user enters the EOF key sequence, EOFError is raised. The returned line does not include the trailing newline. """Write a prompt and read a line. def raw_input(self, prompt=''): self.exit_now = False # Turn off the exit flag, so the mainloop can be restarted if desired self._replace_rlhist_multiline(source_raw, hlen_b4_cell) hlen_b4_cell = \ self.run_cell(source_raw, store_history=True) source_raw = self.input_splitter.raw_reset() if not more: self.edit_syntax_error() self.autoedit_syntax): if (self.SyntaxTB.last_syntax_error and more = False # the exception. # Run the code directly - run_cell takes care of displaying except SyntaxError: more = self.input_splitter.push_accepts_more() self.input_splitter.push(line) try: else: self.showtraceback() # asynchronously by signal handlers, for example. # exceptions here are VERY RARE, but they can be triggered except: 'IPython will resume normal operation.') 'for IPython to properly format this particular exception.\n' 'Because of how pdb handles the stack, it is impossible\n' warn('The Python debugger has exited with a BdbQuit exception.\n' except bdb.BdbQuit: self.exit() self.write('\n') self.readline_startup_hook(None) if self.has_readline: self.rl_do_indent = False if self.autoindent: except EOFError:ad<_Td9 m S 9 { ] @ .  h , " d \ J R 4  hwv]9(c!VEut)m<' return False # Returning False will cause exceptions to propagate pass except (AttributeError, IndexError): self.shell.refill_readline_hist() or self.get_readline_tail() != self.readline_tail: if self.current_length() != self.orig_length \ # If it still doesn't match, just reload readline history. self.shell.readline.remove_history_item(self.orig_length) for _ in range(e): if e > 0: e = self.current_length() - self.orig_length try: # Try clipping the end if it's got longer if self._nested_level == 0: self._nested_level -= 1 def __exit__(self, type, value, traceback): self._nested_level += 1 self.orig_length, self.readline_tail = 999999, [] except (AttributeError, IndexError): # Can fail with pyreadline self.readline_tail = self.get_readline_tail() self.orig_length = self.current_length() try: if self._nested_level == 0: def __enter__(self): self._nested_level = 0 self.shell = shell def __init__(self, shell): so that interactive input to the code doesn't appear when pressing up.""" """Context manager to execute some code, then reload readline historyclass ReadlineNoRecord(object):def no_op(*a, **kw): pass@undoc return print('') except EOFError: yield l else: return if l == sentinel: l = py3compat.str_to_unicode(l_input(prompt)) try: while True: prompt = "" else: prompt = ":" % sentinel) print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ if not quiet: """ """ Yield pasted lines until the user enters the given sentinel value.def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): return 'notepad' # same in Windows! else: return 'vi' # the only one guaranteed to be there! if os.name == 'posix': "default editor.") warn("$EDITOR environment variable is not pure ASCII. Using platform " except UnicodeError: pass except KeyError: return ed ed = ed.decode() if not py3compat.PY3: ed = os.environ['EDITOR'] try:def get_default_editor():from traitlets import Integer, CBool, Unicodefrom IPython.utils.text import num_ini_spaces, SList, strip_email_quotesfrom logging import errorfrom warnings import warnfrom IPython.utils.process import abbrev_cwdfrom IPython.utils.terminal import toggle_set_term_title, set_term_titlefrom IPython.utils import py3compatfrom IPython.utils.encoding import get_stream_encfrom IPython.utils.decorators import undocfrom IPython.utils.contexts import NoOpContextfrom IPython.lib.clipboard import ClipboardEmptyfrom IPython.core.magic import Magics, magics_class, line_magicfrom IPython.core.interactiveshell import InteractiveShell, InteractiveShellABCfrom IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGICfrom IPython.core.usage import interactive_usagefrom IPython.core.error import TryNext, UsageErrorPKZbJ"rlipython/.interactiveshell.py.un~VimUnDoZb$HH1{ \Q"Jx=Z  Xp_)Xn> ><) self.set_readline_completer()5_Xn self.init_readline() if self.has_readline:) self.set_readline_completer()5_ XnYY5_NXn\N self.set_hook('complete_command', reset_completer, str_key = '%reset')5_Xn]! def init_completer(self):5_XnA # Only configure readline if we truly are using readline.5_Xn def init_completer(self):> super(TerminalInteractiveShell, self).init_completer()5_ Xn5_ XnX6 from IPython.core.completer import IPCompleter5_ XnX* from .completer import IPCompleter5_ XnX0 self.Completer = IPCompleter(shell=self,5_ Xp Z Z X import sys5PK[bJErlipython/__init__.py""" Readline interface for IPython """ version_info = (0,0,1) __version__ = '.'.join([str(x) for x in version_info]) from .completer import RLCompleter from .interactiveshell import TerminalInteractiveShell PKZbJ=< < rlipython/completer.pyfrom IPython.core.completer import IPCompleter class RLCompleter(IPCompleter): def rlcomplete(self, text, state): """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. """ #from there import print if state==0: self.line_buffer = line_buffer = self.readline.get_line_buffer() cursor_pos = self.readline.get_endidx() #io.rprint("\nRLCOMPLETE: %r %r %r" % # (text, line_buffer, cursor_pos) ) # dbg # if there is only a tab on a line with only whitespace, instead of # the mostly useless 'do you want to see all million completions' # message, just do the right thing and give the user his tab! # Incidentally, this enables pasting of tabbed text from an editor # (as long as autoindent is off). # It should be noted that at least pyreadline still shows file # completions - is there a way around it? # don't apply this on 'dumb' terminals, such as emacs buffers, so # we don't interfere with their own tab-completion mechanism. if not (self.dumb_terminal or line_buffer.strip()): self.readline.insert_text('\t') sys.stdout.flush() return None # Note: debugging exceptions that may occur in completion is very # tricky, because readline unconditionally silences them. So if # during development you suspect a bug in the completion code, turn # this flag on temporarily by uncommenting the second form (don't # flip the value in the first line, as the '# dbg' marker can be # automatically detected and is used elsewhere). DEBUG = False #DEBUG = True # dbg if DEBUG: try: self.complete(text, line_buffer, cursor_pos) except: import traceback; traceback.print_exc() else: # The normal production version is here # This method computes the self.matches array self.complete(text, line_buffer, cursor_pos) try: return self.matches[state] except IndexError: return None PKZbJab**rlipython/interactiveshell.py# -*- coding: utf-8 -*- """Subclass of InteractiveShell for terminal based frontends.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import print_function import bdb import os import sys from IPython.utils.strdispatch import StrDispatch from IPython.core.error import TryNext, UsageError from IPython.core.usage import interactive_usage from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC from IPython.core.magic import Magics, magics_class, line_magic from IPython.lib.clipboard import ClipboardEmpty from IPython.utils.contexts import NoOpContext from IPython.utils.decorators import undoc from IPython.utils.encoding import get_stream_enc from IPython.utils import py3compat from IPython.utils.terminal import toggle_set_term_title, set_term_title from IPython.utils.process import abbrev_cwd from warnings import warn from logging import error from IPython.utils.text import num_ini_spaces, SList, strip_email_quotes from traitlets import Integer, CBool, Unicode def get_default_editor(): try: ed = os.environ['EDITOR'] if not py3compat.PY3: ed = ed.decode() return ed except KeyError: pass except UnicodeError: warn("$EDITOR environment variable is not pure ASCII. Using platform " "default editor.") if os.name == 'posix': return 'vi' # the only one guaranteed to be there! else: return 'notepad' # same in Windows! def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): """ Yield pasted lines until the user enters the given sentinel value. """ if not quiet: print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ % sentinel) prompt = ":" else: prompt = "" while True: try: l = py3compat.str_to_unicode(l_input(prompt)) if l == sentinel: return else: yield l except EOFError: print('') return @undoc def no_op(*a, **kw): pass class ReadlineNoRecord(object): """Context manager to execute some code, then reload readline history so that interactive input to the code doesn't appear when pressing up.""" def __init__(self, shell): self.shell = shell self._nested_level = 0 def __enter__(self): if self._nested_level == 0: try: self.orig_length = self.current_length() self.readline_tail = self.get_readline_tail() except (AttributeError, IndexError): # Can fail with pyreadline self.orig_length, self.readline_tail = 999999, [] self._nested_level += 1 def __exit__(self, type, value, traceback): self._nested_level -= 1 if self._nested_level == 0: # Try clipping the end if it's got longer try: e = self.current_length() - self.orig_length if e > 0: for _ in range(e): self.shell.readline.remove_history_item(self.orig_length) # If it still doesn't match, just reload readline history. if self.current_length() != self.orig_length \ or self.get_readline_tail() != self.readline_tail: self.shell.refill_readline_hist() except (AttributeError, IndexError): pass # Returning False will cause exceptions to propagate return False def current_length(self): return self.shell.readline.get_current_history_length() def get_readline_tail(self, n=10): """Get the last n items in readline history.""" end = self.shell.readline.get_current_history_length() + 1 start = max(end-n, 1) ghi = self.shell.readline.get_history_item return [ghi(x) for x in range(start, end)] @magics_class class TerminalMagics(Magics): def __init__(self, shell): super(TerminalMagics, self).__init__(shell) self.input_splitter = IPythonInputSplitter() def store_or_execute(self, block, name): """ Execute a block, or store it in a variable, per the user's request. """ if name: # If storing it for further editing self.shell.user_ns[name] = SList(block.splitlines()) print("Block assigned to '%s'" % name) else: b = self.preclean_input(block) self.shell.user_ns['pasted_block'] = b self.shell.using_paste_magics = True try: self.shell.run_cell(b) finally: self.shell.using_paste_magics = False def preclean_input(self, block): lines = block.splitlines() while lines and not lines[0].strip(): lines = lines[1:] return strip_email_quotes('\n'.join(lines)) def rerun_pasted(self, name='pasted_block'): """ Rerun a previously pasted command. """ b = self.shell.user_ns.get(name) # Sanity checks if b is None: raise UsageError('No previous pasted block available') if not isinstance(b, py3compat.string_types): raise UsageError( "Variable 'pasted_block' is not a string, can't execute") print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))) self.shell.run_cell(b) @line_magic def autoindent(self, parameter_s = ''): """Toggle autoindent on/off (if available).""" self.shell.set_autoindent() print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) @line_magic def cpaste(self, parameter_s=''): """Paste & execute a pre-formatted code block from clipboard. You must terminate the block with '--' (two minus-signs) or Ctrl-D alone on the line. You can also provide your own sentinel with '%paste -s %%' ('%%' is the new sentinel for this operation). The block is dedented prior to execution to enable execution of method definitions. '>' and '+' characters at the beginning of a line are ignored, to allow pasting directly from e-mails, diff files and doctests (the '...' continuation prompt is also stripped). The executed block is also assigned to variable named 'pasted_block' for later editing with '%edit pasted_block'. You can also pass a variable name as an argument, e.g. '%cpaste foo'. This assigns the pasted block to variable 'foo' as string, without dedenting or executing it (preceding >>> and + is still stripped) '%cpaste -r' re-executes the block previously entered by cpaste. '%cpaste -q' suppresses any additional output messages. Do not be alarmed by garbled output on Windows (it's a readline bug). Just press enter and type -- (and press enter again) and the block will be what was just pasted. IPython statements (magics, shell escapes) are not supported (yet). See also -------- paste: automatically pull code from clipboard. Examples -------- :: In [8]: %cpaste Pasting code; enter '--' alone on the line to stop. :>>> a = ["world!", "Hello"] :>>> print " ".join(sorted(a)) :-- Hello world! """ opts, name = self.parse_options(parameter_s, 'rqs:', mode='string') if 'r' in opts: self.rerun_pasted() return quiet = ('q' in opts) sentinel = opts.get('s', u'--') block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet)) self.store_or_execute(block, name) @line_magic def paste(self, parameter_s=''): """Paste & execute a pre-formatted code block from clipboard. The text is pulled directly from the clipboard without user intervention and printed back on the screen before execution (unless the -q flag is given to force quiet mode). The block is dedented prior to execution to enable execution of method definitions. '>' and '+' characters at the beginning of a line are ignored, to allow pasting directly from e-mails, diff files and doctests (the '...' continuation prompt is also stripped). The executed block is also assigned to variable named 'pasted_block' for later editing with '%edit pasted_block'. You can also pass a variable name as an argument, e.g. '%paste foo'. This assigns the pasted block to variable 'foo' as string, without executing it (preceding >>> and + is still stripped). Options: -r: re-executes the block previously entered by cpaste. -q: quiet mode: do not echo the pasted text back to the terminal. IPython statements (magics, shell escapes) are not supported (yet). See also -------- cpaste: manually paste code into terminal until you mark its end. """ opts, name = self.parse_options(parameter_s, 'rq', mode='string') if 'r' in opts: self.rerun_pasted() return try: block = self.shell.hooks.clipboard_get() except TryNext as clipboard_exc: message = getattr(clipboard_exc, 'args') if message: error(message[0]) else: error('Could not get text from the clipboard.') return except ClipboardEmpty: raise UsageError("The clipboard appears to be empty") # By default, echo back to terminal unless quiet mode is requested if 'q' not in opts: write = self.shell.write write(self.shell.pycolorize(block)) if not block.endswith('\n'): write('\n') write("## -- End pasted text --\n") self.store_or_execute(block, name) # Class-level: add a '%cls' magic only on Windows if sys.platform == 'win32': @line_magic def cls(self, s): """Clear screen. """ os.system("cls") class TerminalInteractiveShell(InteractiveShell): autoedit_syntax = CBool(False, config=True, help="auto editing of files with syntax errors.") confirm_exit = CBool(True, config=True, help=""" Set to confirm when you try to exit IPython with an EOF (Control-D in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', you can force a direct exit without any confirmation.""", ) # This display_banner only controls whether or not self.show_banner() # is called when mainloop/interact are called. The default is False # because for the terminal based application, the banner behavior # is controlled by the application. display_banner = CBool(False) # This isn't configurable! embedded = CBool(False) embedded_active = CBool(False) editor = Unicode(get_default_editor(), config=True, help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." ) pager = Unicode('less', config=True, help="The shell program to be used for paging.") screen_length = Integer(0, config=True, help= """Number of lines of your screen, used to control printing of very long strings. Strings longer than this number of lines will be sent through a pager instead of directly printed. The default value for this is 0, which means IPython will auto-detect your screen size every time it needs to print certain potentially long strings (this doesn't change the behavior of the 'print' keyword, it's only triggered internally). If for some reason this isn't working well (it needs curses support), specify it yourself. Otherwise don't change the default.""", ) term_title = CBool(False, config=True, help="Enable auto setting the terminal title." ) usage = Unicode(interactive_usage) # This `using_paste_magics` is used to detect whether the code is being # executed via paste magics functions using_paste_magics = CBool(False) # In the terminal, GUI control is done via PyOS_InputHook @staticmethod def enable_gui(gui=None, app=None): """Switch amongst GUI input hooks by name. """ # Deferred import from IPython.lib.inputhook import enable_gui as real_enable_gui try: return real_enable_gui(gui, app) except ValueError as e: raise UsageError("%s" % e) system = InteractiveShell.system_raw #------------------------------------------------------------------------- # Overrides of init stages #------------------------------------------------------------------------- def init_display_formatter(self): super(TerminalInteractiveShell, self).init_display_formatter() # terminal only supports plaintext self.display_formatter.active_types = ['text/plain'] #------------------------------------------------------------------------- # Things related to readline #------------------------------------------------------------------------- def init_readline(self): """Command history completion/saving/reloading.""" self.readline_use = True self._custom_readline_config = False self.readline_parse_and_bind = [ 'tab: complete', '"\C-l": clear-screen', 'set show-all-if-ambiguous on', '"\C-o": tab-insert', '"\C-r": reverse-search-history', '"\C-s": forward-search-history', '"\C-p": history-search-backward', '"\C-n": history-search-forward', '"\e[A": history-search-backward', '"\e[B": history-search-forward', '"\C-k": kill-line', '"\C-u": unix-line-discard'] self.readline_remove_delims = '-/~' self.multiline_history = False if self.readline_use: import IPython.utils.rlineimpl as readline self.rl_next_input = None self.rl_do_indent = False if not self.readline_use or not readline.have_readline: self.readline = None # Set a number of methods that depend on readline to be no-op self.readline_no_record = NoOpContext() self.set_readline_completer = no_op self.set_custom_completer = no_op if self.readline_use: warn('Readline services not available or not loaded.') else: self.has_readline = True self.readline = readline sys.modules['readline'] = readline # Platform-specific configuration if os.name == 'nt': # FIXME - check with Frederick to see if we can harmonize # naming conventions with pyreadline to avoid this # platform-dependent check self.readline_startup_hook = readline.set_pre_input_hook else: self.readline_startup_hook = readline.set_startup_hook # Readline config order: # - IPython config (default value) # - custom inputrc # - IPython config (user customized) # load IPython config before inputrc if default # skip if libedit because parse_and_bind syntax is different if not self._custom_readline_config and not readline.uses_libedit: for rlcommand in self.readline_parse_and_bind: readline.parse_and_bind(rlcommand) # Load user's initrc file (readline config) # Or if libedit is used, load editrc. inputrc_name = os.environ.get('INPUTRC') if inputrc_name is None: inputrc_name = '.inputrc' if readline.uses_libedit: inputrc_name = '.editrc' inputrc_name = os.path.join(self.home_dir, inputrc_name) if os.path.isfile(inputrc_name): try: readline.read_init_file(inputrc_name) except: warn('Problems reading readline initialization file <%s>' % inputrc_name) # load IPython config after inputrc if user has customized if self._custom_readline_config: for rlcommand in self.readline_parse_and_bind: readline.parse_and_bind(rlcommand) # Remove some chars from the delimiters list. If we encounter # unicode chars, discard them. delims = readline.get_completer_delims() if not py3compat.PY3: delims = delims.encode("ascii", "ignore") for d in self.readline_remove_delims: delims = delims.replace(d, "") delims = delims.replace(ESC_MAGIC, '') readline.set_completer_delims(delims) # Store these so we can restore them if something like rpy2 modifies # them. self.readline_delims = delims # otherwise we end up with a monster history after a while: readline.set_history_length(self.history_length) self.refill_readline_hist() self.readline_no_record = ReadlineNoRecord(self) # Configure auto-indent for all platforms self.set_autoindent(self.autoindent) def init_completer(self): """Initialize the completion machinery. This creates completion machinery that can be used by client code, either interactively in-process (typically triggered by the readline library), programmatically (such as in test suites) or out-of-process (typically over the network by remote frontends). """ from .completer import RLCompleter from IPython.core.completerlib import (module_completer, magic_run_completer, cd_completer, reset_completer) self.Completer = RLCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, parent=self, ) self.configurables.append(self.Completer) # Add custom completers to the basic ones built into IPCompleter sdisp = self.strdispatchers.get('complete_command', StrDispatch()) self.strdispatchers['complete_command'] = sdisp self.Completer.custom_completers = sdisp self.set_hook('complete_command', module_completer, str_key = 'import') self.set_hook('complete_command', module_completer, str_key = 'from') self.set_hook('complete_command', module_completer, str_key = '%aimport') self.set_hook('complete_command', magic_run_completer, str_key = '%run') self.set_hook('complete_command', cd_completer, str_key = '%cd') self.set_hook('complete_command', reset_completer, str_key = '%reset') self.init_readline() if self.has_readline: self.set_readline_completer() def set_readline_completer(self): """Reset readline's completer to be our own.""" self.Completer.readline = self.readline self.readline.set_completer(self.Completer.rlcomplete) def pre_readline(self): """readline hook to be used at the start of each line. It handles auto-indent and text from set_next_input.""" if self.rl_do_indent: self.readline.insert_text(self._indent_current_str()) if self.rl_next_input is not None: self.readline.insert_text(self.rl_next_input) self.rl_next_input = None def refill_readline_hist(self): # Load the last 1000 lines from history self.readline.clear_history() stdin_encoding = sys.stdin.encoding or "utf-8" last_cell = u"" for _, _, cell in self.history_manager.get_tail(self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cell.rstrip() if cell and (cell != last_cell): try: if self.multiline_history: self.readline.add_history(py3compat.unicode_to_str(cell, stdin_encoding)) else: for line in cell.splitlines(): self.readline.add_history(py3compat.unicode_to_str(line, stdin_encoding)) last_cell = cell except (TypeError, ValueError) as e: # The history DB can get corrupted so it returns strings # containing null bytes, which readline objects to. warn(("Failed to add string to readline history.\n" "Error: {}\n" "Cell: {!r}").format(e, cell)) #------------------------------------------------------------------------- # Things related to the terminal #------------------------------------------------------------------------- @property def usable_screen_length(self): if self.screen_length == 0: return 0 else: num_lines_bot = self.separate_in.count('\n')+1 return self.screen_length - num_lines_bot def _term_title_changed(self, name, new_value): self.init_term_title() def init_term_title(self): # Enable or disable the terminal title. if self.term_title: toggle_set_term_title(True) set_term_title('IPython: ' + abbrev_cwd()) else: toggle_set_term_title(False) #------------------------------------------------------------------------- # Things related to aliases #------------------------------------------------------------------------- def init_alias(self): # The parent class defines aliases that can be safely used with any # frontend. super(TerminalInteractiveShell, self).init_alias() # Now define aliases that only make sense on the terminal, because they # need direct access to the console in a way that we can't emulate in # GUI or web frontend if os.name == 'posix': aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'), ('man', 'man')] else : aliases = [] for name, cmd in aliases: self.alias_manager.soft_define_alias(name, cmd) #------------------------------------------------------------------------- # Mainloop and code execution logic #------------------------------------------------------------------------- def mainloop(self, display_banner=None): """Start the mainloop. If an optional banner argument is given, it will override the internally created default banner. """ with self.builtin_trap, self.display_trap: while 1: try: self.interact(display_banner=display_banner) #self.interact_with_readline() # XXX for testing of a readline-decoupled repl loop, call # interact_with_readline above break except KeyboardInterrupt: # this should not be necessary, but KeyboardInterrupt # handling seems rather unpredictable... self.write("\nKeyboardInterrupt in interact()\n") def _replace_rlhist_multiline(self, source_raw, hlen_before_cell): """Store multiple lines as a single entry in history""" # do nothing without readline or disabled multiline if not self.has_readline or not self.multiline_history: return hlen_before_cell # windows rl has no remove_history_item if not hasattr(self.readline, "remove_history_item"): return hlen_before_cell # skip empty cells if not source_raw.rstrip(): return hlen_before_cell # nothing changed do nothing, e.g. when rl removes consecutive dups hlen = self.readline.get_current_history_length() if hlen == hlen_before_cell: return hlen_before_cell for i in range(hlen - hlen_before_cell): self.readline.remove_history_item(hlen - i - 1) stdin_encoding = get_stream_enc(sys.stdin, 'utf-8') self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(), stdin_encoding)) return self.readline.get_current_history_length() def interact(self, display_banner=None): """Closely emulate the interactive Python console.""" # batch run -> do not interact if self.exit_now: return if display_banner is None: display_banner = self.display_banner if isinstance(display_banner, py3compat.string_types): self.show_banner(display_banner) elif display_banner: self.show_banner() more = False if self.has_readline: self.readline_startup_hook(self.pre_readline) hlen_b4_cell = self.readline.get_current_history_length() else: hlen_b4_cell = 0 # exit_now is set by a call to %Exit or %Quit, through the # ask_exit callback. while not self.exit_now: self.hooks.pre_prompt_hook() if more: try: prompt = ' ...: ' except: self.showtraceback() if self.autoindent: self.rl_do_indent = True else: try: prompt = self.separate_in + 'In [{}]: '.format(self.execution_count) except: self.showtraceback() try: line = self.raw_input(prompt) if self.exit_now: # quick exit on sys.std[in|out] close break if self.autoindent: self.rl_do_indent = False except KeyboardInterrupt: #double-guard against keyboardinterrupts during kbdint handling try: self.write('\n' + self.get_exception_only()) source_raw = self.input_splitter.raw_reset() hlen_b4_cell = \ self._replace_rlhist_multiline(source_raw, hlen_b4_cell) more = False except KeyboardInterrupt: pass except EOFError: if self.autoindent: self.rl_do_indent = False if self.has_readline: self.readline_startup_hook(None) self.write('\n') self.exit() except bdb.BdbQuit: warn('The Python debugger has exited with a BdbQuit exception.\n' 'Because of how pdb handles the stack, it is impossible\n' 'for IPython to properly format this particular exception.\n' 'IPython will resume normal operation.') except: # exceptions here are VERY RARE, but they can be triggered # asynchronously by signal handlers, for example. self.showtraceback() else: try: self.input_splitter.push(line) more = self.input_splitter.push_accepts_more() except SyntaxError: # Run the code directly - run_cell takes care of displaying # the exception. more = False if (self.SyntaxTB.last_syntax_error and self.autoedit_syntax): self.edit_syntax_error() if not more: source_raw = self.input_splitter.raw_reset() self.run_cell(source_raw, store_history=True) hlen_b4_cell = \ self._replace_rlhist_multiline(source_raw, hlen_b4_cell) # Turn off the exit flag, so the mainloop can be restarted if desired self.exit_now = False def raw_input(self, prompt=''): """Write a prompt and read a line. The returned line does not include the trailing newline. When the user enters the EOF key sequence, EOFError is raised. Parameters ---------- prompt : str, optional A string to be printed to prompt the user. """ # raw_input expects str, but we pass it unicode sometimes prompt = py3compat.cast_bytes_py2(prompt) try: line = py3compat.cast_unicode_py2(self.raw_input_original(prompt)) except ValueError: warn("\n********\nYou or a %run:ed script called sys.stdin.close()" " or sys.stdout.close()!\nExiting IPython!\n") self.ask_exit() return "" # Try to be reasonably smart about not re-indenting pasted input more # than necessary. We do this by trimming out the auto-indent initial # spaces, if the user's actual input started itself with whitespace. if self.autoindent: if num_ini_spaces(line) > self.indent_current_nsp: line = line[self.indent_current_nsp:] self.indent_current_nsp = 0 return line #------------------------------------------------------------------------- # Methods to support auto-editing of SyntaxErrors. #------------------------------------------------------------------------- def edit_syntax_error(self): """The bottom half of the syntax error handler called in the main loop. Loop until syntax error is fixed or user cancels. """ while self.SyntaxTB.last_syntax_error: # copy and clear last_syntax_error err = self.SyntaxTB.clear_err_state() if not self._should_recompile(err): return try: # may set last_syntax_error again if a SyntaxError is raised self.safe_execfile(err.filename,self.user_ns) except: self.showtraceback() else: try: f = open(err.filename) try: # This should be inside a display_trap block and I # think it is. sys.displayhook(f.read()) finally: f.close() except: self.showtraceback() def _should_recompile(self,e): """Utility routine for edit_syntax_error""" if e.filename in ('','','', '','', None): return False try: if (self.autoedit_syntax and not self.ask_yes_no('Return to editor to correct syntax error? ' '[Y/n] ','y')): return False except EOFError: return False def int0(x): try: return int(x) except TypeError: return 0 # always pass integer line and offset values to editor hook try: self.hooks.fix_error_editor(e.filename, int0(e.lineno),int0(e.offset),e.msg) except TryNext: warn('Could not open editor') return False return True #------------------------------------------------------------------------- # Things related to exiting #------------------------------------------------------------------------- def ask_exit(self): """ Ask the shell to exit. Can be overiden and used as a callback. """ self.exit_now = True def exit(self): """Handle interactive exit. This method calls the ask_exit callback.""" if self.confirm_exit: if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): self.ask_exit() else: self.ask_exit() #------------------------------------------------------------------------- # Things related to magics #------------------------------------------------------------------------- def init_magics(self): super(TerminalInteractiveShell, self).init_magics() self.register_magics(TerminalMagics) def showindentationerror(self): super(TerminalInteractiveShell, self).showindentationerror() if not self.using_paste_magics: print("If you want to paste code into IPython, try the " "%paste and %cpaste magic functions.") InteractiveShellABC.register(TerminalInteractiveShell) PK!H|&Ubrlipython-0.0.1.dist-info/WHEEL HM K-*ϳR03rOK-J,/RH,Q034 /, (-JLR()*M ILR(4KM̫#DPK!H166"rlipython-0.0.1.dist-info/METADATAEN0 F~n"XV^붖8 ޞVqi>߉"1 읁^-[Sw TefBXE+ ~^lv8-.]umC”k^"{q,Οڤq/Nc`B12Ƚ9Nd2]!p3Bsy0z }% ٞC407GXPK!H y rlipython-0.0.1.dist-info/RECORD˒@\ :-@/@ACHFP欈\{& +T*SmcU2}^k벀73IBqJyy`tc! JSЌ2,K_f7O3 :*w?KZՏ&ד[,h }u,c[r20[04 C/H`j>]ڌ\j| L4"SUF{/*'ٰ^P;P_zSS[)%Z9icOM!PƪT؊fwwYΎo_GhMg}j#7tV2n֣aYܜQ]$tx ' >i#B L+lΊpɚ30<ʻ~Ia]V̍{A