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