##// END OF EJS Templates
Merge pull request #9685 from Carreau/no-rl-2...
Thomas Kluyver -
r22650:858133ca merge
parent child Browse files
Show More
@@ -1,50 +1,10 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Word completion for IPython.
2 """Word completion for IPython.
3
3
4 This module is a fork of the rlcompleter module in the Python standard
4 This module started as fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3, but we need a lot more
6 upstream and were accepted as of Python 2.3,
7 functionality specific to IPython, so this module will continue to live as an
8 IPython-specific utility.
9
7
10 Original rlcompleter documentation:
11
12 This requires the latest extension to the readline module (the
13 completes keywords, built-ins and globals in __main__; when completing
14 NAME.NAME..., it evaluates (!) the expression up to the last dot and
15 completes its attributes.
16
17 It's very cool to do "import string" type "string.", hit the
18 completion key (twice), and see the list of names defined by the
19 string module!
20
21 Tip: to use the tab key as the completion key, call
22
23 readline.parse_and_bind("tab: complete")
24
25 Notes:
26
27 - Exceptions raised by the completer function are *ignored* (and
28 generally cause the completion to fail). This is a feature -- since
29 readline sets the tty device in raw (or cbreak) mode, printing a
30 traceback wouldn't work well without some complicated hoopla to save,
31 reset and restore the tty state.
32
33 - The evaluation of the NAME.NAME... form may cause arbitrary
34 application defined code to be executed if an object with a
35 ``__getattr__`` hook is found. Since it is the responsibility of the
36 application (or the user) to enable this feature, I consider this an
37 acceptable risk. More complicated expressions (e.g. function calls or
38 indexing operations) are *not* evaluated.
39
40 - GNU readline is also used by the built-in functions input() and
41 raw_input(), and thus these also benefit/suffer from the completer
42 features. Clearly an interactive application can benefit by
43 specifying its own completer function and using raw_input() for all
44 its input.
45
46 - When the original stdin is not a tty device, GNU readline is never
47 used, and this module (and the readline module) are silently inactive.
48 """
8 """
49
9
50 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
@@ -1252,66 +1212,3 b' class IPCompleter(Completer):'
1252 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1212 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1253
1213
1254 return text, self.matches
1214 return text, self.matches
1255
1256 def rlcomplete(self, text, state):
1257 """Return the state-th possible completion for 'text'.
1258
1259 This is called successively with state == 0, 1, 2, ... until it
1260 returns None. The completion should begin with 'text'.
1261
1262 Parameters
1263 ----------
1264 text : string
1265 Text to perform the completion on.
1266
1267 state : int
1268 Counter used by readline.
1269 """
1270 if state==0:
1271
1272 self.line_buffer = line_buffer = self.readline.get_line_buffer()
1273 cursor_pos = self.readline.get_endidx()
1274
1275 #io.rprint("\nRLCOMPLETE: %r %r %r" %
1276 # (text, line_buffer, cursor_pos) ) # dbg
1277
1278 # if there is only a tab on a line with only whitespace, instead of
1279 # the mostly useless 'do you want to see all million completions'
1280 # message, just do the right thing and give the user his tab!
1281 # Incidentally, this enables pasting of tabbed text from an editor
1282 # (as long as autoindent is off).
1283
1284 # It should be noted that at least pyreadline still shows file
1285 # completions - is there a way around it?
1286
1287 # don't apply this on 'dumb' terminals, such as emacs buffers, so
1288 # we don't interfere with their own tab-completion mechanism.
1289 if not (self.dumb_terminal or line_buffer.strip()):
1290 self.readline.insert_text('\t')
1291 sys.stdout.flush()
1292 return None
1293
1294 # Note: debugging exceptions that may occur in completion is very
1295 # tricky, because readline unconditionally silences them. So if
1296 # during development you suspect a bug in the completion code, turn
1297 # this flag on temporarily by uncommenting the second form (don't
1298 # flip the value in the first line, as the '# dbg' marker can be
1299 # automatically detected and is used elsewhere).
1300 DEBUG = False
1301 #DEBUG = True # dbg
1302 if DEBUG:
1303 try:
1304 self.complete(text, line_buffer, cursor_pos)
1305 except:
1306 import traceback; traceback.print_exc()
1307 else:
1308 # The normal production version is here
1309
1310 # This method computes the self.matches array
1311 self.complete(text, line_buffer, cursor_pos)
1312
1313 try:
1314 return self.matches[state]
1315 except IndexError:
1316 return None
1317
@@ -62,7 +62,6 b' from IPython.utils import PyColorize'
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils import py3compat
63 from IPython.utils import py3compat
64 from IPython.utils import openpy
64 from IPython.utils import openpy
65 from IPython.utils.contexts import NoOpContext
66 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
67 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
68 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
@@ -343,9 +342,6 b' class InteractiveShell(SingletonConfigurable):'
343 Automatically call the pdb debugger after every exception.
342 Automatically call the pdb debugger after every exception.
344 """
343 """
345 ).tag(config=True)
344 ).tag(config=True)
346 multiline_history = Bool(sys.platform != 'win32',
347 help="Save multi-line entries as one entry in readline history"
348 ).tag(config=True)
349 display_page = Bool(False,
345 display_page = Bool(False,
350 help="""If True, anything that would be passed to the pager
346 help="""If True, anything that would be passed to the pager
351 will be displayed as regular output instead."""
347 will be displayed as regular output instead."""
@@ -387,40 +383,10 b' class InteractiveShell(SingletonConfigurable):'
387 history_load_length = Integer(1000, help=
383 history_load_length = Integer(1000, help=
388 """
384 """
389 The number of saved history entries to be loaded
385 The number of saved history entries to be loaded
390 into the readline buffer at startup.
386 into the history buffer at startup.
391 """
387 """
392 ).tag(config=True)
388 ).tag(config=True)
393
389
394 # The readline stuff will eventually be moved to the terminal subclass
395 # but for now, we can't do that as readline is welded in everywhere.
396 readline_use = Bool(True).tag(config=True)
397 readline_remove_delims = Unicode('-/~').tag(config=True)
398 readline_delims = Unicode() # set by init_readline()
399 # don't use \M- bindings by default, because they
400 # conflict with 8-bit encodings. See gh-58,gh-88
401 readline_parse_and_bind = List([
402 'tab: complete',
403 '"\C-l": clear-screen',
404 'set show-all-if-ambiguous on',
405 '"\C-o": tab-insert',
406 '"\C-r": reverse-search-history',
407 '"\C-s": forward-search-history',
408 '"\C-p": history-search-backward',
409 '"\C-n": history-search-forward',
410 '"\e[A": history-search-backward',
411 '"\e[B": history-search-forward',
412 '"\C-k": kill-line',
413 '"\C-u": unix-line-discard',
414 ]).tag(config=True)
415
416 _custom_readline_config = False
417
418 @observe('readline_parse_and_bind')
419 def _readline_parse_and_bind_changed(self, change):
420 # notice that readline config is customized
421 # indicates that it should have higher priority than inputrc
422 self._custom_readline_config = True
423
424 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
390 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
425 default_value='last_expr',
391 default_value='last_expr',
426 help="""
392 help="""
@@ -607,9 +573,6 b' class InteractiveShell(SingletonConfigurable):'
607 self.tempfiles = []
573 self.tempfiles = []
608 self.tempdirs = []
574 self.tempdirs = []
609
575
610 # Keep track of readline usage (later set by init_readline)
611 self.has_readline = False
612
613 # keep track of where we started running (mainly for crash post-mortem)
576 # keep track of where we started running (mainly for crash post-mortem)
614 # This is not being used anywhere currently.
577 # This is not being used anywhere currently.
615 self.starting_dir = py3compat.getcwd()
578 self.starting_dir = py3compat.getcwd()
@@ -692,11 +655,8 b' class InteractiveShell(SingletonConfigurable):'
692 # override sys.stdout and sys.stderr themselves, you need to do that
655 # override sys.stdout and sys.stderr themselves, you need to do that
693 # *before* instantiating this class, because io holds onto
656 # *before* instantiating this class, because io holds onto
694 # references to the underlying streams.
657 # references to the underlying streams.
695 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
658 io.stdout = io.IOStream(sys.stdout)
696 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
659 io.stderr = io.IOStream(sys.stderr)
697 else:
698 io.stdout = io.IOStream(sys.stdout)
699 io.stderr = io.IOStream(sys.stderr)
700
660
701 def init_prompts(self):
661 def init_prompts(self):
702 # Set system prompts, so that scripts can decide if they are running
662 # Set system prompts, so that scripts can decide if they are running
@@ -1017,9 +977,7 b' class InteractiveShell(SingletonConfigurable):'
1017 error('No traceback has been produced, nothing to debug.')
977 error('No traceback has been produced, nothing to debug.')
1018 return
978 return
1019
979
1020
980 self.InteractiveTB.debugger(force=True)
1021 with self.readline_no_record:
1022 self.InteractiveTB.debugger(force=True)
1023
981
1024 #-------------------------------------------------------------------------
982 #-------------------------------------------------------------------------
1025 # Things related to IPython's various namespaces
983 # Things related to IPython's various namespaces
@@ -1921,11 +1879,12 b' class InteractiveShell(SingletonConfigurable):'
1921 #-------------------------------------------------------------------------
1879 #-------------------------------------------------------------------------
1922
1880
1923 def init_readline(self):
1881 def init_readline(self):
1924 """Moved to terminal subclass, here only to simplify the init logic."""
1882 """DEPRECATED
1925 self.readline = None
1883
1884 Moved to terminal subclass, here only to simplify the init logic."""
1926 # Set a number of methods that depend on readline to be no-op
1885 # Set a number of methods that depend on readline to be no-op
1927 self.readline_no_record = NoOpContext()
1886 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1928 self.set_readline_completer = no_op
1887 DeprecationWarning, stacklevel=2)
1929 self.set_custom_completer = no_op
1888 self.set_custom_completer = no_op
1930
1889
1931 @skip_doctest
1890 @skip_doctest
@@ -1962,7 +1921,7 b' class InteractiveShell(SingletonConfigurable):'
1962 self.Completer = IPCompleter(shell=self,
1921 self.Completer = IPCompleter(shell=self,
1963 namespace=self.user_ns,
1922 namespace=self.user_ns,
1964 global_namespace=self.user_global_ns,
1923 global_namespace=self.user_global_ns,
1965 use_readline=self.has_readline,
1924 use_readline=False,
1966 parent=self,
1925 parent=self,
1967 )
1926 )
1968 self.configurables.append(self.Completer)
1927 self.configurables.append(self.Completer)
@@ -705,55 +705,54 b' python-profiler package from non-free.""")'
705
705
706 try:
706 try:
707 stats = None
707 stats = None
708 with self.shell.readline_no_record:
708 if 'p' in opts:
709 if 'p' in opts:
709 stats = self._run_with_profiler(code, opts, code_ns)
710 stats = self._run_with_profiler(code, opts, code_ns)
710 else:
711 if 'd' in opts:
712 bp_file, bp_line = parse_breakpoint(
713 opts.get('b', ['1'])[0], filename)
714 self._run_with_debugger(
715 code, code_ns, filename, bp_line, bp_file)
711 else:
716 else:
712 if 'd' in opts:
717 if 'm' in opts:
713 bp_file, bp_line = parse_breakpoint(
718 def run():
714 opts.get('b', ['1'])[0], filename)
719 self.shell.safe_run_module(modulename, prog_ns)
715 self._run_with_debugger(
716 code, code_ns, filename, bp_line, bp_file)
717 else:
720 else:
718 if 'm' in opts:
721 if runner is None:
719 def run():
722 runner = self.default_runner
720 self.shell.safe_run_module(modulename, prog_ns)
723 if runner is None:
721 else:
724 runner = self.shell.safe_execfile
722 if runner is None:
725
723 runner = self.default_runner
726 def run():
724 if runner is None:
727 runner(filename, prog_ns, prog_ns,
725 runner = self.shell.safe_execfile
728 exit_ignore=exit_ignore)
726
729
727 def run():
730 if 't' in opts:
728 runner(filename, prog_ns, prog_ns,
731 # timed execution
729 exit_ignore=exit_ignore)
732 try:
730
733 nruns = int(opts['N'][0])
731 if 't' in opts:
734 if nruns < 1:
732 # timed execution
735 error('Number of runs must be >=1')
733 try:
736 return
734 nruns = int(opts['N'][0])
737 except (KeyError):
735 if nruns < 1:
738 nruns = 1
736 error('Number of runs must be >=1')
739 self._run_with_timing(run, nruns)
737 return
740 else:
738 except (KeyError):
741 # regular execution
739 nruns = 1
742 run()
740 self._run_with_timing(run, nruns)
743
741 else:
744 if 'i' in opts:
742 # regular execution
745 self.shell.user_ns['__name__'] = __name__save
743 run()
746 else:
744
747 # update IPython interactive namespace
745 if 'i' in opts:
746 self.shell.user_ns['__name__'] = __name__save
747 else:
748 # update IPython interactive namespace
749
748
750 # Some forms of read errors on the file may mean the
749 # Some forms of read errors on the file may mean the
751 # __name__ key was never set; using pop we don't have to
750 # __name__ key was never set; using pop we don't have to
752 # worry about a possible KeyError.
751 # worry about a possible KeyError.
753 prog_ns.pop('__name__', None)
752 prog_ns.pop('__name__', None)
754
753
755 with preserve_keys(self.shell.user_ns, '__file__'):
754 with preserve_keys(self.shell.user_ns, '__file__'):
756 self.shell.user_ns.update(prog_ns)
755 self.shell.user_ns.update(prog_ns)
757 finally:
756 finally:
758 # It's a bit of a mystery why, but __builtins__ can change from
757 # It's a bit of a mystery why, but __builtins__ can change from
759 # being a module to becoming a dict missing some key data after
758 # being a module to becoming a dict missing some key data after
@@ -343,12 +343,6 b' class InteractiveShellApp(Configurable):'
343 except:
343 except:
344 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
344 self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup)
345 self.shell.showtraceback()
345 self.shell.showtraceback()
346 finally:
347 # Many PYTHONSTARTUP files set up the readline completions,
348 # but this is often at odds with IPython's own completions.
349 # Do not allow PYTHONSTARTUP to set up readline.
350 if self.shell.has_readline:
351 self.shell.set_readline_completer()
352
346
353 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
347 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
354 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
348 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
@@ -115,7 +115,6 b' from inspect import getsourcefile, getfile, getmodule, \\'
115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
116
116
117 # IPython's own modules
117 # IPython's own modules
118 # Modified pdb which doesn't damage IPython's readline handling
119 from IPython import get_ipython
118 from IPython import get_ipython
120 from IPython.core import debugger
119 from IPython.core import debugger
121 from IPython.core.display_trap import DisplayTrap
120 from IPython.core.display_trap import DisplayTrap
@@ -109,12 +109,9 b' MAIN FEATURES'
109 variable names, and show you a list of the possible completions if there's
109 variable names, and show you a list of the possible completions if there's
110 no unambiguous one. It will also complete filenames in the current directory.
110 no unambiguous one. It will also complete filenames in the current directory.
111
111
112 This feature requires the readline and rlcomplete modules, so it won't work
112 * Search previous command history in two ways:
113 if your Python lacks readline support (such as under Windows).
114
113
115 * Search previous command history in two ways (also requires readline):
114 - Start typing, and then use Ctrl-p (previous, up) and Ctrl-n (next,down) to
116
117 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
118 search through only the history items that match what you've typed so
115 search through only the history items that match what you've typed so
119 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
116 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
120 normal arrow keys.
117 normal arrow keys.
@@ -123,7 +120,7 b' MAIN FEATURES'
123 your history for lines that match what you've typed so far, completing as
120 your history for lines that match what you've typed so far, completing as
124 much as it can.
121 much as it can.
125
122
126 - %hist: search history by index (this does *not* require readline).
123 - %hist: search history by index.
127
124
128 * Persistent command history across sessions.
125 * Persistent command history across sessions.
129
126
@@ -255,7 +252,6 b' MAIN FEATURES'
255 interactive_usage_min = """\
252 interactive_usage_min = """\
256 An enhanced console for Python.
253 An enhanced console for Python.
257 Some of its features are:
254 Some of its features are:
258 - Readline support if the readline library is present.
259 - Tab completion in the local namespace.
255 - Tab completion in the local namespace.
260 - Logging of input, see command-line options.
256 - Logging of input, see command-line options.
261 - System shell escape via ! , eg !ls.
257 - System shell escape via ! , eg !ls.
@@ -140,9 +140,6 b' class InteractiveShellEmbed(TerminalInteractiveShell):'
140 if dummy or (dummy != 0 and self.dummy_mode):
140 if dummy or (dummy != 0 and self.dummy_mode):
141 return
141 return
142
142
143 if self.has_readline:
144 self.set_readline_completer()
145
146 # self.banner is auto computed
143 # self.banner is auto computed
147 if header:
144 if header:
148 self.old_banner2 = self.banner2
145 self.old_banner2 = self.banner2
@@ -2,6 +2,8 b''
2 """Miscellaneous context managers.
2 """Miscellaneous context managers.
3 """
3 """
4
4
5 import warnings
6
5 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
7
9
@@ -59,6 +61,14 b' class preserve_keys(object):'
59
61
60
62
61 class NoOpContext(object):
63 class NoOpContext(object):
62 """Context manager that does nothing."""
64 """
65 Deprecated
66
67 Context manager that does nothing."""
68
69 def __init__(self):
70 warnings.warn("""NoOpContext is deprecated since IPython 5.0 """,
71 DeprecationWarning, stacklevel=2)
72
63 def __enter__(self): pass
73 def __enter__(self): pass
64 def __exit__(self, type, value, traceback): pass
74 def __exit__(self, type, value, traceback): pass
@@ -220,20 +220,8 b" if not any(arg.startswith('bdist') for arg in sys.argv):"
220
220
221 if sys.platform == 'darwin':
221 if sys.platform == 'darwin':
222 install_requires.extend(['appnope'])
222 install_requires.extend(['appnope'])
223 have_readline = False
223
224 try:
224 if not sys.platform.startswith('win'):
225 import readline
226 except ImportError:
227 pass
228 else:
229 if 'libedit' not in readline.__doc__:
230 have_readline = True
231 if not have_readline:
232 install_requires.extend(['gnureadline'])
233
234 if sys.platform.startswith('win'):
235 extras_require['terminal'].append('pyreadline>=2.0')
236 else:
237 install_requires.append('pexpect')
225 install_requires.append('pexpect')
238
226
239 # workaround pypa/setuptools#147, where setuptools misspells
227 # workaround pypa/setuptools#147, where setuptools misspells
General Comments 0
You need to be logged in to leave comments. Login now