Show More
@@ -1,289 +1,296 b'' | |||
|
1 | 1 | """IPython terminal interface using prompt_toolkit in place of readline""" |
|
2 | 2 | from __future__ import print_function |
|
3 | 3 | |
|
4 | 4 | import os |
|
5 | 5 | import sys |
|
6 | import signal | |
|
6 | 7 | |
|
7 | 8 | from IPython.core.interactiveshell import InteractiveShell |
|
8 | 9 | from IPython.utils.py3compat import PY3, cast_unicode_py2, input |
|
9 | 10 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
10 | 11 | from IPython.utils.process import abbrev_cwd |
|
11 | 12 | from traitlets import Bool, Unicode, Dict |
|
12 | 13 | |
|
13 | 14 | from prompt_toolkit.completion import Completer, Completion |
|
14 | 15 | from prompt_toolkit.enums import DEFAULT_BUFFER |
|
15 | 16 | from prompt_toolkit.filters import HasFocus, HasSelection, Condition |
|
16 | 17 | from prompt_toolkit.history import InMemoryHistory |
|
17 | 18 | from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop |
|
18 | 19 | from prompt_toolkit.interface import CommandLineInterface |
|
19 | 20 | from prompt_toolkit.key_binding.manager import KeyBindingManager |
|
20 | 21 | from prompt_toolkit.key_binding.vi_state import InputMode |
|
21 | 22 | from prompt_toolkit.key_binding.bindings.vi import ViStateFilter |
|
22 | 23 | from prompt_toolkit.keys import Keys |
|
23 | 24 | from prompt_toolkit.layout.lexers import PygmentsLexer |
|
24 | 25 | from prompt_toolkit.styles import PygmentsStyle |
|
25 | 26 | |
|
26 | 27 | from pygments.styles import get_style_by_name |
|
27 | 28 | from pygments.lexers import Python3Lexer, PythonLexer |
|
28 | 29 | from pygments.token import Token |
|
29 | 30 | |
|
30 | 31 | from .pt_inputhooks import get_inputhook_func |
|
31 | 32 | from .interactiveshell import get_default_editor, TerminalMagics |
|
32 | 33 | |
|
33 | 34 | |
|
34 | 35 | |
|
35 | 36 | class IPythonPTCompleter(Completer): |
|
36 | 37 | """Adaptor to provide IPython completions to prompt_toolkit""" |
|
37 | 38 | def __init__(self, ipy_completer): |
|
38 | 39 | self.ipy_completer = ipy_completer |
|
39 | 40 | |
|
40 | 41 | def get_completions(self, document, complete_event): |
|
41 | 42 | if not document.current_line.strip(): |
|
42 | 43 | return |
|
43 | 44 | |
|
44 | 45 | used, matches = self.ipy_completer.complete( |
|
45 | 46 | line_buffer=document.current_line, |
|
46 | 47 | cursor_pos=document.cursor_position_col |
|
47 | 48 | ) |
|
48 | 49 | start_pos = -len(used) |
|
49 | 50 | for m in matches: |
|
50 | 51 | yield Completion(m, start_position=start_pos) |
|
51 | 52 | |
|
52 | 53 | class TerminalInteractiveShell(InteractiveShell): |
|
53 | 54 | colors_force = True |
|
54 | 55 | |
|
55 | 56 | pt_cli = None |
|
56 | 57 | |
|
57 | 58 | vi_mode = Bool(False, config=True, |
|
58 | 59 | help="Use vi style keybindings at the prompt", |
|
59 | 60 | ) |
|
60 | 61 | |
|
61 | 62 | mouse_support = Bool(False, config=True, |
|
62 | 63 | help="Enable mouse support in the prompt" |
|
63 | 64 | ) |
|
64 | 65 | |
|
65 | 66 | highlighting_style = Unicode('', config=True, |
|
66 | 67 | help="The name of a Pygments style to use for syntax highlighting" |
|
67 | 68 | ) |
|
68 | 69 | |
|
69 | 70 | highlighting_style_overrides = Dict(config=True, |
|
70 | 71 | help="Override highlighting format for specific tokens" |
|
71 | 72 | ) |
|
72 | 73 | |
|
73 | 74 | editor = Unicode(get_default_editor(), config=True, |
|
74 | 75 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
75 | 76 | ) |
|
76 | 77 | |
|
77 | 78 | term_title = Bool(True, config=True, |
|
78 | 79 | help="Automatically set the terminal title" |
|
79 | 80 | ) |
|
80 | 81 | def _term_title_changed(self, name, new_value): |
|
81 | 82 | self.init_term_title() |
|
82 | 83 | |
|
83 | 84 | def init_term_title(self): |
|
84 | 85 | # Enable or disable the terminal title. |
|
85 | 86 | if self.term_title: |
|
86 | 87 | toggle_set_term_title(True) |
|
87 | 88 | set_term_title('IPython: ' + abbrev_cwd()) |
|
88 | 89 | else: |
|
89 | 90 | toggle_set_term_title(False) |
|
90 | 91 | |
|
91 | 92 | def get_prompt_tokens(self, cli): |
|
92 | 93 | return [ |
|
93 | 94 | (Token.Prompt, 'In ['), |
|
94 | 95 | (Token.PromptNum, str(self.execution_count)), |
|
95 | 96 | (Token.Prompt, ']: '), |
|
96 | 97 | ] |
|
97 | 98 | |
|
98 | 99 | def get_continuation_tokens(self, cli, width): |
|
99 | 100 | return [ |
|
100 | 101 | (Token.Prompt, (' ' * (width - 5)) + '...: '), |
|
101 | 102 | ] |
|
102 | 103 | |
|
103 | 104 | def init_prompt_toolkit_cli(self): |
|
104 | 105 | if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty(): |
|
105 | 106 | # Fall back to plain non-interactive output for tests. |
|
106 | 107 | # This is very limited, and only accepts a single line. |
|
107 | 108 | def prompt(): |
|
108 | 109 | return cast_unicode_py2(input('In [%d]: ' % self.execution_count)) |
|
109 | 110 | self.prompt_for_code = prompt |
|
110 | 111 | return |
|
111 | 112 | |
|
112 | 113 | kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode) |
|
113 | 114 | insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT) |
|
114 | 115 | # Ctrl+J == Enter, seemingly |
|
115 | 116 | @kbmanager.registry.add_binding(Keys.ControlJ, |
|
116 | 117 | filter=(HasFocus(DEFAULT_BUFFER) |
|
117 | 118 | & ~HasSelection() |
|
118 | 119 | & insert_mode |
|
119 | 120 | )) |
|
120 | 121 | def _(event): |
|
121 | 122 | b = event.current_buffer |
|
122 | 123 | d = b.document |
|
123 | 124 | if not (d.on_last_line or d.cursor_position_row >= d.line_count |
|
124 | 125 | - d.empty_line_count_at_the_end()): |
|
125 | 126 | b.newline() |
|
126 | 127 | return |
|
127 | 128 | |
|
128 | 129 | status, indent = self.input_splitter.check_complete(d.text) |
|
129 | 130 | |
|
130 | 131 | if (status != 'incomplete') and b.accept_action.is_returnable: |
|
131 | 132 | b.accept_action.validate_and_handle(event.cli, b) |
|
132 | 133 | else: |
|
133 | 134 | b.insert_text('\n' + (' ' * (indent or 0))) |
|
134 | 135 | |
|
135 | 136 | @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) |
|
136 | 137 | def _(event): |
|
137 | 138 | event.current_buffer.reset() |
|
138 | 139 | |
|
140 | supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) | |
|
141 | ||
|
142 | @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend) | |
|
143 | def _(event): | |
|
144 | event.cli.suspend_to_background() | |
|
145 | ||
|
139 | 146 | @Condition |
|
140 | 147 | def cursor_in_leading_ws(cli): |
|
141 | 148 | before = cli.application.buffer.document.current_line_before_cursor |
|
142 | 149 | return (not before) or before.isspace() |
|
143 | 150 | |
|
144 | 151 | # Ctrl+I == Tab |
|
145 | 152 | @kbmanager.registry.add_binding(Keys.ControlI, |
|
146 | 153 | filter=(HasFocus(DEFAULT_BUFFER) |
|
147 | 154 | & ~HasSelection() |
|
148 | 155 | & insert_mode |
|
149 | 156 | & cursor_in_leading_ws |
|
150 | 157 | )) |
|
151 | 158 | def _(event): |
|
152 | 159 | event.current_buffer.insert_text(' ' * 4) |
|
153 | 160 | |
|
154 | 161 | # Pre-populate history from IPython's history database |
|
155 | 162 | history = InMemoryHistory() |
|
156 | 163 | last_cell = u"" |
|
157 | 164 | for _, _, cell in self.history_manager.get_tail(self.history_load_length, |
|
158 | 165 | include_latest=True): |
|
159 | 166 | # Ignore blank lines and consecutive duplicates |
|
160 | 167 | cell = cell.rstrip() |
|
161 | 168 | if cell and (cell != last_cell): |
|
162 | 169 | history.append(cell) |
|
163 | 170 | |
|
164 | 171 | style_overrides = { |
|
165 | 172 | Token.Prompt: '#009900', |
|
166 | 173 | Token.PromptNum: '#00ff00 bold', |
|
167 | 174 | } |
|
168 | 175 | if self.highlighting_style: |
|
169 | 176 | style_cls = get_style_by_name(self.highlighting_style) |
|
170 | 177 | else: |
|
171 | 178 | style_cls = get_style_by_name('default') |
|
172 | 179 | # The default theme needs to be visible on both a dark background |
|
173 | 180 | # and a light background, because we can't tell what the terminal |
|
174 | 181 | # looks like. These tweaks to the default theme help with that. |
|
175 | 182 | style_overrides.update({ |
|
176 | 183 | Token.Number: '#007700', |
|
177 | 184 | Token.Operator: 'noinherit', |
|
178 | 185 | Token.String: '#BB6622', |
|
179 | 186 | Token.Name.Function: '#2080D0', |
|
180 | 187 | Token.Name.Class: 'bold #2080D0', |
|
181 | 188 | Token.Name.Namespace: 'bold #2080D0', |
|
182 | 189 | }) |
|
183 | 190 | style_overrides.update(self.highlighting_style_overrides) |
|
184 | 191 | style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, |
|
185 | 192 | style_dict=style_overrides) |
|
186 | 193 | |
|
187 | 194 | app = create_prompt_application(multiline=True, |
|
188 | 195 | lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer), |
|
189 | 196 | get_prompt_tokens=self.get_prompt_tokens, |
|
190 | 197 | get_continuation_tokens=self.get_continuation_tokens, |
|
191 | 198 | key_bindings_registry=kbmanager.registry, |
|
192 | 199 | history=history, |
|
193 | 200 | completer=IPythonPTCompleter(self.Completer), |
|
194 | 201 | enable_history_search=True, |
|
195 | 202 | style=style, |
|
196 | 203 | mouse_support=self.mouse_support, |
|
197 | 204 | ) |
|
198 | 205 | |
|
199 | 206 | self.pt_cli = CommandLineInterface(app, |
|
200 | 207 | eventloop=create_eventloop(self.inputhook)) |
|
201 | 208 | |
|
202 | 209 | def prompt_for_code(self): |
|
203 | 210 | document = self.pt_cli.run(pre_run=self.pre_prompt) |
|
204 | 211 | return document.text |
|
205 | 212 | |
|
206 | 213 | def init_io(self): |
|
207 | 214 | if sys.platform not in {'win32', 'cli'}: |
|
208 | 215 | return |
|
209 | 216 | |
|
210 | 217 | import colorama |
|
211 | 218 | colorama.init() |
|
212 | 219 | |
|
213 | 220 | # For some reason we make these wrappers around stdout/stderr. |
|
214 | 221 | # For now, we need to reset them so all output gets coloured. |
|
215 | 222 | # https://github.com/ipython/ipython/issues/8669 |
|
216 | 223 | from IPython.utils import io |
|
217 | 224 | io.stdout = io.IOStream(sys.stdout) |
|
218 | 225 | io.stderr = io.IOStream(sys.stderr) |
|
219 | 226 | |
|
220 | 227 | def init_magics(self): |
|
221 | 228 | super(TerminalInteractiveShell, self).init_magics() |
|
222 | 229 | self.register_magics(TerminalMagics) |
|
223 | 230 | |
|
224 | 231 | def init_alias(self): |
|
225 | 232 | # The parent class defines aliases that can be safely used with any |
|
226 | 233 | # frontend. |
|
227 | 234 | super(TerminalInteractiveShell, self).init_alias() |
|
228 | 235 | |
|
229 | 236 | # Now define aliases that only make sense on the terminal, because they |
|
230 | 237 | # need direct access to the console in a way that we can't emulate in |
|
231 | 238 | # GUI or web frontend |
|
232 | 239 | if os.name == 'posix': |
|
233 | 240 | for cmd in ['clear', 'more', 'less', 'man']: |
|
234 | 241 | self.alias_manager.soft_define_alias(cmd, cmd) |
|
235 | 242 | |
|
236 | 243 | |
|
237 | 244 | def __init__(self, *args, **kwargs): |
|
238 | 245 | super(TerminalInteractiveShell, self).__init__(*args, **kwargs) |
|
239 | 246 | self.init_prompt_toolkit_cli() |
|
240 | 247 | self.init_term_title() |
|
241 | 248 | self.keep_running = True |
|
242 | 249 | |
|
243 | 250 | def ask_exit(self): |
|
244 | 251 | self.keep_running = False |
|
245 | 252 | |
|
246 | 253 | rl_next_input = None |
|
247 | 254 | |
|
248 | 255 | def pre_prompt(self): |
|
249 | 256 | if self.rl_next_input: |
|
250 | 257 | self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input) |
|
251 | 258 | self.rl_next_input = None |
|
252 | 259 | |
|
253 | 260 | def interact(self): |
|
254 | 261 | while self.keep_running: |
|
255 | 262 | print(self.separate_in, end='') |
|
256 | 263 | |
|
257 | 264 | try: |
|
258 | 265 | code = self.prompt_for_code() |
|
259 | 266 | except EOFError: |
|
260 | 267 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): |
|
261 | 268 | self.ask_exit() |
|
262 | 269 | |
|
263 | 270 | else: |
|
264 | 271 | if code: |
|
265 | 272 | self.run_cell(code, store_history=True) |
|
266 | 273 | |
|
267 | 274 | def mainloop(self): |
|
268 | 275 | # An extra layer of protection in case someone mashing Ctrl-C breaks |
|
269 | 276 | # out of our internal code. |
|
270 | 277 | while True: |
|
271 | 278 | try: |
|
272 | 279 | self.interact() |
|
273 | 280 | break |
|
274 | 281 | except KeyboardInterrupt: |
|
275 | 282 | print("\nKeyboardInterrupt escaped interact()\n") |
|
276 | 283 | |
|
277 | 284 | _inputhook = None |
|
278 | 285 | def inputhook(self, context): |
|
279 | 286 | if self._inputhook is not None: |
|
280 | 287 | self._inputhook(context) |
|
281 | 288 | |
|
282 | 289 | def enable_gui(self, gui=None): |
|
283 | 290 | if gui: |
|
284 | 291 | self._inputhook = get_inputhook_func(gui) |
|
285 | 292 | else: |
|
286 | 293 | self._inputhook = None |
|
287 | 294 | |
|
288 | 295 | if __name__ == '__main__': |
|
289 | 296 | TerminalInteractiveShell.instance().interact() |
General Comments 0
You need to be logged in to leave comments.
Login now