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