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