##// END OF EJS Templates
Backport PR #12007: Fix the right inputhook
Matthias Bussonnier -
Show More
@@ -1,126 +1,126 b''
1 import signal
1 import signal
2 import sys
2 import sys
3
3
4 from IPython.core.debugger import Pdb
4 from IPython.core.debugger import Pdb
5
5
6 from IPython.core.completer import IPCompleter
6 from IPython.core.completer import IPCompleter
7 from .ptutils import IPythonPTCompleter
7 from .ptutils import IPythonPTCompleter
8 from .shortcuts import suspend_to_bg, cursor_in_leading_ws
8 from .shortcuts import suspend_to_bg, cursor_in_leading_ws
9
9
10 from prompt_toolkit.enums import DEFAULT_BUFFER
10 from prompt_toolkit.enums import DEFAULT_BUFFER
11 from prompt_toolkit.filters import (Condition, has_focus, has_selection,
11 from prompt_toolkit.filters import (Condition, has_focus, has_selection,
12 vi_insert_mode, emacs_insert_mode)
12 vi_insert_mode, emacs_insert_mode)
13 from prompt_toolkit.key_binding import KeyBindings
13 from prompt_toolkit.key_binding import KeyBindings
14 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
14 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
15 from pygments.token import Token
15 from pygments.token import Token
16 from prompt_toolkit.shortcuts.prompt import PromptSession
16 from prompt_toolkit.shortcuts.prompt import PromptSession
17 from prompt_toolkit.enums import EditingMode
17 from prompt_toolkit.enums import EditingMode
18 from prompt_toolkit.formatted_text import PygmentsTokens
18 from prompt_toolkit.formatted_text import PygmentsTokens
19
19
20 from prompt_toolkit import __version__ as ptk_version
20 from prompt_toolkit import __version__ as ptk_version
21 PTK3 = ptk_version.startswith('3.')
21 PTK3 = ptk_version.startswith('3.')
22
22
23
23
24 class TerminalPdb(Pdb):
24 class TerminalPdb(Pdb):
25 """Standalone IPython debugger."""
25 """Standalone IPython debugger."""
26
26
27 def __init__(self, *args, **kwargs):
27 def __init__(self, *args, **kwargs):
28 Pdb.__init__(self, *args, **kwargs)
28 Pdb.__init__(self, *args, **kwargs)
29 self._ptcomp = None
29 self._ptcomp = None
30 self.pt_init()
30 self.pt_init()
31
31
32 def pt_init(self):
32 def pt_init(self):
33 def get_prompt_tokens():
33 def get_prompt_tokens():
34 return [(Token.Prompt, self.prompt)]
34 return [(Token.Prompt, self.prompt)]
35
35
36 if self._ptcomp is None:
36 if self._ptcomp is None:
37 compl = IPCompleter(shell=self.shell,
37 compl = IPCompleter(shell=self.shell,
38 namespace={},
38 namespace={},
39 global_namespace={},
39 global_namespace={},
40 parent=self.shell,
40 parent=self.shell,
41 )
41 )
42 self._ptcomp = IPythonPTCompleter(compl)
42 self._ptcomp = IPythonPTCompleter(compl)
43
43
44 kb = KeyBindings()
44 kb = KeyBindings()
45 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
45 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
46 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
46 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
47
47
48 if self.shell.display_completions == 'readlinelike':
48 if self.shell.display_completions == 'readlinelike':
49 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
49 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
50 & ~has_selection
50 & ~has_selection
51 & vi_insert_mode | emacs_insert_mode
51 & vi_insert_mode | emacs_insert_mode
52 & ~cursor_in_leading_ws
52 & ~cursor_in_leading_ws
53 ))(display_completions_like_readline)
53 ))(display_completions_like_readline)
54
54
55 options = dict(
55 options = dict(
56 message=(lambda: PygmentsTokens(get_prompt_tokens())),
56 message=(lambda: PygmentsTokens(get_prompt_tokens())),
57 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
57 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
58 key_bindings=kb,
58 key_bindings=kb,
59 history=self.shell.debugger_history,
59 history=self.shell.debugger_history,
60 completer=self._ptcomp,
60 completer=self._ptcomp,
61 enable_history_search=True,
61 enable_history_search=True,
62 mouse_support=self.shell.mouse_support,
62 mouse_support=self.shell.mouse_support,
63 complete_style=self.shell.pt_complete_style,
63 complete_style=self.shell.pt_complete_style,
64 style=self.shell.style,
64 style=self.shell.style,
65 color_depth=self.shell.color_depth,
65 color_depth=self.shell.color_depth,
66 )
66 )
67
67
68 if not PTK3:
68 if not PTK3:
69 options['inputhook'] = self.inputhook
69 options['inputhook'] = self.shell.inputhook
70 self.pt_app = PromptSession(**options)
70 self.pt_app = PromptSession(**options)
71
71
72 def cmdloop(self, intro=None):
72 def cmdloop(self, intro=None):
73 """Repeatedly issue a prompt, accept input, parse an initial prefix
73 """Repeatedly issue a prompt, accept input, parse an initial prefix
74 off the received input, and dispatch to action methods, passing them
74 off the received input, and dispatch to action methods, passing them
75 the remainder of the line as argument.
75 the remainder of the line as argument.
76
76
77 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
77 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
78 """
78 """
79 if not self.use_rawinput:
79 if not self.use_rawinput:
80 raise ValueError('Sorry ipdb does not support use_rawinput=False')
80 raise ValueError('Sorry ipdb does not support use_rawinput=False')
81
81
82 self.preloop()
82 self.preloop()
83
83
84 try:
84 try:
85 if intro is not None:
85 if intro is not None:
86 self.intro = intro
86 self.intro = intro
87 if self.intro:
87 if self.intro:
88 self.stdout.write(str(self.intro)+"\n")
88 self.stdout.write(str(self.intro)+"\n")
89 stop = None
89 stop = None
90 while not stop:
90 while not stop:
91 if self.cmdqueue:
91 if self.cmdqueue:
92 line = self.cmdqueue.pop(0)
92 line = self.cmdqueue.pop(0)
93 else:
93 else:
94 self._ptcomp.ipy_completer.namespace = self.curframe_locals
94 self._ptcomp.ipy_completer.namespace = self.curframe_locals
95 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
95 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
96 try:
96 try:
97 line = self.pt_app.prompt() # reset_current_buffer=True)
97 line = self.pt_app.prompt() # reset_current_buffer=True)
98 except EOFError:
98 except EOFError:
99 line = 'EOF'
99 line = 'EOF'
100 line = self.precmd(line)
100 line = self.precmd(line)
101 stop = self.onecmd(line)
101 stop = self.onecmd(line)
102 stop = self.postcmd(stop, line)
102 stop = self.postcmd(stop, line)
103 self.postloop()
103 self.postloop()
104 except Exception:
104 except Exception:
105 raise
105 raise
106
106
107
107
108 def set_trace(frame=None):
108 def set_trace(frame=None):
109 """
109 """
110 Start debugging from `frame`.
110 Start debugging from `frame`.
111
111
112 If frame is not specified, debugging starts from caller's frame.
112 If frame is not specified, debugging starts from caller's frame.
113 """
113 """
114 TerminalPdb().set_trace(frame or sys._getframe().f_back)
114 TerminalPdb().set_trace(frame or sys._getframe().f_back)
115
115
116
116
117 if __name__ == '__main__':
117 if __name__ == '__main__':
118 import pdb
118 import pdb
119 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
119 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
120 # bdb.BdbQuit. When started through __main__ and an exception
120 # bdb.BdbQuit. When started through __main__ and an exception
121 # happened after hitting "c", this is needed in order to
121 # happened after hitting "c", this is needed in order to
122 # be able to quit the debugging session (see #9950).
122 # be able to quit the debugging session (see #9950).
123 old_trace_dispatch = pdb.Pdb.trace_dispatch
123 old_trace_dispatch = pdb.Pdb.trace_dispatch
124 pdb.Pdb = TerminalPdb
124 pdb.Pdb = TerminalPdb
125 pdb.Pdb.trace_dispatch = old_trace_dispatch
125 pdb.Pdb.trace_dispatch = old_trace_dispatch
126 pdb.main()
126 pdb.main()
@@ -1,640 +1,640 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2
2
3 import asyncio
3 import asyncio
4 import os
4 import os
5 import sys
5 import sys
6 import warnings
6 import warnings
7 from warnings import warn
7 from warnings import warn
8
8
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
10 from IPython.utils import io
10 from IPython.utils import io
11 from IPython.utils.py3compat import input
11 from IPython.utils.py3compat import input
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
13 from IPython.utils.process import abbrev_cwd
13 from IPython.utils.process import abbrev_cwd
14 from traitlets import (
14 from traitlets import (
15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
16 Any, validate
16 Any, validate
17 )
17 )
18
18
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
21 from prompt_toolkit.formatted_text import PygmentsTokens
21 from prompt_toolkit.formatted_text import PygmentsTokens
22 from prompt_toolkit.history import InMemoryHistory
22 from prompt_toolkit.history import InMemoryHistory
23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
24 from prompt_toolkit.output import ColorDepth
24 from prompt_toolkit.output import ColorDepth
25 from prompt_toolkit.patch_stdout import patch_stdout
25 from prompt_toolkit.patch_stdout import patch_stdout
26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
27 from prompt_toolkit.styles import DynamicStyle, merge_styles
27 from prompt_toolkit.styles import DynamicStyle, merge_styles
28 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
28 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
29 from prompt_toolkit import __version__ as ptk_version
29 from prompt_toolkit import __version__ as ptk_version
30
30
31 from pygments.styles import get_style_by_name
31 from pygments.styles import get_style_by_name
32 from pygments.style import Style
32 from pygments.style import Style
33 from pygments.token import Token
33 from pygments.token import Token
34
34
35 from .debugger import TerminalPdb, Pdb
35 from .debugger import TerminalPdb, Pdb
36 from .magics import TerminalMagics
36 from .magics import TerminalMagics
37 from .pt_inputhooks import get_inputhook_name_and_func
37 from .pt_inputhooks import get_inputhook_name_and_func
38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
40 from .shortcuts import create_ipython_shortcuts
40 from .shortcuts import create_ipython_shortcuts
41
41
42 DISPLAY_BANNER_DEPRECATED = object()
42 DISPLAY_BANNER_DEPRECATED = object()
43 PTK3 = ptk_version.startswith('3.')
43 PTK3 = ptk_version.startswith('3.')
44
44
45
45
46 class _NoStyle(Style): pass
46 class _NoStyle(Style): pass
47
47
48
48
49
49
50 _style_overrides_light_bg = {
50 _style_overrides_light_bg = {
51 Token.Prompt: '#0000ff',
51 Token.Prompt: '#0000ff',
52 Token.PromptNum: '#0000ee bold',
52 Token.PromptNum: '#0000ee bold',
53 Token.OutPrompt: '#cc0000',
53 Token.OutPrompt: '#cc0000',
54 Token.OutPromptNum: '#bb0000 bold',
54 Token.OutPromptNum: '#bb0000 bold',
55 }
55 }
56
56
57 _style_overrides_linux = {
57 _style_overrides_linux = {
58 Token.Prompt: '#00cc00',
58 Token.Prompt: '#00cc00',
59 Token.PromptNum: '#00bb00 bold',
59 Token.PromptNum: '#00bb00 bold',
60 Token.OutPrompt: '#cc0000',
60 Token.OutPrompt: '#cc0000',
61 Token.OutPromptNum: '#bb0000 bold',
61 Token.OutPromptNum: '#bb0000 bold',
62 }
62 }
63
63
64 def get_default_editor():
64 def get_default_editor():
65 try:
65 try:
66 return os.environ['EDITOR']
66 return os.environ['EDITOR']
67 except KeyError:
67 except KeyError:
68 pass
68 pass
69 except UnicodeError:
69 except UnicodeError:
70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
71 "default editor.")
71 "default editor.")
72
72
73 if os.name == 'posix':
73 if os.name == 'posix':
74 return 'vi' # the only one guaranteed to be there!
74 return 'vi' # the only one guaranteed to be there!
75 else:
75 else:
76 return 'notepad' # same in Windows!
76 return 'notepad' # same in Windows!
77
77
78 # conservatively check for tty
78 # conservatively check for tty
79 # overridden streams can result in things like:
79 # overridden streams can result in things like:
80 # - sys.stdin = None
80 # - sys.stdin = None
81 # - no isatty method
81 # - no isatty method
82 for _name in ('stdin', 'stdout', 'stderr'):
82 for _name in ('stdin', 'stdout', 'stderr'):
83 _stream = getattr(sys, _name)
83 _stream = getattr(sys, _name)
84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
85 _is_tty = False
85 _is_tty = False
86 break
86 break
87 else:
87 else:
88 _is_tty = True
88 _is_tty = True
89
89
90
90
91 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
91 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
92
92
93 def black_reformat_handler(text_before_cursor):
93 def black_reformat_handler(text_before_cursor):
94 import black
94 import black
95 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
95 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
96 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
96 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
97 formatted_text = formatted_text[:-1]
97 formatted_text = formatted_text[:-1]
98 return formatted_text
98 return formatted_text
99
99
100
100
101 class TerminalInteractiveShell(InteractiveShell):
101 class TerminalInteractiveShell(InteractiveShell):
102 mime_renderers = Dict().tag(config=True)
102 mime_renderers = Dict().tag(config=True)
103
103
104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
105 'to reserve for the completion menu'
105 'to reserve for the completion menu'
106 ).tag(config=True)
106 ).tag(config=True)
107
107
108 pt_app = None
108 pt_app = None
109 debugger_history = None
109 debugger_history = None
110
110
111 simple_prompt = Bool(_use_simple_prompt,
111 simple_prompt = Bool(_use_simple_prompt,
112 help="""Use `raw_input` for the REPL, without completion and prompt colors.
112 help="""Use `raw_input` for the REPL, without completion and prompt colors.
113
113
114 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
114 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
115 IPython own testing machinery, and emacs inferior-shell integration through elpy.
115 IPython own testing machinery, and emacs inferior-shell integration through elpy.
116
116
117 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
117 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
118 environment variable is set, or the current terminal is not a tty."""
118 environment variable is set, or the current terminal is not a tty."""
119 ).tag(config=True)
119 ).tag(config=True)
120
120
121 @property
121 @property
122 def debugger_cls(self):
122 def debugger_cls(self):
123 return Pdb if self.simple_prompt else TerminalPdb
123 return Pdb if self.simple_prompt else TerminalPdb
124
124
125 confirm_exit = Bool(True,
125 confirm_exit = Bool(True,
126 help="""
126 help="""
127 Set to confirm when you try to exit IPython with an EOF (Control-D
127 Set to confirm when you try to exit IPython with an EOF (Control-D
128 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
128 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
129 you can force a direct exit without any confirmation.""",
129 you can force a direct exit without any confirmation.""",
130 ).tag(config=True)
130 ).tag(config=True)
131
131
132 editing_mode = Unicode('emacs',
132 editing_mode = Unicode('emacs',
133 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
133 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
134 ).tag(config=True)
134 ).tag(config=True)
135
135
136 autoformatter = Unicode(None,
136 autoformatter = Unicode(None,
137 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
137 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
138 allow_none=True
138 allow_none=True
139 ).tag(config=True)
139 ).tag(config=True)
140
140
141 mouse_support = Bool(False,
141 mouse_support = Bool(False,
142 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
142 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
143 ).tag(config=True)
143 ).tag(config=True)
144
144
145 # We don't load the list of styles for the help string, because loading
145 # We don't load the list of styles for the help string, because loading
146 # Pygments plugins takes time and can cause unexpected errors.
146 # Pygments plugins takes time and can cause unexpected errors.
147 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
147 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
148 help="""The name or class of a Pygments style to use for syntax
148 help="""The name or class of a Pygments style to use for syntax
149 highlighting. To see available styles, run `pygmentize -L styles`."""
149 highlighting. To see available styles, run `pygmentize -L styles`."""
150 ).tag(config=True)
150 ).tag(config=True)
151
151
152 @validate('editing_mode')
152 @validate('editing_mode')
153 def _validate_editing_mode(self, proposal):
153 def _validate_editing_mode(self, proposal):
154 if proposal['value'].lower() == 'vim':
154 if proposal['value'].lower() == 'vim':
155 proposal['value']= 'vi'
155 proposal['value']= 'vi'
156 elif proposal['value'].lower() == 'default':
156 elif proposal['value'].lower() == 'default':
157 proposal['value']= 'emacs'
157 proposal['value']= 'emacs'
158
158
159 if hasattr(EditingMode, proposal['value'].upper()):
159 if hasattr(EditingMode, proposal['value'].upper()):
160 return proposal['value'].lower()
160 return proposal['value'].lower()
161
161
162 return self.editing_mode
162 return self.editing_mode
163
163
164
164
165 @observe('editing_mode')
165 @observe('editing_mode')
166 def _editing_mode(self, change):
166 def _editing_mode(self, change):
167 u_mode = change.new.upper()
167 u_mode = change.new.upper()
168 if self.pt_app:
168 if self.pt_app:
169 self.pt_app.editing_mode = u_mode
169 self.pt_app.editing_mode = u_mode
170
170
171 @observe('autoformatter')
171 @observe('autoformatter')
172 def _autoformatter_changed(self, change):
172 def _autoformatter_changed(self, change):
173 formatter = change.new
173 formatter = change.new
174 if formatter is None:
174 if formatter is None:
175 self.reformat_handler = lambda x:x
175 self.reformat_handler = lambda x:x
176 elif formatter == 'black':
176 elif formatter == 'black':
177 self.reformat_handler = black_reformat_handler
177 self.reformat_handler = black_reformat_handler
178 else:
178 else:
179 raise ValueError
179 raise ValueError
180
180
181 @observe('highlighting_style')
181 @observe('highlighting_style')
182 @observe('colors')
182 @observe('colors')
183 def _highlighting_style_changed(self, change):
183 def _highlighting_style_changed(self, change):
184 self.refresh_style()
184 self.refresh_style()
185
185
186 def refresh_style(self):
186 def refresh_style(self):
187 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
187 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
188
188
189
189
190 highlighting_style_overrides = Dict(
190 highlighting_style_overrides = Dict(
191 help="Override highlighting format for specific tokens"
191 help="Override highlighting format for specific tokens"
192 ).tag(config=True)
192 ).tag(config=True)
193
193
194 true_color = Bool(False,
194 true_color = Bool(False,
195 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
195 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
196 "If your terminal supports true color, the following command "
196 "If your terminal supports true color, the following command "
197 "should print 'TRUECOLOR' in orange: "
197 "should print 'TRUECOLOR' in orange: "
198 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
198 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
199 ).tag(config=True)
199 ).tag(config=True)
200
200
201 editor = Unicode(get_default_editor(),
201 editor = Unicode(get_default_editor(),
202 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
202 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
203 ).tag(config=True)
203 ).tag(config=True)
204
204
205 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
205 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
206
206
207 prompts = Instance(Prompts)
207 prompts = Instance(Prompts)
208
208
209 @default('prompts')
209 @default('prompts')
210 def _prompts_default(self):
210 def _prompts_default(self):
211 return self.prompts_class(self)
211 return self.prompts_class(self)
212
212
213 # @observe('prompts')
213 # @observe('prompts')
214 # def _(self, change):
214 # def _(self, change):
215 # self._update_layout()
215 # self._update_layout()
216
216
217 @default('displayhook_class')
217 @default('displayhook_class')
218 def _displayhook_class_default(self):
218 def _displayhook_class_default(self):
219 return RichPromptDisplayHook
219 return RichPromptDisplayHook
220
220
221 term_title = Bool(True,
221 term_title = Bool(True,
222 help="Automatically set the terminal title"
222 help="Automatically set the terminal title"
223 ).tag(config=True)
223 ).tag(config=True)
224
224
225 term_title_format = Unicode("IPython: {cwd}",
225 term_title_format = Unicode("IPython: {cwd}",
226 help="Customize the terminal title format. This is a python format string. " +
226 help="Customize the terminal title format. This is a python format string. " +
227 "Available substitutions are: {cwd}."
227 "Available substitutions are: {cwd}."
228 ).tag(config=True)
228 ).tag(config=True)
229
229
230 display_completions = Enum(('column', 'multicolumn','readlinelike'),
230 display_completions = Enum(('column', 'multicolumn','readlinelike'),
231 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
231 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
232 "'readlinelike'. These options are for `prompt_toolkit`, see "
232 "'readlinelike'. These options are for `prompt_toolkit`, see "
233 "`prompt_toolkit` documentation for more information."
233 "`prompt_toolkit` documentation for more information."
234 ),
234 ),
235 default_value='multicolumn').tag(config=True)
235 default_value='multicolumn').tag(config=True)
236
236
237 highlight_matching_brackets = Bool(True,
237 highlight_matching_brackets = Bool(True,
238 help="Highlight matching brackets.",
238 help="Highlight matching brackets.",
239 ).tag(config=True)
239 ).tag(config=True)
240
240
241 extra_open_editor_shortcuts = Bool(False,
241 extra_open_editor_shortcuts = Bool(False,
242 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
242 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
243 "This is in addition to the F2 binding, which is always enabled."
243 "This is in addition to the F2 binding, which is always enabled."
244 ).tag(config=True)
244 ).tag(config=True)
245
245
246 handle_return = Any(None,
246 handle_return = Any(None,
247 help="Provide an alternative handler to be called when the user presses "
247 help="Provide an alternative handler to be called when the user presses "
248 "Return. This is an advanced option intended for debugging, which "
248 "Return. This is an advanced option intended for debugging, which "
249 "may be changed or removed in later releases."
249 "may be changed or removed in later releases."
250 ).tag(config=True)
250 ).tag(config=True)
251
251
252 enable_history_search = Bool(True,
252 enable_history_search = Bool(True,
253 help="Allows to enable/disable the prompt toolkit history search"
253 help="Allows to enable/disable the prompt toolkit history search"
254 ).tag(config=True)
254 ).tag(config=True)
255
255
256 prompt_includes_vi_mode = Bool(True,
256 prompt_includes_vi_mode = Bool(True,
257 help="Display the current vi mode (when using vi editing mode)."
257 help="Display the current vi mode (when using vi editing mode)."
258 ).tag(config=True)
258 ).tag(config=True)
259
259
260 @observe('term_title')
260 @observe('term_title')
261 def init_term_title(self, change=None):
261 def init_term_title(self, change=None):
262 # Enable or disable the terminal title.
262 # Enable or disable the terminal title.
263 if self.term_title:
263 if self.term_title:
264 toggle_set_term_title(True)
264 toggle_set_term_title(True)
265 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
265 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
266 else:
266 else:
267 toggle_set_term_title(False)
267 toggle_set_term_title(False)
268
268
269 def restore_term_title(self):
269 def restore_term_title(self):
270 if self.term_title:
270 if self.term_title:
271 restore_term_title()
271 restore_term_title()
272
272
273 def init_display_formatter(self):
273 def init_display_formatter(self):
274 super(TerminalInteractiveShell, self).init_display_formatter()
274 super(TerminalInteractiveShell, self).init_display_formatter()
275 # terminal only supports plain text
275 # terminal only supports plain text
276 self.display_formatter.active_types = ['text/plain']
276 self.display_formatter.active_types = ['text/plain']
277 # disable `_ipython_display_`
277 # disable `_ipython_display_`
278 self.display_formatter.ipython_display_formatter.enabled = False
278 self.display_formatter.ipython_display_formatter.enabled = False
279
279
280 def init_prompt_toolkit_cli(self):
280 def init_prompt_toolkit_cli(self):
281 if self.simple_prompt:
281 if self.simple_prompt:
282 # Fall back to plain non-interactive output for tests.
282 # Fall back to plain non-interactive output for tests.
283 # This is very limited.
283 # This is very limited.
284 def prompt():
284 def prompt():
285 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
285 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
286 lines = [input(prompt_text)]
286 lines = [input(prompt_text)]
287 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
287 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
288 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
288 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
289 lines.append( input(prompt_continuation) )
289 lines.append( input(prompt_continuation) )
290 return '\n'.join(lines)
290 return '\n'.join(lines)
291 self.prompt_for_code = prompt
291 self.prompt_for_code = prompt
292 return
292 return
293
293
294 # Set up keyboard shortcuts
294 # Set up keyboard shortcuts
295 key_bindings = create_ipython_shortcuts(self)
295 key_bindings = create_ipython_shortcuts(self)
296
296
297 # Pre-populate history from IPython's history database
297 # Pre-populate history from IPython's history database
298 history = InMemoryHistory()
298 history = InMemoryHistory()
299 last_cell = u""
299 last_cell = u""
300 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
300 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
301 include_latest=True):
301 include_latest=True):
302 # Ignore blank lines and consecutive duplicates
302 # Ignore blank lines and consecutive duplicates
303 cell = cell.rstrip()
303 cell = cell.rstrip()
304 if cell and (cell != last_cell):
304 if cell and (cell != last_cell):
305 history.append_string(cell)
305 history.append_string(cell)
306 last_cell = cell
306 last_cell = cell
307
307
308 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
308 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
309 self.style = DynamicStyle(lambda: self._style)
309 self.style = DynamicStyle(lambda: self._style)
310
310
311 editing_mode = getattr(EditingMode, self.editing_mode.upper())
311 editing_mode = getattr(EditingMode, self.editing_mode.upper())
312
312
313 self.pt_loop = asyncio.new_event_loop()
313 self.pt_loop = asyncio.new_event_loop()
314 self.pt_app = PromptSession(
314 self.pt_app = PromptSession(
315 editing_mode=editing_mode,
315 editing_mode=editing_mode,
316 key_bindings=key_bindings,
316 key_bindings=key_bindings,
317 history=history,
317 history=history,
318 completer=IPythonPTCompleter(shell=self),
318 completer=IPythonPTCompleter(shell=self),
319 enable_history_search = self.enable_history_search,
319 enable_history_search = self.enable_history_search,
320 style=self.style,
320 style=self.style,
321 include_default_pygments_style=False,
321 include_default_pygments_style=False,
322 mouse_support=self.mouse_support,
322 mouse_support=self.mouse_support,
323 enable_open_in_editor=self.extra_open_editor_shortcuts,
323 enable_open_in_editor=self.extra_open_editor_shortcuts,
324 color_depth=self.color_depth,
324 color_depth=self.color_depth,
325 **self._extra_prompt_options())
325 **self._extra_prompt_options())
326
326
327 def _make_style_from_name_or_cls(self, name_or_cls):
327 def _make_style_from_name_or_cls(self, name_or_cls):
328 """
328 """
329 Small wrapper that make an IPython compatible style from a style name
329 Small wrapper that make an IPython compatible style from a style name
330
330
331 We need that to add style for prompt ... etc.
331 We need that to add style for prompt ... etc.
332 """
332 """
333 style_overrides = {}
333 style_overrides = {}
334 if name_or_cls == 'legacy':
334 if name_or_cls == 'legacy':
335 legacy = self.colors.lower()
335 legacy = self.colors.lower()
336 if legacy == 'linux':
336 if legacy == 'linux':
337 style_cls = get_style_by_name('monokai')
337 style_cls = get_style_by_name('monokai')
338 style_overrides = _style_overrides_linux
338 style_overrides = _style_overrides_linux
339 elif legacy == 'lightbg':
339 elif legacy == 'lightbg':
340 style_overrides = _style_overrides_light_bg
340 style_overrides = _style_overrides_light_bg
341 style_cls = get_style_by_name('pastie')
341 style_cls = get_style_by_name('pastie')
342 elif legacy == 'neutral':
342 elif legacy == 'neutral':
343 # The default theme needs to be visible on both a dark background
343 # The default theme needs to be visible on both a dark background
344 # and a light background, because we can't tell what the terminal
344 # and a light background, because we can't tell what the terminal
345 # looks like. These tweaks to the default theme help with that.
345 # looks like. These tweaks to the default theme help with that.
346 style_cls = get_style_by_name('default')
346 style_cls = get_style_by_name('default')
347 style_overrides.update({
347 style_overrides.update({
348 Token.Number: '#007700',
348 Token.Number: '#007700',
349 Token.Operator: 'noinherit',
349 Token.Operator: 'noinherit',
350 Token.String: '#BB6622',
350 Token.String: '#BB6622',
351 Token.Name.Function: '#2080D0',
351 Token.Name.Function: '#2080D0',
352 Token.Name.Class: 'bold #2080D0',
352 Token.Name.Class: 'bold #2080D0',
353 Token.Name.Namespace: 'bold #2080D0',
353 Token.Name.Namespace: 'bold #2080D0',
354 Token.Prompt: '#009900',
354 Token.Prompt: '#009900',
355 Token.PromptNum: '#ansibrightgreen bold',
355 Token.PromptNum: '#ansibrightgreen bold',
356 Token.OutPrompt: '#990000',
356 Token.OutPrompt: '#990000',
357 Token.OutPromptNum: '#ansibrightred bold',
357 Token.OutPromptNum: '#ansibrightred bold',
358 })
358 })
359
359
360 # Hack: Due to limited color support on the Windows console
360 # Hack: Due to limited color support on the Windows console
361 # the prompt colors will be wrong without this
361 # the prompt colors will be wrong without this
362 if os.name == 'nt':
362 if os.name == 'nt':
363 style_overrides.update({
363 style_overrides.update({
364 Token.Prompt: '#ansidarkgreen',
364 Token.Prompt: '#ansidarkgreen',
365 Token.PromptNum: '#ansigreen bold',
365 Token.PromptNum: '#ansigreen bold',
366 Token.OutPrompt: '#ansidarkred',
366 Token.OutPrompt: '#ansidarkred',
367 Token.OutPromptNum: '#ansired bold',
367 Token.OutPromptNum: '#ansired bold',
368 })
368 })
369 elif legacy =='nocolor':
369 elif legacy =='nocolor':
370 style_cls=_NoStyle
370 style_cls=_NoStyle
371 style_overrides = {}
371 style_overrides = {}
372 else :
372 else :
373 raise ValueError('Got unknown colors: ', legacy)
373 raise ValueError('Got unknown colors: ', legacy)
374 else :
374 else :
375 if isinstance(name_or_cls, str):
375 if isinstance(name_or_cls, str):
376 style_cls = get_style_by_name(name_or_cls)
376 style_cls = get_style_by_name(name_or_cls)
377 else:
377 else:
378 style_cls = name_or_cls
378 style_cls = name_or_cls
379 style_overrides = {
379 style_overrides = {
380 Token.Prompt: '#009900',
380 Token.Prompt: '#009900',
381 Token.PromptNum: '#ansibrightgreen bold',
381 Token.PromptNum: '#ansibrightgreen bold',
382 Token.OutPrompt: '#990000',
382 Token.OutPrompt: '#990000',
383 Token.OutPromptNum: '#ansibrightred bold',
383 Token.OutPromptNum: '#ansibrightred bold',
384 }
384 }
385 style_overrides.update(self.highlighting_style_overrides)
385 style_overrides.update(self.highlighting_style_overrides)
386 style = merge_styles([
386 style = merge_styles([
387 style_from_pygments_cls(style_cls),
387 style_from_pygments_cls(style_cls),
388 style_from_pygments_dict(style_overrides),
388 style_from_pygments_dict(style_overrides),
389 ])
389 ])
390
390
391 return style
391 return style
392
392
393 @property
393 @property
394 def pt_complete_style(self):
394 def pt_complete_style(self):
395 return {
395 return {
396 'multicolumn': CompleteStyle.MULTI_COLUMN,
396 'multicolumn': CompleteStyle.MULTI_COLUMN,
397 'column': CompleteStyle.COLUMN,
397 'column': CompleteStyle.COLUMN,
398 'readlinelike': CompleteStyle.READLINE_LIKE,
398 'readlinelike': CompleteStyle.READLINE_LIKE,
399 }[self.display_completions]
399 }[self.display_completions]
400
400
401 @property
401 @property
402 def color_depth(self):
402 def color_depth(self):
403 return (ColorDepth.TRUE_COLOR if self.true_color else None)
403 return (ColorDepth.TRUE_COLOR if self.true_color else None)
404
404
405 def _extra_prompt_options(self):
405 def _extra_prompt_options(self):
406 """
406 """
407 Return the current layout option for the current Terminal InteractiveShell
407 Return the current layout option for the current Terminal InteractiveShell
408 """
408 """
409 def get_message():
409 def get_message():
410 return PygmentsTokens(self.prompts.in_prompt_tokens())
410 return PygmentsTokens(self.prompts.in_prompt_tokens())
411
411
412 if self.editing_mode == 'emacs':
412 if self.editing_mode == 'emacs':
413 # with emacs mode the prompt is (usually) static, so we call only
413 # with emacs mode the prompt is (usually) static, so we call only
414 # the function once. With VI mode it can toggle between [ins] and
414 # the function once. With VI mode it can toggle between [ins] and
415 # [nor] so we can't precompute.
415 # [nor] so we can't precompute.
416 # here I'm going to favor the default keybinding which almost
416 # here I'm going to favor the default keybinding which almost
417 # everybody uses to decrease CPU usage.
417 # everybody uses to decrease CPU usage.
418 # if we have issues with users with custom Prompts we can see how to
418 # if we have issues with users with custom Prompts we can see how to
419 # work around this.
419 # work around this.
420 get_message = get_message()
420 get_message = get_message()
421
421
422 options = {
422 options = {
423 'complete_in_thread': False,
423 'complete_in_thread': False,
424 'lexer':IPythonPTLexer(),
424 'lexer':IPythonPTLexer(),
425 'reserve_space_for_menu':self.space_for_menu,
425 'reserve_space_for_menu':self.space_for_menu,
426 'message': get_message,
426 'message': get_message,
427 'prompt_continuation': (
427 'prompt_continuation': (
428 lambda width, lineno, is_soft_wrap:
428 lambda width, lineno, is_soft_wrap:
429 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
429 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
430 'multiline': True,
430 'multiline': True,
431 'complete_style': self.pt_complete_style,
431 'complete_style': self.pt_complete_style,
432
432
433 # Highlight matching brackets, but only when this setting is
433 # Highlight matching brackets, but only when this setting is
434 # enabled, and only when the DEFAULT_BUFFER has the focus.
434 # enabled, and only when the DEFAULT_BUFFER has the focus.
435 'input_processors': [ConditionalProcessor(
435 'input_processors': [ConditionalProcessor(
436 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
436 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
437 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
437 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
438 Condition(lambda: self.highlight_matching_brackets))],
438 Condition(lambda: self.highlight_matching_brackets))],
439 }
439 }
440 if not PTK3:
440 if not PTK3:
441 options['inputhook'] = self.shell.inputhook
441 options['inputhook'] = self.inputhook
442
442
443 return options
443 return options
444
444
445 def prompt_for_code(self):
445 def prompt_for_code(self):
446 if self.rl_next_input:
446 if self.rl_next_input:
447 default = self.rl_next_input
447 default = self.rl_next_input
448 self.rl_next_input = None
448 self.rl_next_input = None
449 else:
449 else:
450 default = ''
450 default = ''
451
451
452 # In order to make sure that asyncio code written in the
452 # In order to make sure that asyncio code written in the
453 # interactive shell doesn't interfere with the prompt, we run the
453 # interactive shell doesn't interfere with the prompt, we run the
454 # prompt in a different event loop.
454 # prompt in a different event loop.
455 # If we don't do this, people could spawn coroutine with a
455 # If we don't do this, people could spawn coroutine with a
456 # while/true inside which will freeze the prompt.
456 # while/true inside which will freeze the prompt.
457
457
458 try:
458 try:
459 old_loop = asyncio.get_event_loop()
459 old_loop = asyncio.get_event_loop()
460 except RuntimeError:
460 except RuntimeError:
461 # This happens when the user used `asyncio.run()`.
461 # This happens when the user used `asyncio.run()`.
462 old_loop = None
462 old_loop = None
463
463
464 asyncio.set_event_loop(self.pt_loop)
464 asyncio.set_event_loop(self.pt_loop)
465 try:
465 try:
466 with patch_stdout(raw=True):
466 with patch_stdout(raw=True):
467 text = self.pt_app.prompt(
467 text = self.pt_app.prompt(
468 default=default,
468 default=default,
469 **self._extra_prompt_options())
469 **self._extra_prompt_options())
470 finally:
470 finally:
471 # Restore the original event loop.
471 # Restore the original event loop.
472 asyncio.set_event_loop(old_loop)
472 asyncio.set_event_loop(old_loop)
473
473
474 return text
474 return text
475
475
476 def enable_win_unicode_console(self):
476 def enable_win_unicode_console(self):
477 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
477 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
478 # console by default, so WUC shouldn't be needed.
478 # console by default, so WUC shouldn't be needed.
479 from warnings import warn
479 from warnings import warn
480 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
480 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
481 DeprecationWarning,
481 DeprecationWarning,
482 stacklevel=2)
482 stacklevel=2)
483
483
484 def init_io(self):
484 def init_io(self):
485 if sys.platform not in {'win32', 'cli'}:
485 if sys.platform not in {'win32', 'cli'}:
486 return
486 return
487
487
488 import colorama
488 import colorama
489 colorama.init()
489 colorama.init()
490
490
491 # For some reason we make these wrappers around stdout/stderr.
491 # For some reason we make these wrappers around stdout/stderr.
492 # For now, we need to reset them so all output gets coloured.
492 # For now, we need to reset them so all output gets coloured.
493 # https://github.com/ipython/ipython/issues/8669
493 # https://github.com/ipython/ipython/issues/8669
494 # io.std* are deprecated, but don't show our own deprecation warnings
494 # io.std* are deprecated, but don't show our own deprecation warnings
495 # during initialization of the deprecated API.
495 # during initialization of the deprecated API.
496 with warnings.catch_warnings():
496 with warnings.catch_warnings():
497 warnings.simplefilter('ignore', DeprecationWarning)
497 warnings.simplefilter('ignore', DeprecationWarning)
498 io.stdout = io.IOStream(sys.stdout)
498 io.stdout = io.IOStream(sys.stdout)
499 io.stderr = io.IOStream(sys.stderr)
499 io.stderr = io.IOStream(sys.stderr)
500
500
501 def init_magics(self):
501 def init_magics(self):
502 super(TerminalInteractiveShell, self).init_magics()
502 super(TerminalInteractiveShell, self).init_magics()
503 self.register_magics(TerminalMagics)
503 self.register_magics(TerminalMagics)
504
504
505 def init_alias(self):
505 def init_alias(self):
506 # The parent class defines aliases that can be safely used with any
506 # The parent class defines aliases that can be safely used with any
507 # frontend.
507 # frontend.
508 super(TerminalInteractiveShell, self).init_alias()
508 super(TerminalInteractiveShell, self).init_alias()
509
509
510 # Now define aliases that only make sense on the terminal, because they
510 # Now define aliases that only make sense on the terminal, because they
511 # need direct access to the console in a way that we can't emulate in
511 # need direct access to the console in a way that we can't emulate in
512 # GUI or web frontend
512 # GUI or web frontend
513 if os.name == 'posix':
513 if os.name == 'posix':
514 for cmd in ('clear', 'more', 'less', 'man'):
514 for cmd in ('clear', 'more', 'less', 'man'):
515 self.alias_manager.soft_define_alias(cmd, cmd)
515 self.alias_manager.soft_define_alias(cmd, cmd)
516
516
517
517
518 def __init__(self, *args, **kwargs):
518 def __init__(self, *args, **kwargs):
519 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
519 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
520 self.init_prompt_toolkit_cli()
520 self.init_prompt_toolkit_cli()
521 self.init_term_title()
521 self.init_term_title()
522 self.keep_running = True
522 self.keep_running = True
523
523
524 self.debugger_history = InMemoryHistory()
524 self.debugger_history = InMemoryHistory()
525
525
526 def ask_exit(self):
526 def ask_exit(self):
527 self.keep_running = False
527 self.keep_running = False
528
528
529 rl_next_input = None
529 rl_next_input = None
530
530
531 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
531 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
532
532
533 if display_banner is not DISPLAY_BANNER_DEPRECATED:
533 if display_banner is not DISPLAY_BANNER_DEPRECATED:
534 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
534 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
535
535
536 self.keep_running = True
536 self.keep_running = True
537 while self.keep_running:
537 while self.keep_running:
538 print(self.separate_in, end='')
538 print(self.separate_in, end='')
539
539
540 try:
540 try:
541 code = self.prompt_for_code()
541 code = self.prompt_for_code()
542 except EOFError:
542 except EOFError:
543 if (not self.confirm_exit) \
543 if (not self.confirm_exit) \
544 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
544 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
545 self.ask_exit()
545 self.ask_exit()
546
546
547 else:
547 else:
548 if code:
548 if code:
549 self.run_cell(code, store_history=True)
549 self.run_cell(code, store_history=True)
550
550
551 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
551 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
552 # An extra layer of protection in case someone mashing Ctrl-C breaks
552 # An extra layer of protection in case someone mashing Ctrl-C breaks
553 # out of our internal code.
553 # out of our internal code.
554 if display_banner is not DISPLAY_BANNER_DEPRECATED:
554 if display_banner is not DISPLAY_BANNER_DEPRECATED:
555 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
555 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
556 while True:
556 while True:
557 try:
557 try:
558 self.interact()
558 self.interact()
559 break
559 break
560 except KeyboardInterrupt as e:
560 except KeyboardInterrupt as e:
561 print("\n%s escaped interact()\n" % type(e).__name__)
561 print("\n%s escaped interact()\n" % type(e).__name__)
562 finally:
562 finally:
563 # An interrupt during the eventloop will mess up the
563 # An interrupt during the eventloop will mess up the
564 # internal state of the prompt_toolkit library.
564 # internal state of the prompt_toolkit library.
565 # Stopping the eventloop fixes this, see
565 # Stopping the eventloop fixes this, see
566 # https://github.com/ipython/ipython/pull/9867
566 # https://github.com/ipython/ipython/pull/9867
567 if hasattr(self, '_eventloop'):
567 if hasattr(self, '_eventloop'):
568 self._eventloop.stop()
568 self._eventloop.stop()
569
569
570 self.restore_term_title()
570 self.restore_term_title()
571
571
572
572
573 _inputhook = None
573 _inputhook = None
574 def inputhook(self, context):
574 def inputhook(self, context):
575 if self._inputhook is not None:
575 if self._inputhook is not None:
576 self._inputhook(context)
576 self._inputhook(context)
577
577
578 active_eventloop = None
578 active_eventloop = None
579 def enable_gui(self, gui=None):
579 def enable_gui(self, gui=None):
580 if gui and (gui != 'inline') :
580 if gui and (gui != 'inline') :
581 self.active_eventloop, self._inputhook =\
581 self.active_eventloop, self._inputhook =\
582 get_inputhook_name_and_func(gui)
582 get_inputhook_name_and_func(gui)
583 else:
583 else:
584 self.active_eventloop = self._inputhook = None
584 self.active_eventloop = self._inputhook = None
585
585
586 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
586 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
587 # this inputhook.
587 # this inputhook.
588 if PTK3:
588 if PTK3:
589 import asyncio
589 import asyncio
590 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
590 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
591
591
592 if gui == 'asyncio':
592 if gui == 'asyncio':
593 # When we integrate the asyncio event loop, run the UI in the
593 # When we integrate the asyncio event loop, run the UI in the
594 # same event loop as the rest of the code. don't use an actual
594 # same event loop as the rest of the code. don't use an actual
595 # input hook. (Asyncio is not made for nesting event loops.)
595 # input hook. (Asyncio is not made for nesting event loops.)
596 self.pt_loop = asyncio.get_event_loop()
596 self.pt_loop = asyncio.get_event_loop()
597
597
598 elif self._inputhook:
598 elif self._inputhook:
599 # If an inputhook was set, create a new asyncio event loop with
599 # If an inputhook was set, create a new asyncio event loop with
600 # this inputhook for the prompt.
600 # this inputhook for the prompt.
601 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
601 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
602 else:
602 else:
603 # When there's no inputhook, run the prompt in a separate
603 # When there's no inputhook, run the prompt in a separate
604 # asyncio event loop.
604 # asyncio event loop.
605 self.pt_loop = asyncio.new_event_loop()
605 self.pt_loop = asyncio.new_event_loop()
606
606
607 # Run !system commands directly, not through pipes, so terminal programs
607 # Run !system commands directly, not through pipes, so terminal programs
608 # work correctly.
608 # work correctly.
609 system = InteractiveShell.system_raw
609 system = InteractiveShell.system_raw
610
610
611 def auto_rewrite_input(self, cmd):
611 def auto_rewrite_input(self, cmd):
612 """Overridden from the parent class to use fancy rewriting prompt"""
612 """Overridden from the parent class to use fancy rewriting prompt"""
613 if not self.show_rewritten_input:
613 if not self.show_rewritten_input:
614 return
614 return
615
615
616 tokens = self.prompts.rewrite_prompt_tokens()
616 tokens = self.prompts.rewrite_prompt_tokens()
617 if self.pt_app:
617 if self.pt_app:
618 print_formatted_text(PygmentsTokens(tokens), end='',
618 print_formatted_text(PygmentsTokens(tokens), end='',
619 style=self.pt_app.app.style)
619 style=self.pt_app.app.style)
620 print(cmd)
620 print(cmd)
621 else:
621 else:
622 prompt = ''.join(s for t, s in tokens)
622 prompt = ''.join(s for t, s in tokens)
623 print(prompt, cmd, sep='')
623 print(prompt, cmd, sep='')
624
624
625 _prompts_before = None
625 _prompts_before = None
626 def switch_doctest_mode(self, mode):
626 def switch_doctest_mode(self, mode):
627 """Switch prompts to classic for %doctest_mode"""
627 """Switch prompts to classic for %doctest_mode"""
628 if mode:
628 if mode:
629 self._prompts_before = self.prompts
629 self._prompts_before = self.prompts
630 self.prompts = ClassicPrompts(self)
630 self.prompts = ClassicPrompts(self)
631 elif self._prompts_before:
631 elif self._prompts_before:
632 self.prompts = self._prompts_before
632 self.prompts = self._prompts_before
633 self._prompts_before = None
633 self._prompts_before = None
634 # self._update_layout()
634 # self._update_layout()
635
635
636
636
637 InteractiveShellABC.register(TerminalInteractiveShell)
637 InteractiveShellABC.register(TerminalInteractiveShell)
638
638
639 if __name__ == '__main__':
639 if __name__ == '__main__':
640 TerminalInteractiveShell.instance().interact()
640 TerminalInteractiveShell.instance().interact()
General Comments 0
You need to be logged in to leave comments. Login now