##// END OF EJS Templates
Merge branch 'master' into fix-rm-harcoded-colors
Matthias Bussonnier -
r25902:21ac5592 merge
parent child Browse files
Show More
@@ -1,802 +1,809 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 https://docs.python.org/2/license.html
16 https://docs.python.org/2/license.html
17 """
17 """
18
18
19 #*****************************************************************************
19 #*****************************************************************************
20 #
20 #
21 # This file is licensed under the PSF license.
21 # This file is licensed under the PSF license.
22 #
22 #
23 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2001 Python Software Foundation, www.python.org
24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
25 #
25 #
26 #
26 #
27 #*****************************************************************************
27 #*****************************************************************************
28
28
29 import bdb
29 import bdb
30 import functools
30 import functools
31 import inspect
31 import inspect
32 import linecache
32 import linecache
33 import sys
33 import sys
34 import warnings
34 import warnings
35 import re
35 import re
36
36
37 from IPython import get_ipython
37 from IPython import get_ipython
38 from IPython.utils import PyColorize
38 from IPython.utils import PyColorize
39 from IPython.utils import coloransi, py3compat
39 from IPython.utils import coloransi, py3compat
40 from IPython.core.excolors import exception_colors
40 from IPython.core.excolors import exception_colors
41 from IPython.testing.skipdoctest import skip_doctest
41 from IPython.testing.skipdoctest import skip_doctest
42
42
43
43
44 prompt = 'ipdb> '
44 prompt = 'ipdb> '
45
45
46 #We have to check this directly from sys.argv, config struct not yet available
46 #We have to check this directly from sys.argv, config struct not yet available
47 from pdb import Pdb as OldPdb
47 from pdb import Pdb as OldPdb
48
48
49 # Allow the set_trace code to operate outside of an ipython instance, even if
49 # Allow the set_trace code to operate outside of an ipython instance, even if
50 # it does so with some limitations. The rest of this support is implemented in
50 # it does so with some limitations. The rest of this support is implemented in
51 # the Tracer constructor.
51 # the Tracer constructor.
52
52
53 def make_arrow(pad):
53 def make_arrow(pad):
54 """generate the leading arrow in front of traceback or debugger"""
54 """generate the leading arrow in front of traceback or debugger"""
55 if pad >= 2:
55 if pad >= 2:
56 return '-'*(pad-2) + '> '
56 return '-'*(pad-2) + '> '
57 elif pad == 1:
57 elif pad == 1:
58 return '>'
58 return '>'
59 return ''
59 return ''
60
60
61
61
62 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
62 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
63 """Exception hook which handles `BdbQuit` exceptions.
63 """Exception hook which handles `BdbQuit` exceptions.
64
64
65 All other exceptions are processed using the `excepthook`
65 All other exceptions are processed using the `excepthook`
66 parameter.
66 parameter.
67 """
67 """
68 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
68 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
69 DeprecationWarning, stacklevel=2)
69 DeprecationWarning, stacklevel=2)
70 if et==bdb.BdbQuit:
70 if et==bdb.BdbQuit:
71 print('Exiting Debugger.')
71 print('Exiting Debugger.')
72 elif excepthook is not None:
72 elif excepthook is not None:
73 excepthook(et, ev, tb)
73 excepthook(et, ev, tb)
74 else:
74 else:
75 # Backwards compatibility. Raise deprecation warning?
75 # Backwards compatibility. Raise deprecation warning?
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
77
77
78
78
79 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
79 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
80 warnings.warn(
80 warnings.warn(
81 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
81 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
82 DeprecationWarning, stacklevel=2)
82 DeprecationWarning, stacklevel=2)
83 print('Exiting Debugger.')
83 print('Exiting Debugger.')
84
84
85
85
86 class Tracer(object):
86 class Tracer(object):
87 """
87 """
88 DEPRECATED
88 DEPRECATED
89
89
90 Class for local debugging, similar to pdb.set_trace.
90 Class for local debugging, similar to pdb.set_trace.
91
91
92 Instances of this class, when called, behave like pdb.set_trace, but
92 Instances of this class, when called, behave like pdb.set_trace, but
93 providing IPython's enhanced capabilities.
93 providing IPython's enhanced capabilities.
94
94
95 This is implemented as a class which must be initialized in your own code
95 This is implemented as a class which must be initialized in your own code
96 and not as a standalone function because we need to detect at runtime
96 and not as a standalone function because we need to detect at runtime
97 whether IPython is already active or not. That detection is done in the
97 whether IPython is already active or not. That detection is done in the
98 constructor, ensuring that this code plays nicely with a running IPython,
98 constructor, ensuring that this code plays nicely with a running IPython,
99 while functioning acceptably (though with limitations) if outside of it.
99 while functioning acceptably (though with limitations) if outside of it.
100 """
100 """
101
101
102 @skip_doctest
102 @skip_doctest
103 def __init__(self, colors=None):
103 def __init__(self, colors=None):
104 """
104 """
105 DEPRECATED
105 DEPRECATED
106
106
107 Create a local debugger instance.
107 Create a local debugger instance.
108
108
109 Parameters
109 Parameters
110 ----------
110 ----------
111
111
112 colors : str, optional
112 colors : str, optional
113 The name of the color scheme to use, it must be one of IPython's
113 The name of the color scheme to use, it must be one of IPython's
114 valid color schemes. If not given, the function will default to
114 valid color schemes. If not given, the function will default to
115 the current IPython scheme when running inside IPython, and to
115 the current IPython scheme when running inside IPython, and to
116 'NoColor' otherwise.
116 'NoColor' otherwise.
117
117
118 Examples
118 Examples
119 --------
119 --------
120 ::
120 ::
121
121
122 from IPython.core.debugger import Tracer; debug_here = Tracer()
122 from IPython.core.debugger import Tracer; debug_here = Tracer()
123
123
124 Later in your code::
124 Later in your code::
125
125
126 debug_here() # -> will open up the debugger at that point.
126 debug_here() # -> will open up the debugger at that point.
127
127
128 Once the debugger activates, you can use all of its regular commands to
128 Once the debugger activates, you can use all of its regular commands to
129 step through code, set breakpoints, etc. See the pdb documentation
129 step through code, set breakpoints, etc. See the pdb documentation
130 from the Python standard library for usage details.
130 from the Python standard library for usage details.
131 """
131 """
132 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
132 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
133 "`IPython.core.debugger.Pdb.set_trace()`",
133 "`IPython.core.debugger.Pdb.set_trace()`",
134 DeprecationWarning, stacklevel=2)
134 DeprecationWarning, stacklevel=2)
135
135
136 ip = get_ipython()
136 ip = get_ipython()
137 if ip is None:
137 if ip is None:
138 # Outside of ipython, we set our own exception hook manually
138 # Outside of ipython, we set our own exception hook manually
139 sys.excepthook = functools.partial(BdbQuit_excepthook,
139 sys.excepthook = functools.partial(BdbQuit_excepthook,
140 excepthook=sys.excepthook)
140 excepthook=sys.excepthook)
141 def_colors = 'NoColor'
141 def_colors = 'NoColor'
142 else:
142 else:
143 # In ipython, we use its custom exception handler mechanism
143 # In ipython, we use its custom exception handler mechanism
144 def_colors = ip.colors
144 def_colors = ip.colors
145 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
145 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
146
146
147 if colors is None:
147 if colors is None:
148 colors = def_colors
148 colors = def_colors
149
149
150 # The stdlib debugger internally uses a modified repr from the `repr`
150 # The stdlib debugger internally uses a modified repr from the `repr`
151 # module, that limits the length of printed strings to a hardcoded
151 # module, that limits the length of printed strings to a hardcoded
152 # limit of 30 characters. That much trimming is too aggressive, let's
152 # limit of 30 characters. That much trimming is too aggressive, let's
153 # at least raise that limit to 80 chars, which should be enough for
153 # at least raise that limit to 80 chars, which should be enough for
154 # most interactive uses.
154 # most interactive uses.
155 try:
155 try:
156 from reprlib import aRepr
156 from reprlib import aRepr
157 aRepr.maxstring = 80
157 aRepr.maxstring = 80
158 except:
158 except:
159 # This is only a user-facing convenience, so any error we encounter
159 # This is only a user-facing convenience, so any error we encounter
160 # here can be warned about but can be otherwise ignored. These
160 # here can be warned about but can be otherwise ignored. These
161 # printouts will tell us about problems if this API changes
161 # printouts will tell us about problems if this API changes
162 import traceback
162 import traceback
163 traceback.print_exc()
163 traceback.print_exc()
164
164
165 self.debugger = Pdb(colors)
165 self.debugger = Pdb(colors)
166
166
167 def __call__(self):
167 def __call__(self):
168 """Starts an interactive debugger at the point where called.
168 """Starts an interactive debugger at the point where called.
169
169
170 This is similar to the pdb.set_trace() function from the std lib, but
170 This is similar to the pdb.set_trace() function from the std lib, but
171 using IPython's enhanced debugger."""
171 using IPython's enhanced debugger."""
172
172
173 self.debugger.set_trace(sys._getframe().f_back)
173 self.debugger.set_trace(sys._getframe().f_back)
174
174
175
175
176 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
176 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
177
177
178
178
179 def strip_indentation(multiline_string):
179 def strip_indentation(multiline_string):
180 return RGX_EXTRA_INDENT.sub('', multiline_string)
180 return RGX_EXTRA_INDENT.sub('', multiline_string)
181
181
182
182
183 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
183 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
184 """Make new_fn have old_fn's doc string. This is particularly useful
184 """Make new_fn have old_fn's doc string. This is particularly useful
185 for the ``do_...`` commands that hook into the help system.
185 for the ``do_...`` commands that hook into the help system.
186 Adapted from from a comp.lang.python posting
186 Adapted from from a comp.lang.python posting
187 by Duncan Booth."""
187 by Duncan Booth."""
188 def wrapper(*args, **kw):
188 def wrapper(*args, **kw):
189 return new_fn(*args, **kw)
189 return new_fn(*args, **kw)
190 if old_fn.__doc__:
190 if old_fn.__doc__:
191 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
191 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
192 return wrapper
192 return wrapper
193
193
194
194
195 class Pdb(OldPdb):
195 class Pdb(OldPdb):
196 """Modified Pdb class, does not load readline.
196 """Modified Pdb class, does not load readline.
197
197
198 for a standalone version that uses prompt_toolkit, see
198 for a standalone version that uses prompt_toolkit, see
199 `IPython.terminal.debugger.TerminalPdb` and
199 `IPython.terminal.debugger.TerminalPdb` and
200 `IPython.terminal.debugger.set_trace()`
200 `IPython.terminal.debugger.set_trace()`
201 """
201 """
202
202
203 def __init__(self, color_scheme=None, completekey=None,
203 def __init__(self, color_scheme=None, completekey=None,
204 stdin=None, stdout=None, context=5, **kwargs):
204 stdin=None, stdout=None, context=5, **kwargs):
205 """Create a new IPython debugger.
205 """Create a new IPython debugger.
206
206
207 :param color_scheme: Deprecated, do not use.
207 :param color_scheme: Deprecated, do not use.
208 :param completekey: Passed to pdb.Pdb.
208 :param completekey: Passed to pdb.Pdb.
209 :param stdin: Passed to pdb.Pdb.
209 :param stdin: Passed to pdb.Pdb.
210 :param stdout: Passed to pdb.Pdb.
210 :param stdout: Passed to pdb.Pdb.
211 :param context: Number of lines of source code context to show when
211 :param context: Number of lines of source code context to show when
212 displaying stacktrace information.
212 displaying stacktrace information.
213 :param kwargs: Passed to pdb.Pdb.
213 :param kwargs: Passed to pdb.Pdb.
214 The possibilities are python version dependent, see the python
214 The possibilities are python version dependent, see the python
215 docs for more info.
215 docs for more info.
216 """
216 """
217
217
218 # Parent constructor:
218 # Parent constructor:
219 try:
219 try:
220 self.context = int(context)
220 self.context = int(context)
221 if self.context <= 0:
221 if self.context <= 0:
222 raise ValueError("Context must be a positive integer")
222 raise ValueError("Context must be a positive integer")
223 except (TypeError, ValueError) as e:
223 except (TypeError, ValueError) as e:
224 raise ValueError("Context must be a positive integer") from e
224 raise ValueError("Context must be a positive integer") from e
225
225
226 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
226 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
227 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
227 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
228
228
229 # IPython changes...
229 # IPython changes...
230 self.shell = get_ipython()
230 self.shell = get_ipython()
231
231
232 if self.shell is None:
232 if self.shell is None:
233 save_main = sys.modules['__main__']
233 save_main = sys.modules['__main__']
234 # No IPython instance running, we must create one
234 # No IPython instance running, we must create one
235 from IPython.terminal.interactiveshell import \
235 from IPython.terminal.interactiveshell import \
236 TerminalInteractiveShell
236 TerminalInteractiveShell
237 self.shell = TerminalInteractiveShell.instance()
237 self.shell = TerminalInteractiveShell.instance()
238 # needed by any code which calls __import__("__main__") after
238 # needed by any code which calls __import__("__main__") after
239 # the debugger was entered. See also #9941.
239 # the debugger was entered. See also #9941.
240 sys.modules['__main__'] = save_main
240 sys.modules['__main__'] = save_main
241
241
242 if color_scheme is not None:
242 if color_scheme is not None:
243 warnings.warn(
243 warnings.warn(
244 "The `color_scheme` argument is deprecated since version 5.1",
244 "The `color_scheme` argument is deprecated since version 5.1",
245 DeprecationWarning, stacklevel=2)
245 DeprecationWarning, stacklevel=2)
246 else:
246 else:
247 color_scheme = self.shell.colors
247 color_scheme = self.shell.colors
248
248
249 self.aliases = {}
249 self.aliases = {}
250
250
251 # Create color table: we copy the default one from the traceback
251 # Create color table: we copy the default one from the traceback
252 # module and add a few attributes needed for debugging
252 # module and add a few attributes needed for debugging
253 self.color_scheme_table = exception_colors()
253 self.color_scheme_table = exception_colors()
254
254
255 # shorthands
255 # shorthands
256 C = coloransi.TermColors
256 C = coloransi.TermColors
257 cst = self.color_scheme_table
257 cst = self.color_scheme_table
258
258
259 cst['NoColor'].colors.prompt = C.NoColor
259 cst['NoColor'].colors.prompt = C.NoColor
260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
262
262
263 cst['Linux'].colors.prompt = C.Green
263 cst['Linux'].colors.prompt = C.Green
264 cst['Linux'].colors.breakpoint_enabled = C.LightRed
264 cst['Linux'].colors.breakpoint_enabled = C.LightRed
265 cst['Linux'].colors.breakpoint_disabled = C.Red
265 cst['Linux'].colors.breakpoint_disabled = C.Red
266
266
267 cst['LightBG'].colors.prompt = C.Blue
267 cst['LightBG'].colors.prompt = C.Blue
268 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
268 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
269 cst['LightBG'].colors.breakpoint_disabled = C.Red
269 cst['LightBG'].colors.breakpoint_disabled = C.Red
270
270
271 cst['Neutral'].colors.prompt = C.Blue
271 cst['Neutral'].colors.prompt = C.Blue
272 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
272 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
273 cst['Neutral'].colors.breakpoint_disabled = C.Red
273 cst['Neutral'].colors.breakpoint_disabled = C.Red
274
274
275
275
276 # Add a python parser so we can syntax highlight source while
276 # Add a python parser so we can syntax highlight source while
277 # debugging.
277 # debugging.
278 self.parser = PyColorize.Parser(style=color_scheme)
278 self.parser = PyColorize.Parser(style=color_scheme)
279 self.set_colors(color_scheme)
279 self.set_colors(color_scheme)
280
280
281 # Set the prompt - the default prompt is '(Pdb)'
281 # Set the prompt - the default prompt is '(Pdb)'
282 self.prompt = prompt
282 self.prompt = prompt
283 self.skip_hidden = True
283 self.skip_hidden = True
284
284
285 def set_colors(self, scheme):
285 def set_colors(self, scheme):
286 """Shorthand access to the color table scheme selector method."""
286 """Shorthand access to the color table scheme selector method."""
287 self.color_scheme_table.set_active_scheme(scheme)
287 self.color_scheme_table.set_active_scheme(scheme)
288 self.parser.style = scheme
288 self.parser.style = scheme
289
289
290
290
291 def hidden_frames(self, stack):
291 def hidden_frames(self, stack):
292 """
292 """
293 Given an index in the stack return wether it should be skipped.
293 Given an index in the stack return wether it should be skipped.
294
294
295 This is used in up/down and where to skip frames.
295 This is used in up/down and where to skip frames.
296 """
296 """
297 ip_hide = [s[0].f_locals.get("__tracebackhide__", False) for s in stack]
297 # The f_locals dictionary is updated from the actual frame
298 # locals whenever the .f_locals accessor is called, so we
299 # avoid calling it here to preserve self.curframe_locals.
300 # Futhermore, there is no good reason to hide the current frame.
301 ip_hide = [
302 False if s[0] is self.curframe else s[0].f_locals.get(
303 "__tracebackhide__", False)
304 for s in stack]
298 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
305 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
299 if ip_start:
306 if ip_start:
300 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
307 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
301 return ip_hide
308 return ip_hide
302
309
303 def interaction(self, frame, traceback):
310 def interaction(self, frame, traceback):
304 try:
311 try:
305 OldPdb.interaction(self, frame, traceback)
312 OldPdb.interaction(self, frame, traceback)
306 except KeyboardInterrupt:
313 except KeyboardInterrupt:
307 self.stdout.write("\n" + self.shell.get_exception_only())
314 self.stdout.write("\n" + self.shell.get_exception_only())
308
315
309 def new_do_frame(self, arg):
316 def new_do_frame(self, arg):
310 OldPdb.do_frame(self, arg)
317 OldPdb.do_frame(self, arg)
311
318
312 def new_do_quit(self, arg):
319 def new_do_quit(self, arg):
313
320
314 if hasattr(self, 'old_all_completions'):
321 if hasattr(self, 'old_all_completions'):
315 self.shell.Completer.all_completions=self.old_all_completions
322 self.shell.Completer.all_completions=self.old_all_completions
316
323
317 return OldPdb.do_quit(self, arg)
324 return OldPdb.do_quit(self, arg)
318
325
319 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
326 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
320
327
321 def new_do_restart(self, arg):
328 def new_do_restart(self, arg):
322 """Restart command. In the context of ipython this is exactly the same
329 """Restart command. In the context of ipython this is exactly the same
323 thing as 'quit'."""
330 thing as 'quit'."""
324 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
331 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
325 return self.do_quit(arg)
332 return self.do_quit(arg)
326
333
327 def print_stack_trace(self, context=None):
334 def print_stack_trace(self, context=None):
328 Colors = self.color_scheme_table.active_colors
335 Colors = self.color_scheme_table.active_colors
329 ColorsNormal = Colors.Normal
336 ColorsNormal = Colors.Normal
330 if context is None:
337 if context is None:
331 context = self.context
338 context = self.context
332 try:
339 try:
333 context=int(context)
340 context=int(context)
334 if context <= 0:
341 if context <= 0:
335 raise ValueError("Context must be a positive integer")
342 raise ValueError("Context must be a positive integer")
336 except (TypeError, ValueError) as e:
343 except (TypeError, ValueError) as e:
337 raise ValueError("Context must be a positive integer") from e
344 raise ValueError("Context must be a positive integer") from e
338 try:
345 try:
339 skipped = 0
346 skipped = 0
340 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
347 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
341 if hidden and self.skip_hidden:
348 if hidden and self.skip_hidden:
342 skipped += 1
349 skipped += 1
343 continue
350 continue
344 if skipped:
351 if skipped:
345 print(
352 print(
346 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
353 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
347 )
354 )
348 skipped = 0
355 skipped = 0
349 self.print_stack_entry(frame_lineno, context=context)
356 self.print_stack_entry(frame_lineno, context=context)
350 if skipped:
357 if skipped:
351 print(
358 print(
352 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
359 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
353 )
360 )
354 except KeyboardInterrupt:
361 except KeyboardInterrupt:
355 pass
362 pass
356
363
357 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
364 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
358 context=None):
365 context=None):
359 if context is None:
366 if context is None:
360 context = self.context
367 context = self.context
361 try:
368 try:
362 context=int(context)
369 context=int(context)
363 if context <= 0:
370 if context <= 0:
364 raise ValueError("Context must be a positive integer")
371 raise ValueError("Context must be a positive integer")
365 except (TypeError, ValueError) as e:
372 except (TypeError, ValueError) as e:
366 raise ValueError("Context must be a positive integer") from e
373 raise ValueError("Context must be a positive integer") from e
367 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
374 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
368
375
369 # vds: >>
376 # vds: >>
370 frame, lineno = frame_lineno
377 frame, lineno = frame_lineno
371 filename = frame.f_code.co_filename
378 filename = frame.f_code.co_filename
372 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
379 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
373 # vds: <<
380 # vds: <<
374
381
375 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
382 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
376 if context is None:
383 if context is None:
377 context = self.context
384 context = self.context
378 try:
385 try:
379 context=int(context)
386 context=int(context)
380 if context <= 0:
387 if context <= 0:
381 print("Context must be a positive integer", file=self.stdout)
388 print("Context must be a positive integer", file=self.stdout)
382 except (TypeError, ValueError):
389 except (TypeError, ValueError):
383 print("Context must be a positive integer", file=self.stdout)
390 print("Context must be a positive integer", file=self.stdout)
384
391
385 import reprlib
392 import reprlib
386
393
387 ret = []
394 ret = []
388
395
389 Colors = self.color_scheme_table.active_colors
396 Colors = self.color_scheme_table.active_colors
390 ColorsNormal = Colors.Normal
397 ColorsNormal = Colors.Normal
391 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
398 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
392 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
399 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
393 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
400 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
394 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
401 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
395 ColorsNormal)
402 ColorsNormal)
396
403
397 frame, lineno = frame_lineno
404 frame, lineno = frame_lineno
398
405
399 return_value = ''
406 return_value = ''
400 if '__return__' in frame.f_locals:
407 if '__return__' in frame.f_locals:
401 rv = frame.f_locals['__return__']
408 rv = frame.f_locals['__return__']
402 #return_value += '->'
409 #return_value += '->'
403 return_value += reprlib.repr(rv) + '\n'
410 return_value += reprlib.repr(rv) + '\n'
404 ret.append(return_value)
411 ret.append(return_value)
405
412
406 #s = filename + '(' + `lineno` + ')'
413 #s = filename + '(' + `lineno` + ')'
407 filename = self.canonic(frame.f_code.co_filename)
414 filename = self.canonic(frame.f_code.co_filename)
408 link = tpl_link % py3compat.cast_unicode(filename)
415 link = tpl_link % py3compat.cast_unicode(filename)
409
416
410 if frame.f_code.co_name:
417 if frame.f_code.co_name:
411 func = frame.f_code.co_name
418 func = frame.f_code.co_name
412 else:
419 else:
413 func = "<lambda>"
420 func = "<lambda>"
414
421
415 call = ''
422 call = ''
416 if func != '?':
423 if func != '?':
417 if '__args__' in frame.f_locals:
424 if '__args__' in frame.f_locals:
418 args = reprlib.repr(frame.f_locals['__args__'])
425 args = reprlib.repr(frame.f_locals['__args__'])
419 else:
426 else:
420 args = '()'
427 args = '()'
421 call = tpl_call % (func, args)
428 call = tpl_call % (func, args)
422
429
423 # The level info should be generated in the same format pdb uses, to
430 # The level info should be generated in the same format pdb uses, to
424 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
431 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
425 if frame is self.curframe:
432 if frame is self.curframe:
426 ret.append('> ')
433 ret.append('> ')
427 else:
434 else:
428 ret.append(' ')
435 ret.append(' ')
429 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
436 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
430
437
431 start = lineno - 1 - context//2
438 start = lineno - 1 - context//2
432 lines = linecache.getlines(filename)
439 lines = linecache.getlines(filename)
433 start = min(start, len(lines) - context)
440 start = min(start, len(lines) - context)
434 start = max(start, 0)
441 start = max(start, 0)
435 lines = lines[start : start + context]
442 lines = lines[start : start + context]
436
443
437 for i,line in enumerate(lines):
444 for i,line in enumerate(lines):
438 show_arrow = (start + 1 + i == lineno)
445 show_arrow = (start + 1 + i == lineno)
439 linetpl = (frame is self.curframe or show_arrow) \
446 linetpl = (frame is self.curframe or show_arrow) \
440 and tpl_line_em \
447 and tpl_line_em \
441 or tpl_line
448 or tpl_line
442 ret.append(self.__format_line(linetpl, filename,
449 ret.append(self.__format_line(linetpl, filename,
443 start + 1 + i, line,
450 start + 1 + i, line,
444 arrow = show_arrow) )
451 arrow = show_arrow) )
445 return ''.join(ret)
452 return ''.join(ret)
446
453
447 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
454 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
448 bp_mark = ""
455 bp_mark = ""
449 bp_mark_color = ""
456 bp_mark_color = ""
450
457
451 new_line, err = self.parser.format2(line, 'str')
458 new_line, err = self.parser.format2(line, 'str')
452 if not err:
459 if not err:
453 line = new_line
460 line = new_line
454
461
455 bp = None
462 bp = None
456 if lineno in self.get_file_breaks(filename):
463 if lineno in self.get_file_breaks(filename):
457 bps = self.get_breaks(filename, lineno)
464 bps = self.get_breaks(filename, lineno)
458 bp = bps[-1]
465 bp = bps[-1]
459
466
460 if bp:
467 if bp:
461 Colors = self.color_scheme_table.active_colors
468 Colors = self.color_scheme_table.active_colors
462 bp_mark = str(bp.number)
469 bp_mark = str(bp.number)
463 bp_mark_color = Colors.breakpoint_enabled
470 bp_mark_color = Colors.breakpoint_enabled
464 if not bp.enabled:
471 if not bp.enabled:
465 bp_mark_color = Colors.breakpoint_disabled
472 bp_mark_color = Colors.breakpoint_disabled
466
473
467 numbers_width = 7
474 numbers_width = 7
468 if arrow:
475 if arrow:
469 # This is the line with the error
476 # This is the line with the error
470 pad = numbers_width - len(str(lineno)) - len(bp_mark)
477 pad = numbers_width - len(str(lineno)) - len(bp_mark)
471 num = '%s%s' % (make_arrow(pad), str(lineno))
478 num = '%s%s' % (make_arrow(pad), str(lineno))
472 else:
479 else:
473 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
480 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
474
481
475 return tpl_line % (bp_mark_color + bp_mark, num, line)
482 return tpl_line % (bp_mark_color + bp_mark, num, line)
476
483
477
484
478 def print_list_lines(self, filename, first, last):
485 def print_list_lines(self, filename, first, last):
479 """The printing (as opposed to the parsing part of a 'list'
486 """The printing (as opposed to the parsing part of a 'list'
480 command."""
487 command."""
481 try:
488 try:
482 Colors = self.color_scheme_table.active_colors
489 Colors = self.color_scheme_table.active_colors
483 ColorsNormal = Colors.Normal
490 ColorsNormal = Colors.Normal
484 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
491 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
485 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
492 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
486 src = []
493 src = []
487 if filename == "<string>" and hasattr(self, "_exec_filename"):
494 if filename == "<string>" and hasattr(self, "_exec_filename"):
488 filename = self._exec_filename
495 filename = self._exec_filename
489
496
490 for lineno in range(first, last+1):
497 for lineno in range(first, last+1):
491 line = linecache.getline(filename, lineno)
498 line = linecache.getline(filename, lineno)
492 if not line:
499 if not line:
493 break
500 break
494
501
495 if lineno == self.curframe.f_lineno:
502 if lineno == self.curframe.f_lineno:
496 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
503 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
497 else:
504 else:
498 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
505 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
499
506
500 src.append(line)
507 src.append(line)
501 self.lineno = lineno
508 self.lineno = lineno
502
509
503 print(''.join(src), file=self.stdout)
510 print(''.join(src), file=self.stdout)
504
511
505 except KeyboardInterrupt:
512 except KeyboardInterrupt:
506 pass
513 pass
507
514
508 def do_skip_hidden(self, arg):
515 def do_skip_hidden(self, arg):
509 """
516 """
510 Change whether or not we should skip frames with the
517 Change whether or not we should skip frames with the
511 __tracebackhide__ attribute.
518 __tracebackhide__ attribute.
512 """
519 """
513 if arg.strip().lower() in ("true", "yes"):
520 if arg.strip().lower() in ("true", "yes"):
514 self.skip_hidden = True
521 self.skip_hidden = True
515 elif arg.strip().lower() in ("false", "no"):
522 elif arg.strip().lower() in ("false", "no"):
516 self.skip_hidden = False
523 self.skip_hidden = False
517
524
518 def do_list(self, arg):
525 def do_list(self, arg):
519 """Print lines of code from the current stack frame
526 """Print lines of code from the current stack frame
520 """
527 """
521 self.lastcmd = 'list'
528 self.lastcmd = 'list'
522 last = None
529 last = None
523 if arg:
530 if arg:
524 try:
531 try:
525 x = eval(arg, {}, {})
532 x = eval(arg, {}, {})
526 if type(x) == type(()):
533 if type(x) == type(()):
527 first, last = x
534 first, last = x
528 first = int(first)
535 first = int(first)
529 last = int(last)
536 last = int(last)
530 if last < first:
537 if last < first:
531 # Assume it's a count
538 # Assume it's a count
532 last = first + last
539 last = first + last
533 else:
540 else:
534 first = max(1, int(x) - 5)
541 first = max(1, int(x) - 5)
535 except:
542 except:
536 print('*** Error in argument:', repr(arg), file=self.stdout)
543 print('*** Error in argument:', repr(arg), file=self.stdout)
537 return
544 return
538 elif self.lineno is None:
545 elif self.lineno is None:
539 first = max(1, self.curframe.f_lineno - 5)
546 first = max(1, self.curframe.f_lineno - 5)
540 else:
547 else:
541 first = self.lineno + 1
548 first = self.lineno + 1
542 if last is None:
549 if last is None:
543 last = first + 10
550 last = first + 10
544 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
551 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
545
552
546 # vds: >>
553 # vds: >>
547 lineno = first
554 lineno = first
548 filename = self.curframe.f_code.co_filename
555 filename = self.curframe.f_code.co_filename
549 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
556 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
550 # vds: <<
557 # vds: <<
551
558
552 do_l = do_list
559 do_l = do_list
553
560
554 def getsourcelines(self, obj):
561 def getsourcelines(self, obj):
555 lines, lineno = inspect.findsource(obj)
562 lines, lineno = inspect.findsource(obj)
556 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
563 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
557 # must be a module frame: do not try to cut a block out of it
564 # must be a module frame: do not try to cut a block out of it
558 return lines, 1
565 return lines, 1
559 elif inspect.ismodule(obj):
566 elif inspect.ismodule(obj):
560 return lines, 1
567 return lines, 1
561 return inspect.getblock(lines[lineno:]), lineno+1
568 return inspect.getblock(lines[lineno:]), lineno+1
562
569
563 def do_longlist(self, arg):
570 def do_longlist(self, arg):
564 """Print lines of code from the current stack frame.
571 """Print lines of code from the current stack frame.
565
572
566 Shows more lines than 'list' does.
573 Shows more lines than 'list' does.
567 """
574 """
568 self.lastcmd = 'longlist'
575 self.lastcmd = 'longlist'
569 try:
576 try:
570 lines, lineno = self.getsourcelines(self.curframe)
577 lines, lineno = self.getsourcelines(self.curframe)
571 except OSError as err:
578 except OSError as err:
572 self.error(err)
579 self.error(err)
573 return
580 return
574 last = lineno + len(lines)
581 last = lineno + len(lines)
575 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
582 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
576 do_ll = do_longlist
583 do_ll = do_longlist
577
584
578 def do_debug(self, arg):
585 def do_debug(self, arg):
579 """debug code
586 """debug code
580 Enter a recursive debugger that steps through the code
587 Enter a recursive debugger that steps through the code
581 argument (which is an arbitrary expression or statement to be
588 argument (which is an arbitrary expression or statement to be
582 executed in the current environment).
589 executed in the current environment).
583 """
590 """
584 sys.settrace(None)
591 sys.settrace(None)
585 globals = self.curframe.f_globals
592 globals = self.curframe.f_globals
586 locals = self.curframe_locals
593 locals = self.curframe_locals
587 p = self.__class__(completekey=self.completekey,
594 p = self.__class__(completekey=self.completekey,
588 stdin=self.stdin, stdout=self.stdout)
595 stdin=self.stdin, stdout=self.stdout)
589 p.use_rawinput = self.use_rawinput
596 p.use_rawinput = self.use_rawinput
590 p.prompt = "(%s) " % self.prompt.strip()
597 p.prompt = "(%s) " % self.prompt.strip()
591 self.message("ENTERING RECURSIVE DEBUGGER")
598 self.message("ENTERING RECURSIVE DEBUGGER")
592 sys.call_tracing(p.run, (arg, globals, locals))
599 sys.call_tracing(p.run, (arg, globals, locals))
593 self.message("LEAVING RECURSIVE DEBUGGER")
600 self.message("LEAVING RECURSIVE DEBUGGER")
594 sys.settrace(self.trace_dispatch)
601 sys.settrace(self.trace_dispatch)
595 self.lastcmd = p.lastcmd
602 self.lastcmd = p.lastcmd
596
603
597 def do_pdef(self, arg):
604 def do_pdef(self, arg):
598 """Print the call signature for any callable object.
605 """Print the call signature for any callable object.
599
606
600 The debugger interface to %pdef"""
607 The debugger interface to %pdef"""
601 namespaces = [('Locals', self.curframe.f_locals),
608 namespaces = [('Locals', self.curframe.f_locals),
602 ('Globals', self.curframe.f_globals)]
609 ('Globals', self.curframe.f_globals)]
603 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
610 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
604
611
605 def do_pdoc(self, arg):
612 def do_pdoc(self, arg):
606 """Print the docstring for an object.
613 """Print the docstring for an object.
607
614
608 The debugger interface to %pdoc."""
615 The debugger interface to %pdoc."""
609 namespaces = [('Locals', self.curframe.f_locals),
616 namespaces = [('Locals', self.curframe.f_locals),
610 ('Globals', self.curframe.f_globals)]
617 ('Globals', self.curframe.f_globals)]
611 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
618 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
612
619
613 def do_pfile(self, arg):
620 def do_pfile(self, arg):
614 """Print (or run through pager) the file where an object is defined.
621 """Print (or run through pager) the file where an object is defined.
615
622
616 The debugger interface to %pfile.
623 The debugger interface to %pfile.
617 """
624 """
618 namespaces = [('Locals', self.curframe.f_locals),
625 namespaces = [('Locals', self.curframe.f_locals),
619 ('Globals', self.curframe.f_globals)]
626 ('Globals', self.curframe.f_globals)]
620 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
627 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
621
628
622 def do_pinfo(self, arg):
629 def do_pinfo(self, arg):
623 """Provide detailed information about an object.
630 """Provide detailed information about an object.
624
631
625 The debugger interface to %pinfo, i.e., obj?."""
632 The debugger interface to %pinfo, i.e., obj?."""
626 namespaces = [('Locals', self.curframe.f_locals),
633 namespaces = [('Locals', self.curframe.f_locals),
627 ('Globals', self.curframe.f_globals)]
634 ('Globals', self.curframe.f_globals)]
628 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
635 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
629
636
630 def do_pinfo2(self, arg):
637 def do_pinfo2(self, arg):
631 """Provide extra detailed information about an object.
638 """Provide extra detailed information about an object.
632
639
633 The debugger interface to %pinfo2, i.e., obj??."""
640 The debugger interface to %pinfo2, i.e., obj??."""
634 namespaces = [('Locals', self.curframe.f_locals),
641 namespaces = [('Locals', self.curframe.f_locals),
635 ('Globals', self.curframe.f_globals)]
642 ('Globals', self.curframe.f_globals)]
636 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
643 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
637
644
638 def do_psource(self, arg):
645 def do_psource(self, arg):
639 """Print (or run through pager) the source code for an object."""
646 """Print (or run through pager) the source code for an object."""
640 namespaces = [('Locals', self.curframe.f_locals),
647 namespaces = [('Locals', self.curframe.f_locals),
641 ('Globals', self.curframe.f_globals)]
648 ('Globals', self.curframe.f_globals)]
642 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
649 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
643
650
644 def do_where(self, arg):
651 def do_where(self, arg):
645 """w(here)
652 """w(here)
646 Print a stack trace, with the most recent frame at the bottom.
653 Print a stack trace, with the most recent frame at the bottom.
647 An arrow indicates the "current frame", which determines the
654 An arrow indicates the "current frame", which determines the
648 context of most commands. 'bt' is an alias for this command.
655 context of most commands. 'bt' is an alias for this command.
649
656
650 Take a number as argument as an (optional) number of context line to
657 Take a number as argument as an (optional) number of context line to
651 print"""
658 print"""
652 if arg:
659 if arg:
653 try:
660 try:
654 context = int(arg)
661 context = int(arg)
655 except ValueError as err:
662 except ValueError as err:
656 self.error(err)
663 self.error(err)
657 return
664 return
658 self.print_stack_trace(context)
665 self.print_stack_trace(context)
659 else:
666 else:
660 self.print_stack_trace()
667 self.print_stack_trace()
661
668
662 do_w = do_where
669 do_w = do_where
663
670
664 def stop_here(self, frame):
671 def stop_here(self, frame):
665 hidden = False
672 hidden = False
666 if self.skip_hidden:
673 if self.skip_hidden:
667 hidden = frame.f_locals.get("__tracebackhide__", False)
674 hidden = frame.f_locals.get("__tracebackhide__", False)
668 if hidden:
675 if hidden:
669 Colors = self.color_scheme_table.active_colors
676 Colors = self.color_scheme_table.active_colors
670 ColorsNormal = Colors.Normal
677 ColorsNormal = Colors.Normal
671 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
678 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
672
679
673 return super().stop_here(frame)
680 return super().stop_here(frame)
674
681
675 def do_up(self, arg):
682 def do_up(self, arg):
676 """u(p) [count]
683 """u(p) [count]
677 Move the current frame count (default one) levels up in the
684 Move the current frame count (default one) levels up in the
678 stack trace (to an older frame).
685 stack trace (to an older frame).
679
686
680 Will skip hidden frames.
687 Will skip hidden frames.
681 """
688 """
682 ## modified version of upstream that skips
689 ## modified version of upstream that skips
683 # frames with __tracebackide__
690 # frames with __tracebackide__
684 if self.curindex == 0:
691 if self.curindex == 0:
685 self.error("Oldest frame")
692 self.error("Oldest frame")
686 return
693 return
687 try:
694 try:
688 count = int(arg or 1)
695 count = int(arg or 1)
689 except ValueError:
696 except ValueError:
690 self.error("Invalid frame count (%s)" % arg)
697 self.error("Invalid frame count (%s)" % arg)
691 return
698 return
692 skipped = 0
699 skipped = 0
693 if count < 0:
700 if count < 0:
694 _newframe = 0
701 _newframe = 0
695 else:
702 else:
696 _newindex = self.curindex
703 _newindex = self.curindex
697 counter = 0
704 counter = 0
698 hidden_frames = self.hidden_frames(self.stack)
705 hidden_frames = self.hidden_frames(self.stack)
699 for i in range(self.curindex - 1, -1, -1):
706 for i in range(self.curindex - 1, -1, -1):
700 frame = self.stack[i][0]
707 frame = self.stack[i][0]
701 if hidden_frames[i] and self.skip_hidden:
708 if hidden_frames[i] and self.skip_hidden:
702 skipped += 1
709 skipped += 1
703 continue
710 continue
704 counter += 1
711 counter += 1
705 if counter >= count:
712 if counter >= count:
706 break
713 break
707 else:
714 else:
708 # if no break occured.
715 # if no break occured.
709 self.error("all frames above hidden")
716 self.error("all frames above hidden")
710 return
717 return
711
718
712 Colors = self.color_scheme_table.active_colors
719 Colors = self.color_scheme_table.active_colors
713 ColorsNormal = Colors.Normal
720 ColorsNormal = Colors.Normal
714 _newframe = i
721 _newframe = i
715 self._select_frame(_newframe)
722 self._select_frame(_newframe)
716 if skipped:
723 if skipped:
717 print(
724 print(
718 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
725 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
719 )
726 )
720
727
721 def do_down(self, arg):
728 def do_down(self, arg):
722 """d(own) [count]
729 """d(own) [count]
723 Move the current frame count (default one) levels down in the
730 Move the current frame count (default one) levels down in the
724 stack trace (to a newer frame).
731 stack trace (to a newer frame).
725
732
726 Will skip hidden frames.
733 Will skip hidden frames.
727 """
734 """
728 if self.curindex + 1 == len(self.stack):
735 if self.curindex + 1 == len(self.stack):
729 self.error("Newest frame")
736 self.error("Newest frame")
730 return
737 return
731 try:
738 try:
732 count = int(arg or 1)
739 count = int(arg or 1)
733 except ValueError:
740 except ValueError:
734 self.error("Invalid frame count (%s)" % arg)
741 self.error("Invalid frame count (%s)" % arg)
735 return
742 return
736 if count < 0:
743 if count < 0:
737 _newframe = len(self.stack) - 1
744 _newframe = len(self.stack) - 1
738 else:
745 else:
739 _newindex = self.curindex
746 _newindex = self.curindex
740 counter = 0
747 counter = 0
741 skipped = 0
748 skipped = 0
742 hidden_frames = self.hidden_frames(self.stack)
749 hidden_frames = self.hidden_frames(self.stack)
743 for i in range(self.curindex + 1, len(self.stack)):
750 for i in range(self.curindex + 1, len(self.stack)):
744 frame = self.stack[i][0]
751 frame = self.stack[i][0]
745 if hidden_frames[i] and self.skip_hidden:
752 if hidden_frames[i] and self.skip_hidden:
746 skipped += 1
753 skipped += 1
747 continue
754 continue
748 counter += 1
755 counter += 1
749 if counter >= count:
756 if counter >= count:
750 break
757 break
751 else:
758 else:
752 self.error("all frames bellow hidden")
759 self.error("all frames bellow hidden")
753 return
760 return
754
761
755 Colors = self.color_scheme_table.active_colors
762 Colors = self.color_scheme_table.active_colors
756 ColorsNormal = Colors.Normal
763 ColorsNormal = Colors.Normal
757 if skipped:
764 if skipped:
758 print(
765 print(
759 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
766 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
760 )
767 )
761 _newframe = i
768 _newframe = i
762
769
763 self._select_frame(_newframe)
770 self._select_frame(_newframe)
764
771
765 do_d = do_down
772 do_d = do_down
766 do_u = do_up
773 do_u = do_up
767
774
768 class InterruptiblePdb(Pdb):
775 class InterruptiblePdb(Pdb):
769 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
776 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
770
777
771 def cmdloop(self):
778 def cmdloop(self):
772 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
779 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
773 try:
780 try:
774 return OldPdb.cmdloop(self)
781 return OldPdb.cmdloop(self)
775 except KeyboardInterrupt:
782 except KeyboardInterrupt:
776 self.stop_here = lambda frame: False
783 self.stop_here = lambda frame: False
777 self.do_quit("")
784 self.do_quit("")
778 sys.settrace(None)
785 sys.settrace(None)
779 self.quitting = False
786 self.quitting = False
780 raise
787 raise
781
788
782 def _cmdloop(self):
789 def _cmdloop(self):
783 while True:
790 while True:
784 try:
791 try:
785 # keyboard interrupts allow for an easy way to cancel
792 # keyboard interrupts allow for an easy way to cancel
786 # the current command, so allow them during interactive input
793 # the current command, so allow them during interactive input
787 self.allow_kbdint = True
794 self.allow_kbdint = True
788 self.cmdloop()
795 self.cmdloop()
789 self.allow_kbdint = False
796 self.allow_kbdint = False
790 break
797 break
791 except KeyboardInterrupt:
798 except KeyboardInterrupt:
792 self.message('--KeyboardInterrupt--')
799 self.message('--KeyboardInterrupt--')
793 raise
800 raise
794
801
795
802
796 def set_trace(frame=None):
803 def set_trace(frame=None):
797 """
804 """
798 Start debugging from `frame`.
805 Start debugging from `frame`.
799
806
800 If frame is not specified, debugging starts from caller's frame.
807 If frame is not specified, debugging starts from caller's frame.
801 """
808 """
802 Pdb().set_trace(frame or sys._getframe().f_back)
809 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,645 +1,646 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2
2
3 import asyncio
3 import asyncio
4 import os
4 import os
5 import sys
5 import sys
6 import warnings
6 import warnings
7 from warnings import warn
7 from warnings import warn
8
8
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
10 from IPython.utils import io
10 from IPython.utils import io
11 from IPython.utils.py3compat import input
11 from IPython.utils.py3compat import input
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
13 from IPython.utils.process import abbrev_cwd
13 from IPython.utils.process import abbrev_cwd
14 from traitlets import (
14 from traitlets import (
15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
15 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
16 Any, validate
16 Any, validate
17 )
17 )
18
18
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
21 from prompt_toolkit.formatted_text import PygmentsTokens
21 from prompt_toolkit.formatted_text import PygmentsTokens
22 from prompt_toolkit.history import InMemoryHistory
22 from prompt_toolkit.history import InMemoryHistory
23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
23 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
24 from prompt_toolkit.output import ColorDepth
24 from prompt_toolkit.output import ColorDepth
25 from prompt_toolkit.patch_stdout import patch_stdout
25 from prompt_toolkit.patch_stdout import patch_stdout
26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
26 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
27 from prompt_toolkit.styles import DynamicStyle, merge_styles
27 from prompt_toolkit.styles import DynamicStyle, merge_styles
28 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
28 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
29 from prompt_toolkit import __version__ as ptk_version
29 from prompt_toolkit import __version__ as ptk_version
30
30
31 from pygments.styles import get_style_by_name
31 from pygments.styles import get_style_by_name
32 from pygments.style import Style
32 from pygments.style import Style
33 from pygments.token import Token
33 from pygments.token import Token
34
34
35 from .debugger import TerminalPdb, Pdb
35 from .debugger import TerminalPdb, Pdb
36 from .magics import TerminalMagics
36 from .magics import TerminalMagics
37 from .pt_inputhooks import get_inputhook_name_and_func
37 from .pt_inputhooks import get_inputhook_name_and_func
38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
38 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
39 from .ptutils import IPythonPTCompleter, IPythonPTLexer
40 from .shortcuts import create_ipython_shortcuts
40 from .shortcuts import create_ipython_shortcuts
41
41
42 DISPLAY_BANNER_DEPRECATED = object()
42 DISPLAY_BANNER_DEPRECATED = object()
43 PTK3 = ptk_version.startswith('3.')
43 PTK3 = ptk_version.startswith('3.')
44
44
45
45
46 class _NoStyle(Style): pass
46 class _NoStyle(Style): pass
47
47
48
48
49
49
50 _style_overrides_light_bg = {
50 _style_overrides_light_bg = {
51 Token.Prompt: '#ansibrightblue',
51 Token.Prompt: '#ansibrightblue',
52 Token.PromptNum: '#ansiblue bold',
52 Token.PromptNum: '#ansiblue bold',
53 Token.OutPrompt: '#ansibrightred',
53 Token.OutPrompt: '#ansibrightred',
54 Token.OutPromptNum: '#ansired bold',
54 Token.OutPromptNum: '#ansired bold',
55 }
55 }
56
56
57 _style_overrides_linux = {
57 _style_overrides_linux = {
58 Token.Prompt: '#ansibrightgreen',
58 Token.Prompt: '#ansibrightgreen',
59 Token.PromptNum: '#ansigreen bold',
59 Token.PromptNum: '#ansigreen bold',
60 Token.OutPrompt: '#ansibrightred',
60 Token.OutPrompt: '#ansibrightred',
61 Token.OutPromptNum: '#ansired bold',
61 Token.OutPromptNum: '#ansired bold',
62 }
62 }
63
63
64 def get_default_editor():
64 def get_default_editor():
65 try:
65 try:
66 return os.environ['EDITOR']
66 return os.environ['EDITOR']
67 except KeyError:
67 except KeyError:
68 pass
68 pass
69 except UnicodeError:
69 except UnicodeError:
70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
70 warn("$EDITOR environment variable is not pure ASCII. Using platform "
71 "default editor.")
71 "default editor.")
72
72
73 if os.name == 'posix':
73 if os.name == 'posix':
74 return 'vi' # the only one guaranteed to be there!
74 return 'vi' # the only one guaranteed to be there!
75 else:
75 else:
76 return 'notepad' # same in Windows!
76 return 'notepad' # same in Windows!
77
77
78 # conservatively check for tty
78 # conservatively check for tty
79 # overridden streams can result in things like:
79 # overridden streams can result in things like:
80 # - sys.stdin = None
80 # - sys.stdin = None
81 # - no isatty method
81 # - no isatty method
82 for _name in ('stdin', 'stdout', 'stderr'):
82 for _name in ('stdin', 'stdout', 'stderr'):
83 _stream = getattr(sys, _name)
83 _stream = getattr(sys, _name)
84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
84 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
85 _is_tty = False
85 _is_tty = False
86 break
86 break
87 else:
87 else:
88 _is_tty = True
88 _is_tty = True
89
89
90
90
91 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
91 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
92
92
93 def black_reformat_handler(text_before_cursor):
93 def black_reformat_handler(text_before_cursor):
94 import black
94 import black
95 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
95 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
96 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
96 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
97 formatted_text = formatted_text[:-1]
97 formatted_text = formatted_text[:-1]
98 return formatted_text
98 return formatted_text
99
99
100
100
101 class TerminalInteractiveShell(InteractiveShell):
101 class TerminalInteractiveShell(InteractiveShell):
102 mime_renderers = Dict().tag(config=True)
102 mime_renderers = Dict().tag(config=True)
103
103
104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
104 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
105 'to reserve for the tab completion menu, '
105 'to reserve for the tab completion menu, '
106 'search history, ...etc, the height of '
106 'search history, ...etc, the height of '
107 'these menus will at most this value. '
107 'these menus will at most this value. '
108 'Increase it is you prefer long and skinny '
108 'Increase it is you prefer long and skinny '
109 'menus, decrease for short and wide.'
109 'menus, decrease for short and wide.'
110 ).tag(config=True)
110 ).tag(config=True)
111
111
112 pt_app = None
112 pt_app = None
113 debugger_history = None
113 debugger_history = None
114
114
115 simple_prompt = Bool(_use_simple_prompt,
115 simple_prompt = Bool(_use_simple_prompt,
116 help="""Use `raw_input` for the REPL, without completion and prompt colors.
116 help="""Use `raw_input` for the REPL, without completion and prompt colors.
117
117
118 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
118 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
119 IPython own testing machinery, and emacs inferior-shell integration through elpy.
119 IPython own testing machinery, and emacs inferior-shell integration through elpy.
120
120
121 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
121 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
122 environment variable is set, or the current terminal is not a tty."""
122 environment variable is set, or the current terminal is not a tty."""
123 ).tag(config=True)
123 ).tag(config=True)
124
124
125 @property
125 @property
126 def debugger_cls(self):
126 def debugger_cls(self):
127 return Pdb if self.simple_prompt else TerminalPdb
127 return Pdb if self.simple_prompt else TerminalPdb
128
128
129 confirm_exit = Bool(True,
129 confirm_exit = Bool(True,
130 help="""
130 help="""
131 Set to confirm when you try to exit IPython with an EOF (Control-D
131 Set to confirm when you try to exit IPython with an EOF (Control-D
132 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
132 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
133 you can force a direct exit without any confirmation.""",
133 you can force a direct exit without any confirmation.""",
134 ).tag(config=True)
134 ).tag(config=True)
135
135
136 editing_mode = Unicode('emacs',
136 editing_mode = Unicode('emacs',
137 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
137 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
138 ).tag(config=True)
138 ).tag(config=True)
139
139
140 autoformatter = Unicode(None,
140 autoformatter = Unicode(None,
141 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
141 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
142 allow_none=True
142 allow_none=True
143 ).tag(config=True)
143 ).tag(config=True)
144
144
145 mouse_support = Bool(False,
145 mouse_support = Bool(False,
146 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
146 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
147 ).tag(config=True)
147 ).tag(config=True)
148
148
149 # We don't load the list of styles for the help string, because loading
149 # We don't load the list of styles for the help string, because loading
150 # Pygments plugins takes time and can cause unexpected errors.
150 # Pygments plugins takes time and can cause unexpected errors.
151 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
151 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
152 help="""The name or class of a Pygments style to use for syntax
152 help="""The name or class of a Pygments style to use for syntax
153 highlighting. To see available styles, run `pygmentize -L styles`."""
153 highlighting. To see available styles, run `pygmentize -L styles`."""
154 ).tag(config=True)
154 ).tag(config=True)
155
155
156 @validate('editing_mode')
156 @validate('editing_mode')
157 def _validate_editing_mode(self, proposal):
157 def _validate_editing_mode(self, proposal):
158 if proposal['value'].lower() == 'vim':
158 if proposal['value'].lower() == 'vim':
159 proposal['value']= 'vi'
159 proposal['value']= 'vi'
160 elif proposal['value'].lower() == 'default':
160 elif proposal['value'].lower() == 'default':
161 proposal['value']= 'emacs'
161 proposal['value']= 'emacs'
162
162
163 if hasattr(EditingMode, proposal['value'].upper()):
163 if hasattr(EditingMode, proposal['value'].upper()):
164 return proposal['value'].lower()
164 return proposal['value'].lower()
165
165
166 return self.editing_mode
166 return self.editing_mode
167
167
168
168
169 @observe('editing_mode')
169 @observe('editing_mode')
170 def _editing_mode(self, change):
170 def _editing_mode(self, change):
171 u_mode = change.new.upper()
171 u_mode = change.new.upper()
172 if self.pt_app:
172 if self.pt_app:
173 self.pt_app.editing_mode = u_mode
173 self.pt_app.editing_mode = u_mode
174
174
175 @observe('autoformatter')
175 @observe('autoformatter')
176 def _autoformatter_changed(self, change):
176 def _autoformatter_changed(self, change):
177 formatter = change.new
177 formatter = change.new
178 if formatter is None:
178 if formatter is None:
179 self.reformat_handler = lambda x:x
179 self.reformat_handler = lambda x:x
180 elif formatter == 'black':
180 elif formatter == 'black':
181 self.reformat_handler = black_reformat_handler
181 self.reformat_handler = black_reformat_handler
182 else:
182 else:
183 raise ValueError
183 raise ValueError
184
184
185 @observe('highlighting_style')
185 @observe('highlighting_style')
186 @observe('colors')
186 @observe('colors')
187 def _highlighting_style_changed(self, change):
187 def _highlighting_style_changed(self, change):
188 self.refresh_style()
188 self.refresh_style()
189
189
190 def refresh_style(self):
190 def refresh_style(self):
191 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
191 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
192
192
193
193
194 highlighting_style_overrides = Dict(
194 highlighting_style_overrides = Dict(
195 help="Override highlighting format for specific tokens"
195 help="Override highlighting format for specific tokens"
196 ).tag(config=True)
196 ).tag(config=True)
197
197
198 true_color = Bool(False,
198 true_color = Bool(False,
199 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
199 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
200 "If your terminal supports true color, the following command "
200 "If your terminal supports true color, the following command "
201 "should print 'TRUECOLOR' in orange: "
201 "should print 'TRUECOLOR' in orange: "
202 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
202 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
203 ).tag(config=True)
203 ).tag(config=True)
204
204
205 editor = Unicode(get_default_editor(),
205 editor = Unicode(get_default_editor(),
206 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
206 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
207 ).tag(config=True)
207 ).tag(config=True)
208
208
209 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
209 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
210
210
211 prompts = Instance(Prompts)
211 prompts = Instance(Prompts)
212
212
213 @default('prompts')
213 @default('prompts')
214 def _prompts_default(self):
214 def _prompts_default(self):
215 return self.prompts_class(self)
215 return self.prompts_class(self)
216
216
217 # @observe('prompts')
217 # @observe('prompts')
218 # def _(self, change):
218 # def _(self, change):
219 # self._update_layout()
219 # self._update_layout()
220
220
221 @default('displayhook_class')
221 @default('displayhook_class')
222 def _displayhook_class_default(self):
222 def _displayhook_class_default(self):
223 return RichPromptDisplayHook
223 return RichPromptDisplayHook
224
224
225 term_title = Bool(True,
225 term_title = Bool(True,
226 help="Automatically set the terminal title"
226 help="Automatically set the terminal title"
227 ).tag(config=True)
227 ).tag(config=True)
228
228
229 term_title_format = Unicode("IPython: {cwd}",
229 term_title_format = Unicode("IPython: {cwd}",
230 help="Customize the terminal title format. This is a python format string. " +
230 help="Customize the terminal title format. This is a python format string. " +
231 "Available substitutions are: {cwd}."
231 "Available substitutions are: {cwd}."
232 ).tag(config=True)
232 ).tag(config=True)
233
233
234 display_completions = Enum(('column', 'multicolumn','readlinelike'),
234 display_completions = Enum(('column', 'multicolumn','readlinelike'),
235 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
235 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
236 "'readlinelike'. These options are for `prompt_toolkit`, see "
236 "'readlinelike'. These options are for `prompt_toolkit`, see "
237 "`prompt_toolkit` documentation for more information."
237 "`prompt_toolkit` documentation for more information."
238 ),
238 ),
239 default_value='multicolumn').tag(config=True)
239 default_value='multicolumn').tag(config=True)
240
240
241 highlight_matching_brackets = Bool(True,
241 highlight_matching_brackets = Bool(True,
242 help="Highlight matching brackets.",
242 help="Highlight matching brackets.",
243 ).tag(config=True)
243 ).tag(config=True)
244
244
245 extra_open_editor_shortcuts = Bool(False,
245 extra_open_editor_shortcuts = Bool(False,
246 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
246 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
247 "This is in addition to the F2 binding, which is always enabled."
247 "This is in addition to the F2 binding, which is always enabled."
248 ).tag(config=True)
248 ).tag(config=True)
249
249
250 handle_return = Any(None,
250 handle_return = Any(None,
251 help="Provide an alternative handler to be called when the user presses "
251 help="Provide an alternative handler to be called when the user presses "
252 "Return. This is an advanced option intended for debugging, which "
252 "Return. This is an advanced option intended for debugging, which "
253 "may be changed or removed in later releases."
253 "may be changed or removed in later releases."
254 ).tag(config=True)
254 ).tag(config=True)
255
255
256 enable_history_search = Bool(True,
256 enable_history_search = Bool(True,
257 help="Allows to enable/disable the prompt toolkit history search"
257 help="Allows to enable/disable the prompt toolkit history search"
258 ).tag(config=True)
258 ).tag(config=True)
259
259
260 prompt_includes_vi_mode = Bool(True,
260 prompt_includes_vi_mode = Bool(True,
261 help="Display the current vi mode (when using vi editing mode)."
261 help="Display the current vi mode (when using vi editing mode)."
262 ).tag(config=True)
262 ).tag(config=True)
263
263
264 @observe('term_title')
264 @observe('term_title')
265 def init_term_title(self, change=None):
265 def init_term_title(self, change=None):
266 # Enable or disable the terminal title.
266 # Enable or disable the terminal title.
267 if self.term_title:
267 if self.term_title:
268 toggle_set_term_title(True)
268 toggle_set_term_title(True)
269 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
269 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
270 else:
270 else:
271 toggle_set_term_title(False)
271 toggle_set_term_title(False)
272
272
273 def restore_term_title(self):
273 def restore_term_title(self):
274 if self.term_title:
274 if self.term_title:
275 restore_term_title()
275 restore_term_title()
276
276
277 def init_display_formatter(self):
277 def init_display_formatter(self):
278 super(TerminalInteractiveShell, self).init_display_formatter()
278 super(TerminalInteractiveShell, self).init_display_formatter()
279 # terminal only supports plain text
279 # terminal only supports plain text
280 self.display_formatter.active_types = ['text/plain']
280 self.display_formatter.active_types = ['text/plain']
281 # disable `_ipython_display_`
281 # disable `_ipython_display_`
282 self.display_formatter.ipython_display_formatter.enabled = False
282 self.display_formatter.ipython_display_formatter.enabled = False
283
283
284 def init_prompt_toolkit_cli(self):
284 def init_prompt_toolkit_cli(self):
285 if self.simple_prompt:
285 if self.simple_prompt:
286 # Fall back to plain non-interactive output for tests.
286 # Fall back to plain non-interactive output for tests.
287 # This is very limited.
287 # This is very limited.
288 def prompt():
288 def prompt():
289 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
289 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
290 lines = [input(prompt_text)]
290 lines = [input(prompt_text)]
291 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
291 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
292 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
292 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
293 lines.append( input(prompt_continuation) )
293 lines.append( input(prompt_continuation) )
294 return '\n'.join(lines)
294 return '\n'.join(lines)
295 self.prompt_for_code = prompt
295 self.prompt_for_code = prompt
296 return
296 return
297
297
298 # Set up keyboard shortcuts
298 # Set up keyboard shortcuts
299 key_bindings = create_ipython_shortcuts(self)
299 key_bindings = create_ipython_shortcuts(self)
300
300
301 # Pre-populate history from IPython's history database
301 # Pre-populate history from IPython's history database
302 history = InMemoryHistory()
302 history = InMemoryHistory()
303 last_cell = u""
303 last_cell = u""
304 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
304 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
305 include_latest=True):
305 include_latest=True):
306 # Ignore blank lines and consecutive duplicates
306 # Ignore blank lines and consecutive duplicates
307 cell = cell.rstrip()
307 cell = cell.rstrip()
308 if cell and (cell != last_cell):
308 if cell and (cell != last_cell):
309 history.append_string(cell)
309 history.append_string(cell)
310 last_cell = cell
310 last_cell = cell
311
311
312 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
312 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
313 self.style = DynamicStyle(lambda: self._style)
313 self.style = DynamicStyle(lambda: self._style)
314
314
315 editing_mode = getattr(EditingMode, self.editing_mode.upper())
315 editing_mode = getattr(EditingMode, self.editing_mode.upper())
316
316
317 self.pt_loop = asyncio.new_event_loop()
317 self.pt_loop = asyncio.new_event_loop()
318 self.pt_app = PromptSession(
318 self.pt_app = PromptSession(
319 editing_mode=editing_mode,
319 editing_mode=editing_mode,
320 key_bindings=key_bindings,
320 key_bindings=key_bindings,
321 history=history,
321 history=history,
322 completer=IPythonPTCompleter(shell=self),
322 completer=IPythonPTCompleter(shell=self),
323 enable_history_search = self.enable_history_search,
323 enable_history_search = self.enable_history_search,
324 style=self.style,
324 style=self.style,
325 include_default_pygments_style=False,
325 include_default_pygments_style=False,
326 mouse_support=self.mouse_support,
326 mouse_support=self.mouse_support,
327 enable_open_in_editor=self.extra_open_editor_shortcuts,
327 enable_open_in_editor=self.extra_open_editor_shortcuts,
328 color_depth=self.color_depth,
328 color_depth=self.color_depth,
329 tempfile_suffix=".py",
329 tempfile_suffix=".py",
330 **self._extra_prompt_options())
330 **self._extra_prompt_options())
331
331
332 def _make_style_from_name_or_cls(self, name_or_cls):
332 def _make_style_from_name_or_cls(self, name_or_cls):
333 """
333 """
334 Small wrapper that make an IPython compatible style from a style name
334 Small wrapper that make an IPython compatible style from a style name
335
335
336 We need that to add style for prompt ... etc.
336 We need that to add style for prompt ... etc.
337 """
337 """
338 style_overrides = {}
338 style_overrides = {}
339 if name_or_cls == 'legacy':
339 if name_or_cls == 'legacy':
340 legacy = self.colors.lower()
340 legacy = self.colors.lower()
341 if legacy == 'linux':
341 if legacy == 'linux':
342 style_cls = get_style_by_name('monokai')
342 style_cls = get_style_by_name('monokai')
343 style_overrides = _style_overrides_linux
343 style_overrides = _style_overrides_linux
344 elif legacy == 'lightbg':
344 elif legacy == 'lightbg':
345 style_overrides = _style_overrides_light_bg
345 style_overrides = _style_overrides_light_bg
346 style_cls = get_style_by_name('pastie')
346 style_cls = get_style_by_name('pastie')
347 elif legacy == 'neutral':
347 elif legacy == 'neutral':
348 # The default theme needs to be visible on both a dark background
348 # The default theme needs to be visible on both a dark background
349 # and a light background, because we can't tell what the terminal
349 # and a light background, because we can't tell what the terminal
350 # looks like. These tweaks to the default theme help with that.
350 # looks like. These tweaks to the default theme help with that.
351 style_cls = get_style_by_name('default')
351 style_cls = get_style_by_name('default')
352 style_overrides.update({
352 style_overrides.update({
353 Token.Number: '#ansigreen',
353 Token.Number: '#ansigreen',
354 Token.Operator: 'noinherit',
354 Token.Operator: 'noinherit',
355 Token.String: '#ansiyellow',
355 Token.String: '#ansiyellow',
356 Token.Name.Function: '#ansiblue',
356 Token.Name.Function: '#ansiblue',
357 Token.Name.Class: 'bold #ansiblue',
357 Token.Name.Class: 'bold #ansiblue',
358 Token.Name.Namespace: 'bold #ansiblue',
358 Token.Name.Namespace: 'bold #ansiblue',
359 Token.Name.Variable.Magic: '#ansiblue',
359 Token.Prompt: '#ansigreen',
360 Token.Prompt: '#ansigreen',
360 Token.PromptNum: '#ansibrightgreen bold',
361 Token.PromptNum: '#ansibrightgreen bold',
361 Token.OutPrompt: '#ansired',
362 Token.OutPrompt: '#ansired',
362 Token.OutPromptNum: '#ansibrightred bold',
363 Token.OutPromptNum: '#ansibrightred bold',
363 })
364 })
364
365
365 # Hack: Due to limited color support on the Windows console
366 # Hack: Due to limited color support on the Windows console
366 # the prompt colors will be wrong without this
367 # the prompt colors will be wrong without this
367 if os.name == 'nt':
368 if os.name == 'nt':
368 style_overrides.update({
369 style_overrides.update({
369 Token.Prompt: '#ansidarkgreen',
370 Token.Prompt: '#ansidarkgreen',
370 Token.PromptNum: '#ansigreen bold',
371 Token.PromptNum: '#ansigreen bold',
371 Token.OutPrompt: '#ansidarkred',
372 Token.OutPrompt: '#ansidarkred',
372 Token.OutPromptNum: '#ansired bold',
373 Token.OutPromptNum: '#ansired bold',
373 })
374 })
374 elif legacy =='nocolor':
375 elif legacy =='nocolor':
375 style_cls=_NoStyle
376 style_cls=_NoStyle
376 style_overrides = {}
377 style_overrides = {}
377 else :
378 else :
378 raise ValueError('Got unknown colors: ', legacy)
379 raise ValueError('Got unknown colors: ', legacy)
379 else :
380 else :
380 if isinstance(name_or_cls, str):
381 if isinstance(name_or_cls, str):
381 style_cls = get_style_by_name(name_or_cls)
382 style_cls = get_style_by_name(name_or_cls)
382 else:
383 else:
383 style_cls = name_or_cls
384 style_cls = name_or_cls
384 style_overrides = {
385 style_overrides = {
385 Token.Prompt: '#ansigreen',
386 Token.Prompt: '#ansigreen',
386 Token.PromptNum: '#ansibrightgreen bold',
387 Token.PromptNum: '#ansibrightgreen bold',
387 Token.OutPrompt: '#ansired',
388 Token.OutPrompt: '#ansired',
388 Token.OutPromptNum: '#ansibrightred bold',
389 Token.OutPromptNum: '#ansibrightred bold',
389 }
390 }
390 style_overrides.update(self.highlighting_style_overrides)
391 style_overrides.update(self.highlighting_style_overrides)
391 style = merge_styles([
392 style = merge_styles([
392 style_from_pygments_cls(style_cls),
393 style_from_pygments_cls(style_cls),
393 style_from_pygments_dict(style_overrides),
394 style_from_pygments_dict(style_overrides),
394 ])
395 ])
395
396
396 return style
397 return style
397
398
398 @property
399 @property
399 def pt_complete_style(self):
400 def pt_complete_style(self):
400 return {
401 return {
401 'multicolumn': CompleteStyle.MULTI_COLUMN,
402 'multicolumn': CompleteStyle.MULTI_COLUMN,
402 'column': CompleteStyle.COLUMN,
403 'column': CompleteStyle.COLUMN,
403 'readlinelike': CompleteStyle.READLINE_LIKE,
404 'readlinelike': CompleteStyle.READLINE_LIKE,
404 }[self.display_completions]
405 }[self.display_completions]
405
406
406 @property
407 @property
407 def color_depth(self):
408 def color_depth(self):
408 return (ColorDepth.TRUE_COLOR if self.true_color else None)
409 return (ColorDepth.TRUE_COLOR if self.true_color else None)
409
410
410 def _extra_prompt_options(self):
411 def _extra_prompt_options(self):
411 """
412 """
412 Return the current layout option for the current Terminal InteractiveShell
413 Return the current layout option for the current Terminal InteractiveShell
413 """
414 """
414 def get_message():
415 def get_message():
415 return PygmentsTokens(self.prompts.in_prompt_tokens())
416 return PygmentsTokens(self.prompts.in_prompt_tokens())
416
417
417 if self.editing_mode == 'emacs':
418 if self.editing_mode == 'emacs':
418 # with emacs mode the prompt is (usually) static, so we call only
419 # with emacs mode the prompt is (usually) static, so we call only
419 # the function once. With VI mode it can toggle between [ins] and
420 # the function once. With VI mode it can toggle between [ins] and
420 # [nor] so we can't precompute.
421 # [nor] so we can't precompute.
421 # here I'm going to favor the default keybinding which almost
422 # here I'm going to favor the default keybinding which almost
422 # everybody uses to decrease CPU usage.
423 # everybody uses to decrease CPU usage.
423 # if we have issues with users with custom Prompts we can see how to
424 # if we have issues with users with custom Prompts we can see how to
424 # work around this.
425 # work around this.
425 get_message = get_message()
426 get_message = get_message()
426
427
427 options = {
428 options = {
428 'complete_in_thread': False,
429 'complete_in_thread': False,
429 'lexer':IPythonPTLexer(),
430 'lexer':IPythonPTLexer(),
430 'reserve_space_for_menu':self.space_for_menu,
431 'reserve_space_for_menu':self.space_for_menu,
431 'message': get_message,
432 'message': get_message,
432 'prompt_continuation': (
433 'prompt_continuation': (
433 lambda width, lineno, is_soft_wrap:
434 lambda width, lineno, is_soft_wrap:
434 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
435 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
435 'multiline': True,
436 'multiline': True,
436 'complete_style': self.pt_complete_style,
437 'complete_style': self.pt_complete_style,
437
438
438 # Highlight matching brackets, but only when this setting is
439 # Highlight matching brackets, but only when this setting is
439 # enabled, and only when the DEFAULT_BUFFER has the focus.
440 # enabled, and only when the DEFAULT_BUFFER has the focus.
440 'input_processors': [ConditionalProcessor(
441 'input_processors': [ConditionalProcessor(
441 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
442 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
442 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
443 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
443 Condition(lambda: self.highlight_matching_brackets))],
444 Condition(lambda: self.highlight_matching_brackets))],
444 }
445 }
445 if not PTK3:
446 if not PTK3:
446 options['inputhook'] = self.inputhook
447 options['inputhook'] = self.inputhook
447
448
448 return options
449 return options
449
450
450 def prompt_for_code(self):
451 def prompt_for_code(self):
451 if self.rl_next_input:
452 if self.rl_next_input:
452 default = self.rl_next_input
453 default = self.rl_next_input
453 self.rl_next_input = None
454 self.rl_next_input = None
454 else:
455 else:
455 default = ''
456 default = ''
456
457
457 # In order to make sure that asyncio code written in the
458 # In order to make sure that asyncio code written in the
458 # interactive shell doesn't interfere with the prompt, we run the
459 # interactive shell doesn't interfere with the prompt, we run the
459 # prompt in a different event loop.
460 # prompt in a different event loop.
460 # If we don't do this, people could spawn coroutine with a
461 # If we don't do this, people could spawn coroutine with a
461 # while/true inside which will freeze the prompt.
462 # while/true inside which will freeze the prompt.
462
463
463 try:
464 try:
464 old_loop = asyncio.get_event_loop()
465 old_loop = asyncio.get_event_loop()
465 except RuntimeError:
466 except RuntimeError:
466 # This happens when the user used `asyncio.run()`.
467 # This happens when the user used `asyncio.run()`.
467 old_loop = None
468 old_loop = None
468
469
469 asyncio.set_event_loop(self.pt_loop)
470 asyncio.set_event_loop(self.pt_loop)
470 try:
471 try:
471 with patch_stdout(raw=True):
472 with patch_stdout(raw=True):
472 text = self.pt_app.prompt(
473 text = self.pt_app.prompt(
473 default=default,
474 default=default,
474 **self._extra_prompt_options())
475 **self._extra_prompt_options())
475 finally:
476 finally:
476 # Restore the original event loop.
477 # Restore the original event loop.
477 asyncio.set_event_loop(old_loop)
478 asyncio.set_event_loop(old_loop)
478
479
479 return text
480 return text
480
481
481 def enable_win_unicode_console(self):
482 def enable_win_unicode_console(self):
482 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
483 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
483 # console by default, so WUC shouldn't be needed.
484 # console by default, so WUC shouldn't be needed.
484 from warnings import warn
485 from warnings import warn
485 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
486 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
486 DeprecationWarning,
487 DeprecationWarning,
487 stacklevel=2)
488 stacklevel=2)
488
489
489 def init_io(self):
490 def init_io(self):
490 if sys.platform not in {'win32', 'cli'}:
491 if sys.platform not in {'win32', 'cli'}:
491 return
492 return
492
493
493 import colorama
494 import colorama
494 colorama.init()
495 colorama.init()
495
496
496 # For some reason we make these wrappers around stdout/stderr.
497 # For some reason we make these wrappers around stdout/stderr.
497 # For now, we need to reset them so all output gets coloured.
498 # For now, we need to reset them so all output gets coloured.
498 # https://github.com/ipython/ipython/issues/8669
499 # https://github.com/ipython/ipython/issues/8669
499 # io.std* are deprecated, but don't show our own deprecation warnings
500 # io.std* are deprecated, but don't show our own deprecation warnings
500 # during initialization of the deprecated API.
501 # during initialization of the deprecated API.
501 with warnings.catch_warnings():
502 with warnings.catch_warnings():
502 warnings.simplefilter('ignore', DeprecationWarning)
503 warnings.simplefilter('ignore', DeprecationWarning)
503 io.stdout = io.IOStream(sys.stdout)
504 io.stdout = io.IOStream(sys.stdout)
504 io.stderr = io.IOStream(sys.stderr)
505 io.stderr = io.IOStream(sys.stderr)
505
506
506 def init_magics(self):
507 def init_magics(self):
507 super(TerminalInteractiveShell, self).init_magics()
508 super(TerminalInteractiveShell, self).init_magics()
508 self.register_magics(TerminalMagics)
509 self.register_magics(TerminalMagics)
509
510
510 def init_alias(self):
511 def init_alias(self):
511 # The parent class defines aliases that can be safely used with any
512 # The parent class defines aliases that can be safely used with any
512 # frontend.
513 # frontend.
513 super(TerminalInteractiveShell, self).init_alias()
514 super(TerminalInteractiveShell, self).init_alias()
514
515
515 # Now define aliases that only make sense on the terminal, because they
516 # Now define aliases that only make sense on the terminal, because they
516 # need direct access to the console in a way that we can't emulate in
517 # need direct access to the console in a way that we can't emulate in
517 # GUI or web frontend
518 # GUI or web frontend
518 if os.name == 'posix':
519 if os.name == 'posix':
519 for cmd in ('clear', 'more', 'less', 'man'):
520 for cmd in ('clear', 'more', 'less', 'man'):
520 self.alias_manager.soft_define_alias(cmd, cmd)
521 self.alias_manager.soft_define_alias(cmd, cmd)
521
522
522
523
523 def __init__(self, *args, **kwargs):
524 def __init__(self, *args, **kwargs):
524 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
525 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
525 self.init_prompt_toolkit_cli()
526 self.init_prompt_toolkit_cli()
526 self.init_term_title()
527 self.init_term_title()
527 self.keep_running = True
528 self.keep_running = True
528
529
529 self.debugger_history = InMemoryHistory()
530 self.debugger_history = InMemoryHistory()
530
531
531 def ask_exit(self):
532 def ask_exit(self):
532 self.keep_running = False
533 self.keep_running = False
533
534
534 rl_next_input = None
535 rl_next_input = None
535
536
536 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
537 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
537
538
538 if display_banner is not DISPLAY_BANNER_DEPRECATED:
539 if display_banner is not DISPLAY_BANNER_DEPRECATED:
539 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
540 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
540
541
541 self.keep_running = True
542 self.keep_running = True
542 while self.keep_running:
543 while self.keep_running:
543 print(self.separate_in, end='')
544 print(self.separate_in, end='')
544
545
545 try:
546 try:
546 code = self.prompt_for_code()
547 code = self.prompt_for_code()
547 except EOFError:
548 except EOFError:
548 if (not self.confirm_exit) \
549 if (not self.confirm_exit) \
549 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
550 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
550 self.ask_exit()
551 self.ask_exit()
551
552
552 else:
553 else:
553 if code:
554 if code:
554 self.run_cell(code, store_history=True)
555 self.run_cell(code, store_history=True)
555
556
556 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
557 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
557 # An extra layer of protection in case someone mashing Ctrl-C breaks
558 # An extra layer of protection in case someone mashing Ctrl-C breaks
558 # out of our internal code.
559 # out of our internal code.
559 if display_banner is not DISPLAY_BANNER_DEPRECATED:
560 if display_banner is not DISPLAY_BANNER_DEPRECATED:
560 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
561 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
561 while True:
562 while True:
562 try:
563 try:
563 self.interact()
564 self.interact()
564 break
565 break
565 except KeyboardInterrupt as e:
566 except KeyboardInterrupt as e:
566 print("\n%s escaped interact()\n" % type(e).__name__)
567 print("\n%s escaped interact()\n" % type(e).__name__)
567 finally:
568 finally:
568 # An interrupt during the eventloop will mess up the
569 # An interrupt during the eventloop will mess up the
569 # internal state of the prompt_toolkit library.
570 # internal state of the prompt_toolkit library.
570 # Stopping the eventloop fixes this, see
571 # Stopping the eventloop fixes this, see
571 # https://github.com/ipython/ipython/pull/9867
572 # https://github.com/ipython/ipython/pull/9867
572 if hasattr(self, '_eventloop'):
573 if hasattr(self, '_eventloop'):
573 self._eventloop.stop()
574 self._eventloop.stop()
574
575
575 self.restore_term_title()
576 self.restore_term_title()
576
577
577
578
578 _inputhook = None
579 _inputhook = None
579 def inputhook(self, context):
580 def inputhook(self, context):
580 if self._inputhook is not None:
581 if self._inputhook is not None:
581 self._inputhook(context)
582 self._inputhook(context)
582
583
583 active_eventloop = None
584 active_eventloop = None
584 def enable_gui(self, gui=None):
585 def enable_gui(self, gui=None):
585 if gui and (gui != 'inline') :
586 if gui and (gui != 'inline') :
586 self.active_eventloop, self._inputhook =\
587 self.active_eventloop, self._inputhook =\
587 get_inputhook_name_and_func(gui)
588 get_inputhook_name_and_func(gui)
588 else:
589 else:
589 self.active_eventloop = self._inputhook = None
590 self.active_eventloop = self._inputhook = None
590
591
591 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
592 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
592 # this inputhook.
593 # this inputhook.
593 if PTK3:
594 if PTK3:
594 import asyncio
595 import asyncio
595 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
596 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
596
597
597 if gui == 'asyncio':
598 if gui == 'asyncio':
598 # When we integrate the asyncio event loop, run the UI in the
599 # When we integrate the asyncio event loop, run the UI in the
599 # same event loop as the rest of the code. don't use an actual
600 # same event loop as the rest of the code. don't use an actual
600 # input hook. (Asyncio is not made for nesting event loops.)
601 # input hook. (Asyncio is not made for nesting event loops.)
601 self.pt_loop = asyncio.get_event_loop()
602 self.pt_loop = asyncio.get_event_loop()
602
603
603 elif self._inputhook:
604 elif self._inputhook:
604 # If an inputhook was set, create a new asyncio event loop with
605 # If an inputhook was set, create a new asyncio event loop with
605 # this inputhook for the prompt.
606 # this inputhook for the prompt.
606 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
607 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
607 else:
608 else:
608 # When there's no inputhook, run the prompt in a separate
609 # When there's no inputhook, run the prompt in a separate
609 # asyncio event loop.
610 # asyncio event loop.
610 self.pt_loop = asyncio.new_event_loop()
611 self.pt_loop = asyncio.new_event_loop()
611
612
612 # Run !system commands directly, not through pipes, so terminal programs
613 # Run !system commands directly, not through pipes, so terminal programs
613 # work correctly.
614 # work correctly.
614 system = InteractiveShell.system_raw
615 system = InteractiveShell.system_raw
615
616
616 def auto_rewrite_input(self, cmd):
617 def auto_rewrite_input(self, cmd):
617 """Overridden from the parent class to use fancy rewriting prompt"""
618 """Overridden from the parent class to use fancy rewriting prompt"""
618 if not self.show_rewritten_input:
619 if not self.show_rewritten_input:
619 return
620 return
620
621
621 tokens = self.prompts.rewrite_prompt_tokens()
622 tokens = self.prompts.rewrite_prompt_tokens()
622 if self.pt_app:
623 if self.pt_app:
623 print_formatted_text(PygmentsTokens(tokens), end='',
624 print_formatted_text(PygmentsTokens(tokens), end='',
624 style=self.pt_app.app.style)
625 style=self.pt_app.app.style)
625 print(cmd)
626 print(cmd)
626 else:
627 else:
627 prompt = ''.join(s for t, s in tokens)
628 prompt = ''.join(s for t, s in tokens)
628 print(prompt, cmd, sep='')
629 print(prompt, cmd, sep='')
629
630
630 _prompts_before = None
631 _prompts_before = None
631 def switch_doctest_mode(self, mode):
632 def switch_doctest_mode(self, mode):
632 """Switch prompts to classic for %doctest_mode"""
633 """Switch prompts to classic for %doctest_mode"""
633 if mode:
634 if mode:
634 self._prompts_before = self.prompts
635 self._prompts_before = self.prompts
635 self.prompts = ClassicPrompts(self)
636 self.prompts = ClassicPrompts(self)
636 elif self._prompts_before:
637 elif self._prompts_before:
637 self.prompts = self._prompts_before
638 self.prompts = self._prompts_before
638 self._prompts_before = None
639 self._prompts_before = None
639 # self._update_layout()
640 # self._update_layout()
640
641
641
642
642 InteractiveShellABC.register(TerminalInteractiveShell)
643 InteractiveShellABC.register(TerminalInteractiveShell)
643
644
644 if __name__ == '__main__':
645 if __name__ == '__main__':
645 TerminalInteractiveShell.instance().interact()
646 TerminalInteractiveShell.instance().interact()
General Comments 0
You need to be logged in to leave comments. Login now