##// END OF EJS Templates
added help line tointeractiveshell.py
michaelpacer -
Show More
@@ -1,452 +1,457 b''
1 1 """IPython terminal interface using prompt_toolkit"""
2 2 from __future__ import print_function
3 3
4 4 import os
5 5 import sys
6 6 from warnings import warn
7 7
8 8 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 9 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
10 10 from IPython.utils.terminal import toggle_set_term_title, set_term_title
11 11 from IPython.utils.process import abbrev_cwd
12 12 from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum
13 13
14 14 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
15 15 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
16 16 from prompt_toolkit.history import InMemoryHistory
17 17 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
18 18 from prompt_toolkit.interface import CommandLineInterface
19 19 from prompt_toolkit.key_binding.manager import KeyBindingManager
20 20 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
21 21 from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
22 22
23 23 from pygments.styles import get_style_by_name, get_all_styles
24 24 from pygments.token import Token
25 25
26 26 from .debugger import TerminalPdb, Pdb
27 27 from .magics import TerminalMagics
28 28 from .pt_inputhooks import get_inputhook_func
29 29 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
30 30 from .ptutils import IPythonPTCompleter, IPythonPTLexer
31 31 from .shortcuts import register_ipython_shortcuts
32 32
33 33 DISPLAY_BANNER_DEPRECATED = object()
34 34
35 35
36 36 from pygments.style import Style
37 37
38 38 class _NoStyle(Style): pass
39 39
40 40
41 41
42 42 _style_overrides_light_bg = {
43 43 Token.Prompt: '#0000ff',
44 44 Token.PromptNum: '#0000ee bold',
45 45 Token.OutPrompt: '#cc0000',
46 46 Token.OutPromptNum: '#bb0000 bold',
47 47 }
48 48
49 49 _style_overrides_linux = {
50 50 Token.Prompt: '#00cc00',
51 51 Token.PromptNum: '#00bb00 bold',
52 52 Token.OutPrompt: '#cc0000',
53 53 Token.OutPromptNum: '#bb0000 bold',
54 54 }
55 55
56 56
57 57
58 58 def get_default_editor():
59 59 try:
60 60 ed = os.environ['EDITOR']
61 61 if not PY3:
62 62 ed = ed.decode()
63 63 return ed
64 64 except KeyError:
65 65 pass
66 66 except UnicodeError:
67 67 warn("$EDITOR environment variable is not pure ASCII. Using platform "
68 68 "default editor.")
69 69
70 70 if os.name == 'posix':
71 71 return 'vi' # the only one guaranteed to be there!
72 72 else:
73 73 return 'notepad' # same in Windows!
74 74
75 75
76 76 if sys.stdin and sys.stdout and sys.stderr:
77 77 _is_tty = (sys.stdin.isatty()) and (sys.stdout.isatty()) and (sys.stderr.isatty())
78 78 else:
79 79 _is_tty = False
80 80
81 81
82 82 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
83 83
84 84 class TerminalInteractiveShell(InteractiveShell):
85 85 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
86 86 'to reserve for the completion menu'
87 87 ).tag(config=True)
88 88
89 89 def _space_for_menu_changed(self, old, new):
90 90 self._update_layout()
91 91
92 92 pt_cli = None
93 93 debugger_history = None
94 94 _pt_app = None
95 95
96 96 simple_prompt = Bool(_use_simple_prompt,
97 97 help="""Use `raw_input` for the REPL, without completion, multiline input, and prompt colors.
98 98
99 99 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
100 100 IPython own testing machinery, and emacs inferior-shell integration through elpy.
101 101
102 102 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
103 103 environment variable is set, or the current terminal is not a tty.
104 104
105 105 """
106 106 ).tag(config=True)
107 107
108 108 @property
109 109 def debugger_cls(self):
110 110 return Pdb if self.simple_prompt else TerminalPdb
111 111
112 112 confirm_exit = Bool(True,
113 113 help="""
114 114 Set to confirm when you try to exit IPython with an EOF (Control-D
115 115 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
116 116 you can force a direct exit without any confirmation.""",
117 117 ).tag(config=True)
118 118
119 119 editing_mode = Unicode('emacs',
120 120 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
121 121 ).tag(config=True)
122 122
123 123 mouse_support = Bool(False,
124 124 help="Enable mouse support in the prompt"
125 125 ).tag(config=True)
126 126
127 127 highlighting_style = Unicode('legacy',
128 128 help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles())
129 129 ).tag(config=True)
130 130
131 131
132 132 @observe('highlighting_style')
133 133 @observe('colors')
134 134 def _highlighting_style_changed(self, change):
135 135 self.refresh_style()
136 136
137 137 def refresh_style(self):
138 138 self._style = self._make_style_from_name(self.highlighting_style)
139 139
140 140
141 141 highlighting_style_overrides = Dict(
142 142 help="Override highlighting format for specific tokens"
143 143 ).tag(config=True)
144 144
145 145 true_color = Bool(False,
146 146 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
147 147 "If your terminal supports true color, the following command "
148 148 "should print 'TRUECOLOR' in orange: "
149 149 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
150 150 ).tag(config=True)
151 151
152 152 editor = Unicode(get_default_editor(),
153 153 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
154 154 ).tag(config=True)
155 155
156 156 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
157 157
158 158 prompts = Instance(Prompts)
159 159
160 160 @default('prompts')
161 161 def _prompts_default(self):
162 162 return self.prompts_class(self)
163 163
164 164 @observe('prompts')
165 165 def _(self, change):
166 166 self._update_layout()
167 167
168 168 @default('displayhook_class')
169 169 def _displayhook_class_default(self):
170 170 return RichPromptDisplayHook
171 171
172 172 term_title = Bool(True,
173 173 help="Automatically set the terminal title"
174 174 ).tag(config=True)
175 175
176 display_completions = Enum(('column', 'multicolumn','readlinelike'), default_value='multicolumn').tag(config=True)
176 display_completions = Enum(('column', 'multicolumn','readlinelike'),
177 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and"
178 "'readlinelike'. These options are for `prompt_toolkit`, see `prompt_toolkit`"
179 "documentation for more information."
180 ),
181 default_value='multicolumn').tag(config=True)
177 182
178 183 highlight_matching_brackets = Bool(True,
179 184 help="Highlight matching brackets .",
180 185 ).tag(config=True)
181 186
182 187 @observe('term_title')
183 188 def init_term_title(self, change=None):
184 189 # Enable or disable the terminal title.
185 190 if self.term_title:
186 191 toggle_set_term_title(True)
187 192 set_term_title('IPython: ' + abbrev_cwd())
188 193 else:
189 194 toggle_set_term_title(False)
190 195
191 196 def init_display_formatter(self):
192 197 super(TerminalInteractiveShell, self).init_display_formatter()
193 198 # terminal only supports plain text
194 199 self.display_formatter.active_types = ['text/plain']
195 200
196 201 def init_prompt_toolkit_cli(self):
197 202 if self.simple_prompt:
198 203 # Fall back to plain non-interactive output for tests.
199 204 # This is very limited, and only accepts a single line.
200 205 def prompt():
201 206 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
202 207 self.prompt_for_code = prompt
203 208 return
204 209
205 210 # Set up keyboard shortcuts
206 211 kbmanager = KeyBindingManager.for_prompt()
207 212 register_ipython_shortcuts(kbmanager.registry, self)
208 213
209 214 # Pre-populate history from IPython's history database
210 215 history = InMemoryHistory()
211 216 last_cell = u""
212 217 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
213 218 include_latest=True):
214 219 # Ignore blank lines and consecutive duplicates
215 220 cell = cell.rstrip()
216 221 if cell and (cell != last_cell):
217 222 history.append(cell)
218 223
219 224 self._style = self._make_style_from_name(self.highlighting_style)
220 225 style = DynamicStyle(lambda: self._style)
221 226
222 227 editing_mode = getattr(EditingMode, self.editing_mode.upper())
223 228
224 229 self._pt_app = create_prompt_application(
225 230 editing_mode=editing_mode,
226 231 key_bindings_registry=kbmanager.registry,
227 232 history=history,
228 233 completer=IPythonPTCompleter(self.Completer),
229 234 enable_history_search=True,
230 235 style=style,
231 236 mouse_support=self.mouse_support,
232 237 **self._layout_options()
233 238 )
234 239 self._eventloop = create_eventloop(self.inputhook)
235 240 self.pt_cli = CommandLineInterface(
236 241 self._pt_app, eventloop=self._eventloop,
237 242 output=create_output(true_color=self.true_color))
238 243
239 244 def _make_style_from_name(self, name):
240 245 """
241 246 Small wrapper that make an IPython compatible style from a style name
242 247
243 248 We need that to add style for prompt ... etc.
244 249 """
245 250 style_overrides = {}
246 251 if name == 'legacy':
247 252 legacy = self.colors.lower()
248 253 if legacy == 'linux':
249 254 style_cls = get_style_by_name('monokai')
250 255 style_overrides = _style_overrides_linux
251 256 elif legacy == 'lightbg':
252 257 style_overrides = _style_overrides_light_bg
253 258 style_cls = get_style_by_name('pastie')
254 259 elif legacy == 'neutral':
255 260 # The default theme needs to be visible on both a dark background
256 261 # and a light background, because we can't tell what the terminal
257 262 # looks like. These tweaks to the default theme help with that.
258 263 style_cls = get_style_by_name('default')
259 264 style_overrides.update({
260 265 Token.Number: '#007700',
261 266 Token.Operator: 'noinherit',
262 267 Token.String: '#BB6622',
263 268 Token.Name.Function: '#2080D0',
264 269 Token.Name.Class: 'bold #2080D0',
265 270 Token.Name.Namespace: 'bold #2080D0',
266 271 Token.Prompt: '#009900',
267 272 Token.PromptNum: '#00ff00 bold',
268 273 Token.OutPrompt: '#990000',
269 274 Token.OutPromptNum: '#ff0000 bold',
270 275 })
271 276 elif legacy =='nocolor':
272 277 style_cls=_NoStyle
273 278 style_overrides = {}
274 279 else :
275 280 raise ValueError('Got unknown colors: ', legacy)
276 281 else :
277 282 style_cls = get_style_by_name(name)
278 283 style_overrides = {
279 284 Token.Prompt: '#009900',
280 285 Token.PromptNum: '#00ff00 bold',
281 286 Token.OutPrompt: '#990000',
282 287 Token.OutPromptNum: '#ff0000 bold',
283 288 }
284 289 style_overrides.update(self.highlighting_style_overrides)
285 290 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
286 291 style_dict=style_overrides)
287 292
288 293 return style
289 294
290 295 def _layout_options(self):
291 296 """
292 297 Return the current layout option for the current Terminal InteractiveShell
293 298 """
294 299 return {
295 300 'lexer':IPythonPTLexer(),
296 301 'reserve_space_for_menu':self.space_for_menu,
297 302 'get_prompt_tokens':self.prompts.in_prompt_tokens,
298 303 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
299 304 'multiline':True,
300 305 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
301 306
302 307 # Highlight matching brackets, but only when this setting is
303 308 # enabled, and only when the DEFAULT_BUFFER has the focus.
304 309 'extra_input_processors': [ConditionalProcessor(
305 310 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
306 311 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
307 312 Condition(lambda cli: self.highlight_matching_brackets))],
308 313 }
309 314
310 315 def _update_layout(self):
311 316 """
312 317 Ask for a re computation of the application layout, if for example ,
313 318 some configuration options have changed.
314 319 """
315 320 if self._pt_app:
316 321 self._pt_app.layout = create_prompt_layout(**self._layout_options())
317 322
318 323 def prompt_for_code(self):
319 324 document = self.pt_cli.run(
320 325 pre_run=self.pre_prompt, reset_current_buffer=True)
321 326 return document.text
322 327
323 328 def init_io(self):
324 329 if sys.platform not in {'win32', 'cli'}:
325 330 return
326 331
327 332 import win_unicode_console
328 333 import colorama
329 334
330 335 win_unicode_console.enable()
331 336 colorama.init()
332 337
333 338 # For some reason we make these wrappers around stdout/stderr.
334 339 # For now, we need to reset them so all output gets coloured.
335 340 # https://github.com/ipython/ipython/issues/8669
336 341 from IPython.utils import io
337 342 io.stdout = io.IOStream(sys.stdout)
338 343 io.stderr = io.IOStream(sys.stderr)
339 344
340 345 def init_magics(self):
341 346 super(TerminalInteractiveShell, self).init_magics()
342 347 self.register_magics(TerminalMagics)
343 348
344 349 def init_alias(self):
345 350 # The parent class defines aliases that can be safely used with any
346 351 # frontend.
347 352 super(TerminalInteractiveShell, self).init_alias()
348 353
349 354 # Now define aliases that only make sense on the terminal, because they
350 355 # need direct access to the console in a way that we can't emulate in
351 356 # GUI or web frontend
352 357 if os.name == 'posix':
353 358 for cmd in ['clear', 'more', 'less', 'man']:
354 359 self.alias_manager.soft_define_alias(cmd, cmd)
355 360
356 361
357 362 def __init__(self, *args, **kwargs):
358 363 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
359 364 self.init_prompt_toolkit_cli()
360 365 self.init_term_title()
361 366 self.keep_running = True
362 367
363 368 self.debugger_history = InMemoryHistory()
364 369
365 370 def ask_exit(self):
366 371 self.keep_running = False
367 372
368 373 rl_next_input = None
369 374
370 375 def pre_prompt(self):
371 376 if self.rl_next_input:
372 377 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
373 378 self.rl_next_input = None
374 379
375 380 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
376 381
377 382 if display_banner is not DISPLAY_BANNER_DEPRECATED:
378 383 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
379 384
380 385 while self.keep_running:
381 386 print(self.separate_in, end='')
382 387
383 388 try:
384 389 code = self.prompt_for_code()
385 390 except EOFError:
386 391 if (not self.confirm_exit) \
387 392 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
388 393 self.ask_exit()
389 394
390 395 else:
391 396 if code:
392 397 self.run_cell(code, store_history=True)
393 398
394 399 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
395 400 # An extra layer of protection in case someone mashing Ctrl-C breaks
396 401 # out of our internal code.
397 402 if display_banner is not DISPLAY_BANNER_DEPRECATED:
398 403 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
399 404 while True:
400 405 try:
401 406 self.interact()
402 407 break
403 408 except KeyboardInterrupt:
404 409 print("\nKeyboardInterrupt escaped interact()\n")
405 410
406 411 if hasattr(self, '_eventloop'):
407 412 self._eventloop.close()
408 413
409 414 _inputhook = None
410 415 def inputhook(self, context):
411 416 if self._inputhook is not None:
412 417 self._inputhook(context)
413 418
414 419 def enable_gui(self, gui=None):
415 420 if gui:
416 421 self._inputhook = get_inputhook_func(gui)
417 422 else:
418 423 self._inputhook = None
419 424
420 425 # Run !system commands directly, not through pipes, so terminal programs
421 426 # work correctly.
422 427 system = InteractiveShell.system_raw
423 428
424 429 def auto_rewrite_input(self, cmd):
425 430 """Overridden from the parent class to use fancy rewriting prompt"""
426 431 if not self.show_rewritten_input:
427 432 return
428 433
429 434 tokens = self.prompts.rewrite_prompt_tokens()
430 435 if self.pt_cli:
431 436 self.pt_cli.print_tokens(tokens)
432 437 print(cmd)
433 438 else:
434 439 prompt = ''.join(s for t, s in tokens)
435 440 print(prompt, cmd, sep='')
436 441
437 442 _prompts_before = None
438 443 def switch_doctest_mode(self, mode):
439 444 """Switch prompts to classic for %doctest_mode"""
440 445 if mode:
441 446 self._prompts_before = self.prompts
442 447 self.prompts = ClassicPrompts(self)
443 448 elif self._prompts_before:
444 449 self.prompts = self._prompts_before
445 450 self._prompts_before = None
446 451 self._update_layout()
447 452
448 453
449 454 InteractiveShellABC.register(TerminalInteractiveShell)
450 455
451 456 if __name__ == '__main__':
452 457 TerminalInteractiveShell.instance().interact()
General Comments 0
You need to be logged in to leave comments. Login now