Show More
@@ -1,630 +1,632 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Pdb debugger class. |
|
4 | 4 | |
|
5 | 5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
6 | 6 | the command line completion of other programs which include this isn't |
|
7 | 7 | damaged. |
|
8 | 8 | |
|
9 | 9 | In the future, this class will be expanded with improvements over the standard |
|
10 | 10 | pdb. |
|
11 | 11 | |
|
12 | 12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
13 | 13 | changes. Licensing should therefore be under the standard Python terms. For |
|
14 | 14 | details on the PSF (Python Software Foundation) standard license, see: |
|
15 | 15 | |
|
16 | 16 | http://www.python.org/2.2.3/license.html""" |
|
17 | 17 | |
|
18 | 18 | #***************************************************************************** |
|
19 | 19 | # |
|
20 | 20 | # This file is licensed under the PSF license. |
|
21 | 21 | # |
|
22 | 22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
23 | 23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
24 | 24 | # |
|
25 | 25 | # |
|
26 | 26 | #***************************************************************************** |
|
27 | 27 | from __future__ import print_function |
|
28 | 28 | |
|
29 | 29 | import bdb |
|
30 | 30 | import functools |
|
31 | 31 | import inspect |
|
32 | 32 | import sys |
|
33 | 33 | |
|
34 | 34 | from IPython import get_ipython |
|
35 | 35 | from IPython.utils import PyColorize, ulinecache |
|
36 | 36 | from IPython.utils import coloransi, py3compat |
|
37 | 37 | from IPython.core.excolors import exception_colors |
|
38 | 38 | from IPython.testing.skipdoctest import skip_doctest |
|
39 | 39 | |
|
40 | 40 | from prompt_toolkit import prompt as ptk_prompt |
|
41 | 41 | |
|
42 | 42 | prompt = 'ipdb> ' |
|
43 | 43 | |
|
44 | 44 | #We have to check this directly from sys.argv, config struct not yet available |
|
45 | 45 | from pdb import Pdb as OldPdb |
|
46 | 46 | |
|
47 | 47 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
48 | 48 | # it does so with some limitations. The rest of this support is implemented in |
|
49 | 49 | # the Tracer constructor. |
|
50 | 50 | |
|
51 | 51 | def make_arrow(pad): |
|
52 | 52 | """generate the leading arrow in front of traceback or debugger""" |
|
53 | 53 | if pad >= 2: |
|
54 | 54 | return '-'*(pad-2) + '> ' |
|
55 | 55 | elif pad == 1: |
|
56 | 56 | return '>' |
|
57 | 57 | return '' |
|
58 | 58 | |
|
59 | 59 | |
|
60 | 60 | def BdbQuit_excepthook(et, ev, tb, excepthook=None): |
|
61 | 61 | """Exception hook which handles `BdbQuit` exceptions. |
|
62 | 62 | |
|
63 | 63 | All other exceptions are processed using the `excepthook` |
|
64 | 64 | parameter. |
|
65 | 65 | """ |
|
66 | 66 | if et==bdb.BdbQuit: |
|
67 | 67 | print('Exiting Debugger.') |
|
68 | 68 | elif excepthook is not None: |
|
69 | 69 | excepthook(et, ev, tb) |
|
70 | 70 | else: |
|
71 | 71 | # Backwards compatibility. Raise deprecation warning? |
|
72 | 72 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
73 | 73 | |
|
74 | 74 | def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): |
|
75 | 75 | print('Exiting Debugger.') |
|
76 | 76 | |
|
77 | 77 | |
|
78 | 78 | class Tracer(object): |
|
79 | 79 | """Class for local debugging, similar to pdb.set_trace. |
|
80 | 80 | |
|
81 | 81 | Instances of this class, when called, behave like pdb.set_trace, but |
|
82 | 82 | providing IPython's enhanced capabilities. |
|
83 | 83 | |
|
84 | 84 | This is implemented as a class which must be initialized in your own code |
|
85 | 85 | and not as a standalone function because we need to detect at runtime |
|
86 | 86 | whether IPython is already active or not. That detection is done in the |
|
87 | 87 | constructor, ensuring that this code plays nicely with a running IPython, |
|
88 | 88 | while functioning acceptably (though with limitations) if outside of it. |
|
89 | 89 | """ |
|
90 | 90 | |
|
91 | 91 | @skip_doctest |
|
92 | 92 | def __init__(self, colors=None): |
|
93 | 93 | """Create a local debugger instance. |
|
94 | 94 | |
|
95 | 95 | Parameters |
|
96 | 96 | ---------- |
|
97 | 97 | |
|
98 | 98 | colors : str, optional |
|
99 | 99 | The name of the color scheme to use, it must be one of IPython's |
|
100 | 100 | valid color schemes. If not given, the function will default to |
|
101 | 101 | the current IPython scheme when running inside IPython, and to |
|
102 | 102 | 'NoColor' otherwise. |
|
103 | 103 | |
|
104 | 104 | Examples |
|
105 | 105 | -------- |
|
106 | 106 | :: |
|
107 | 107 | |
|
108 | 108 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
109 | 109 | |
|
110 | 110 | Later in your code:: |
|
111 | 111 | |
|
112 | 112 | debug_here() # -> will open up the debugger at that point. |
|
113 | 113 | |
|
114 | 114 | Once the debugger activates, you can use all of its regular commands to |
|
115 | 115 | step through code, set breakpoints, etc. See the pdb documentation |
|
116 | 116 | from the Python standard library for usage details. |
|
117 | 117 | """ |
|
118 | 118 | |
|
119 | 119 | ip = get_ipython() |
|
120 | 120 | if ip is None: |
|
121 | 121 | # Outside of ipython, we set our own exception hook manually |
|
122 | 122 | sys.excepthook = functools.partial(BdbQuit_excepthook, |
|
123 | 123 | excepthook=sys.excepthook) |
|
124 | 124 | def_colors = 'NoColor' |
|
125 | 125 | else: |
|
126 | 126 | # In ipython, we use its custom exception handler mechanism |
|
127 | 127 | def_colors = ip.colors |
|
128 | 128 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) |
|
129 | 129 | |
|
130 | 130 | if colors is None: |
|
131 | 131 | colors = def_colors |
|
132 | 132 | |
|
133 | 133 | # The stdlib debugger internally uses a modified repr from the `repr` |
|
134 | 134 | # module, that limits the length of printed strings to a hardcoded |
|
135 | 135 | # limit of 30 characters. That much trimming is too aggressive, let's |
|
136 | 136 | # at least raise that limit to 80 chars, which should be enough for |
|
137 | 137 | # most interactive uses. |
|
138 | 138 | try: |
|
139 | 139 | try: |
|
140 | 140 | from reprlib import aRepr # Py 3 |
|
141 | 141 | except ImportError: |
|
142 | 142 | from repr import aRepr # Py 2 |
|
143 | 143 | aRepr.maxstring = 80 |
|
144 | 144 | except: |
|
145 | 145 | # This is only a user-facing convenience, so any error we encounter |
|
146 | 146 | # here can be warned about but can be otherwise ignored. These |
|
147 | 147 | # printouts will tell us about problems if this API changes |
|
148 | 148 | import traceback |
|
149 | 149 | traceback.print_exc() |
|
150 | 150 | |
|
151 | 151 | self.debugger = Pdb(colors) |
|
152 | 152 | |
|
153 | 153 | def __call__(self): |
|
154 | 154 | """Starts an interactive debugger at the point where called. |
|
155 | 155 | |
|
156 | 156 | This is similar to the pdb.set_trace() function from the std lib, but |
|
157 | 157 | using IPython's enhanced debugger.""" |
|
158 | 158 | |
|
159 | 159 | self.debugger.set_trace(sys._getframe().f_back) |
|
160 | 160 | |
|
161 | 161 | |
|
162 | 162 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
163 | 163 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
164 | 164 | for the ``do_...`` commands that hook into the help system. |
|
165 | 165 | Adapted from from a comp.lang.python posting |
|
166 | 166 | by Duncan Booth.""" |
|
167 | 167 | def wrapper(*args, **kw): |
|
168 | 168 | return new_fn(*args, **kw) |
|
169 | 169 | if old_fn.__doc__: |
|
170 | 170 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
171 | 171 | return wrapper |
|
172 | 172 | |
|
173 | 173 | |
|
174 | 174 | def _file_lines(fname): |
|
175 | 175 | """Return the contents of a named file as a list of lines. |
|
176 | 176 | |
|
177 | 177 | This function never raises an IOError exception: if the file can't be |
|
178 | 178 | read, it simply returns an empty list.""" |
|
179 | 179 | |
|
180 | 180 | try: |
|
181 | 181 | outfile = open(fname) |
|
182 | 182 | except IOError: |
|
183 | 183 | return [] |
|
184 | 184 | else: |
|
185 | 185 | out = outfile.readlines() |
|
186 | 186 | outfile.close() |
|
187 | 187 | return out |
|
188 | 188 | |
|
189 | 189 | |
|
190 | 190 | class Pdb(OldPdb, object): |
|
191 | 191 | """Modified Pdb class, does not load readline.""" |
|
192 | 192 | |
|
193 | 193 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
194 | 194 | stdin=None, stdout=None, context=5): |
|
195 | 195 | |
|
196 | 196 | # Parent constructor: |
|
197 | 197 | try: |
|
198 | 198 | self.context=int(context) |
|
199 | 199 | if self.context <= 0: |
|
200 | 200 | raise ValueError("Context must be a positive integer") |
|
201 | 201 | except (TypeError, ValueError): |
|
202 | 202 | raise ValueError("Context must be a positive integer") |
|
203 | 203 | |
|
204 | 204 | OldPdb.__init__(self,completekey,stdin,stdout) |
|
205 | 205 | |
|
206 | 206 | # IPython changes... |
|
207 | 207 | self.shell = get_ipython() |
|
208 | 208 | |
|
209 | 209 | if self.shell is None: |
|
210 | 210 | # No IPython instance running, we must create one |
|
211 | 211 | from IPython.terminal.interactiveshell import \ |
|
212 | 212 | TerminalInteractiveShell |
|
213 | 213 | self.shell = TerminalInteractiveShell.instance() |
|
214 | 214 | |
|
215 | 215 | # This is icky, but I'm not currently sure how best to test if we're |
|
216 | 216 | # in a terminal shell using prompt_toolkit |
|
217 | 217 | self.use_prompt_toolkit = hasattr(self.shell, 'pt_cli') |
|
218 | 218 | |
|
219 | 219 | self.aliases = {} |
|
220 | 220 | |
|
221 | 221 | # Create color table: we copy the default one from the traceback |
|
222 | 222 | # module and add a few attributes needed for debugging |
|
223 | 223 | self.color_scheme_table = exception_colors() |
|
224 | 224 | |
|
225 | 225 | # shorthands |
|
226 | 226 | C = coloransi.TermColors |
|
227 | 227 | cst = self.color_scheme_table |
|
228 | 228 | |
|
229 | 229 | cst['NoColor'].colors.prompt = C.NoColor |
|
230 | 230 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
231 | 231 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
232 | 232 | |
|
233 | 233 | cst['Linux'].colors.prompt = C.Green |
|
234 | 234 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
235 | 235 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
236 | 236 | |
|
237 | 237 | cst['LightBG'].colors.prompt = C.Blue |
|
238 | 238 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
239 | 239 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
240 | 240 | |
|
241 | 241 | self.set_colors(color_scheme) |
|
242 | 242 | |
|
243 | 243 | # Add a python parser so we can syntax highlight source while |
|
244 | 244 | # debugging. |
|
245 | 245 | self.parser = PyColorize.Parser() |
|
246 | 246 | |
|
247 | 247 | # Set the prompt - the default prompt is '(Pdb)' |
|
248 | 248 | self.prompt = prompt |
|
249 | 249 | |
|
250 | 250 | |
|
251 | 251 | def cmdloop(self, intro=None): |
|
252 | 252 | """Repeatedly issue a prompt, accept input, parse an initial prefix |
|
253 | 253 | off the received input, and dispatch to action methods, passing them |
|
254 | 254 | the remainder of the line as argument. |
|
255 | 255 | |
|
256 | 256 | override the same methods from cmd.Cmd to provide prompt toolkit replacement. |
|
257 | 257 | """ |
|
258 | 258 | if not self.use_prompt_toolkit: |
|
259 | 259 | return OldPdb.cmdloop(self, intro) |
|
260 | 260 | |
|
261 | 261 | if not self.use_rawinput: |
|
262 | 262 | raise ValueError('Sorry ipdb does not support raw_input=False') |
|
263 | 263 | |
|
264 | 264 | def get_prompt_tokens(cli): |
|
265 | 265 | from pygments.token import Token |
|
266 | 266 | return [(Token.Prompt, self.prompt)] |
|
267 | 267 | |
|
268 | 268 | self.preloop() |
|
269 | 269 | try: |
|
270 | 270 | if intro is not None: |
|
271 | 271 | self.intro = intro |
|
272 | 272 | if self.intro: |
|
273 | 273 | self.stdout.write(str(self.intro)+"\n") |
|
274 | 274 | stop = None |
|
275 | 275 | while not stop: |
|
276 | 276 | if self.cmdqueue: |
|
277 | 277 | line = self.cmdqueue.pop(0) |
|
278 | 278 | else: |
|
279 | 279 | try: |
|
280 |
line = ptk_prompt(get_prompt_tokens=get_prompt_tokens |
|
|
280 | line = ptk_prompt(get_prompt_tokens=get_prompt_tokens, | |
|
281 | history=self.shell.debugger_history, | |
|
282 | ) | |
|
281 | 283 | except EOFError: |
|
282 | 284 | line = 'EOF' |
|
283 | 285 | line = self.precmd(line) |
|
284 | 286 | stop = self.onecmd(line) |
|
285 | 287 | stop = self.postcmd(stop, line) |
|
286 | 288 | self.postloop() |
|
287 | 289 | except Exception: |
|
288 | 290 | pass |
|
289 | 291 | |
|
290 | 292 | |
|
291 | 293 | |
|
292 | 294 | def set_colors(self, scheme): |
|
293 | 295 | """Shorthand access to the color table scheme selector method.""" |
|
294 | 296 | self.color_scheme_table.set_active_scheme(scheme) |
|
295 | 297 | |
|
296 | 298 | def interaction(self, frame, traceback): |
|
297 | 299 | try: |
|
298 | 300 | OldPdb.interaction(self, frame, traceback) |
|
299 | 301 | except KeyboardInterrupt: |
|
300 | 302 | sys.stdout.write('\n' + self.shell.get_exception_only()) |
|
301 | 303 | |
|
302 | 304 | def parseline(self, line): |
|
303 | 305 | if line.startswith("!!"): |
|
304 | 306 | # Force standard behavior. |
|
305 | 307 | return super(Pdb, self).parseline(line[2:]) |
|
306 | 308 | # "Smart command mode" from pdb++: don't execute commands if a variable |
|
307 | 309 | # with the same name exists. |
|
308 | 310 | cmd, arg, newline = super(Pdb, self).parseline(line) |
|
309 | 311 | if cmd in self.curframe.f_globals or cmd in self.curframe.f_locals: |
|
310 | 312 | return super(Pdb, self).parseline("!" + line) |
|
311 | 313 | return super(Pdb, self).parseline(line) |
|
312 | 314 | |
|
313 | 315 | def new_do_up(self, arg): |
|
314 | 316 | OldPdb.do_up(self, arg) |
|
315 | 317 | self.shell.set_completer_frame(self.curframe) |
|
316 | 318 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
317 | 319 | |
|
318 | 320 | def new_do_down(self, arg): |
|
319 | 321 | OldPdb.do_down(self, arg) |
|
320 | 322 | self.shell.set_completer_frame(self.curframe) |
|
321 | 323 | |
|
322 | 324 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
323 | 325 | |
|
324 | 326 | def new_do_frame(self, arg): |
|
325 | 327 | OldPdb.do_frame(self, arg) |
|
326 | 328 | self.shell.set_completer_frame(self.curframe) |
|
327 | 329 | |
|
328 | 330 | def new_do_quit(self, arg): |
|
329 | 331 | |
|
330 | 332 | if hasattr(self, 'old_all_completions'): |
|
331 | 333 | self.shell.Completer.all_completions=self.old_all_completions |
|
332 | 334 | |
|
333 | 335 | return OldPdb.do_quit(self, arg) |
|
334 | 336 | |
|
335 | 337 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
336 | 338 | |
|
337 | 339 | def new_do_restart(self, arg): |
|
338 | 340 | """Restart command. In the context of ipython this is exactly the same |
|
339 | 341 | thing as 'quit'.""" |
|
340 | 342 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
341 | 343 | return self.do_quit(arg) |
|
342 | 344 | |
|
343 | 345 | def postloop(self): |
|
344 | 346 | self.shell.set_completer_frame(None) |
|
345 | 347 | |
|
346 | 348 | def print_stack_trace(self, context=None): |
|
347 | 349 | if context is None: |
|
348 | 350 | context = self.context |
|
349 | 351 | try: |
|
350 | 352 | context=int(context) |
|
351 | 353 | if context <= 0: |
|
352 | 354 | raise ValueError("Context must be a positive integer") |
|
353 | 355 | except (TypeError, ValueError): |
|
354 | 356 | raise ValueError("Context must be a positive integer") |
|
355 | 357 | try: |
|
356 | 358 | for frame_lineno in self.stack: |
|
357 | 359 | self.print_stack_entry(frame_lineno, context=context) |
|
358 | 360 | except KeyboardInterrupt: |
|
359 | 361 | pass |
|
360 | 362 | |
|
361 | 363 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
362 | 364 | context=None): |
|
363 | 365 | if context is None: |
|
364 | 366 | context = self.context |
|
365 | 367 | try: |
|
366 | 368 | context=int(context) |
|
367 | 369 | if context <= 0: |
|
368 | 370 | raise ValueError("Context must be a positive integer") |
|
369 | 371 | except (TypeError, ValueError): |
|
370 | 372 | raise ValueError("Context must be a positive integer") |
|
371 | 373 | print(self.format_stack_entry(frame_lineno, '', context)) |
|
372 | 374 | |
|
373 | 375 | # vds: >> |
|
374 | 376 | frame, lineno = frame_lineno |
|
375 | 377 | filename = frame.f_code.co_filename |
|
376 | 378 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
377 | 379 | # vds: << |
|
378 | 380 | |
|
379 | 381 | def format_stack_entry(self, frame_lineno, lprefix=': ', context=None): |
|
380 | 382 | if context is None: |
|
381 | 383 | context = self.context |
|
382 | 384 | try: |
|
383 | 385 | context=int(context) |
|
384 | 386 | if context <= 0: |
|
385 | 387 | print("Context must be a positive integer") |
|
386 | 388 | except (TypeError, ValueError): |
|
387 | 389 | print("Context must be a positive integer") |
|
388 | 390 | try: |
|
389 | 391 | import reprlib # Py 3 |
|
390 | 392 | except ImportError: |
|
391 | 393 | import repr as reprlib # Py 2 |
|
392 | 394 | |
|
393 | 395 | ret = [] |
|
394 | 396 | |
|
395 | 397 | Colors = self.color_scheme_table.active_colors |
|
396 | 398 | ColorsNormal = Colors.Normal |
|
397 | 399 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
398 | 400 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
399 | 401 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
400 | 402 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
401 | 403 | ColorsNormal) |
|
402 | 404 | |
|
403 | 405 | frame, lineno = frame_lineno |
|
404 | 406 | |
|
405 | 407 | return_value = '' |
|
406 | 408 | if '__return__' in frame.f_locals: |
|
407 | 409 | rv = frame.f_locals['__return__'] |
|
408 | 410 | #return_value += '->' |
|
409 | 411 | return_value += reprlib.repr(rv) + '\n' |
|
410 | 412 | ret.append(return_value) |
|
411 | 413 | |
|
412 | 414 | #s = filename + '(' + `lineno` + ')' |
|
413 | 415 | filename = self.canonic(frame.f_code.co_filename) |
|
414 | 416 | link = tpl_link % py3compat.cast_unicode(filename) |
|
415 | 417 | |
|
416 | 418 | if frame.f_code.co_name: |
|
417 | 419 | func = frame.f_code.co_name |
|
418 | 420 | else: |
|
419 | 421 | func = "<lambda>" |
|
420 | 422 | |
|
421 | 423 | call = '' |
|
422 | 424 | if func != '?': |
|
423 | 425 | if '__args__' in frame.f_locals: |
|
424 | 426 | args = reprlib.repr(frame.f_locals['__args__']) |
|
425 | 427 | else: |
|
426 | 428 | args = '()' |
|
427 | 429 | call = tpl_call % (func, args) |
|
428 | 430 | |
|
429 | 431 | # The level info should be generated in the same format pdb uses, to |
|
430 | 432 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
431 | 433 | if frame is self.curframe: |
|
432 | 434 | ret.append('> ') |
|
433 | 435 | else: |
|
434 | 436 | ret.append(' ') |
|
435 | 437 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) |
|
436 | 438 | |
|
437 | 439 | start = lineno - 1 - context//2 |
|
438 | 440 | lines = ulinecache.getlines(filename) |
|
439 | 441 | start = min(start, len(lines) - context) |
|
440 | 442 | start = max(start, 0) |
|
441 | 443 | lines = lines[start : start + context] |
|
442 | 444 | |
|
443 | 445 | for i,line in enumerate(lines): |
|
444 | 446 | show_arrow = (start + 1 + i == lineno) |
|
445 | 447 | linetpl = (frame is self.curframe or show_arrow) \ |
|
446 | 448 | and tpl_line_em \ |
|
447 | 449 | or tpl_line |
|
448 | 450 | ret.append(self.__format_line(linetpl, filename, |
|
449 | 451 | start + 1 + i, line, |
|
450 | 452 | arrow = show_arrow) ) |
|
451 | 453 | return ''.join(ret) |
|
452 | 454 | |
|
453 | 455 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
454 | 456 | bp_mark = "" |
|
455 | 457 | bp_mark_color = "" |
|
456 | 458 | |
|
457 | 459 | scheme = self.color_scheme_table.active_scheme_name |
|
458 | 460 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
459 | 461 | if not err: line = new_line |
|
460 | 462 | |
|
461 | 463 | bp = None |
|
462 | 464 | if lineno in self.get_file_breaks(filename): |
|
463 | 465 | bps = self.get_breaks(filename, lineno) |
|
464 | 466 | bp = bps[-1] |
|
465 | 467 | |
|
466 | 468 | if bp: |
|
467 | 469 | Colors = self.color_scheme_table.active_colors |
|
468 | 470 | bp_mark = str(bp.number) |
|
469 | 471 | bp_mark_color = Colors.breakpoint_enabled |
|
470 | 472 | if not bp.enabled: |
|
471 | 473 | bp_mark_color = Colors.breakpoint_disabled |
|
472 | 474 | |
|
473 | 475 | numbers_width = 7 |
|
474 | 476 | if arrow: |
|
475 | 477 | # This is the line with the error |
|
476 | 478 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
477 | 479 | num = '%s%s' % (make_arrow(pad), str(lineno)) |
|
478 | 480 | else: |
|
479 | 481 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
480 | 482 | |
|
481 | 483 | return tpl_line % (bp_mark_color + bp_mark, num, line) |
|
482 | 484 | |
|
483 | 485 | |
|
484 | 486 | def print_list_lines(self, filename, first, last): |
|
485 | 487 | """The printing (as opposed to the parsing part of a 'list' |
|
486 | 488 | command.""" |
|
487 | 489 | try: |
|
488 | 490 | Colors = self.color_scheme_table.active_colors |
|
489 | 491 | ColorsNormal = Colors.Normal |
|
490 | 492 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
491 | 493 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
492 | 494 | src = [] |
|
493 | 495 | if filename == "<string>" and hasattr(self, "_exec_filename"): |
|
494 | 496 | filename = self._exec_filename |
|
495 | 497 | |
|
496 | 498 | for lineno in range(first, last+1): |
|
497 | 499 | line = ulinecache.getline(filename, lineno) |
|
498 | 500 | if not line: |
|
499 | 501 | break |
|
500 | 502 | |
|
501 | 503 | if lineno == self.curframe.f_lineno: |
|
502 | 504 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
503 | 505 | else: |
|
504 | 506 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
505 | 507 | |
|
506 | 508 | src.append(line) |
|
507 | 509 | self.lineno = lineno |
|
508 | 510 | |
|
509 | 511 | print(''.join(src)) |
|
510 | 512 | |
|
511 | 513 | except KeyboardInterrupt: |
|
512 | 514 | pass |
|
513 | 515 | |
|
514 | 516 | def do_list(self, arg): |
|
515 | 517 | self.lastcmd = 'list' |
|
516 | 518 | last = None |
|
517 | 519 | if arg: |
|
518 | 520 | try: |
|
519 | 521 | x = eval(arg, {}, {}) |
|
520 | 522 | if type(x) == type(()): |
|
521 | 523 | first, last = x |
|
522 | 524 | first = int(first) |
|
523 | 525 | last = int(last) |
|
524 | 526 | if last < first: |
|
525 | 527 | # Assume it's a count |
|
526 | 528 | last = first + last |
|
527 | 529 | else: |
|
528 | 530 | first = max(1, int(x) - 5) |
|
529 | 531 | except: |
|
530 | 532 | print('*** Error in argument:', repr(arg)) |
|
531 | 533 | return |
|
532 | 534 | elif self.lineno is None: |
|
533 | 535 | first = max(1, self.curframe.f_lineno - 5) |
|
534 | 536 | else: |
|
535 | 537 | first = self.lineno + 1 |
|
536 | 538 | if last is None: |
|
537 | 539 | last = first + 10 |
|
538 | 540 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
539 | 541 | |
|
540 | 542 | # vds: >> |
|
541 | 543 | lineno = first |
|
542 | 544 | filename = self.curframe.f_code.co_filename |
|
543 | 545 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
544 | 546 | # vds: << |
|
545 | 547 | |
|
546 | 548 | do_l = do_list |
|
547 | 549 | |
|
548 | 550 | def getsourcelines(self, obj): |
|
549 | 551 | lines, lineno = inspect.findsource(obj) |
|
550 | 552 | if inspect.isframe(obj) and obj.f_globals is obj.f_locals: |
|
551 | 553 | # must be a module frame: do not try to cut a block out of it |
|
552 | 554 | return lines, 1 |
|
553 | 555 | elif inspect.ismodule(obj): |
|
554 | 556 | return lines, 1 |
|
555 | 557 | return inspect.getblock(lines[lineno:]), lineno+1 |
|
556 | 558 | |
|
557 | 559 | def do_longlist(self, arg): |
|
558 | 560 | self.lastcmd = 'longlist' |
|
559 | 561 | try: |
|
560 | 562 | lines, lineno = self.getsourcelines(self.curframe) |
|
561 | 563 | except OSError as err: |
|
562 | 564 | self.error(err) |
|
563 | 565 | return |
|
564 | 566 | last = lineno + len(lines) |
|
565 | 567 | self.print_list_lines(self.curframe.f_code.co_filename, lineno, last) |
|
566 | 568 | do_ll = do_longlist |
|
567 | 569 | |
|
568 | 570 | def do_pdef(self, arg): |
|
569 | 571 | """Print the call signature for any callable object. |
|
570 | 572 | |
|
571 | 573 | The debugger interface to %pdef""" |
|
572 | 574 | namespaces = [('Locals', self.curframe.f_locals), |
|
573 | 575 | ('Globals', self.curframe.f_globals)] |
|
574 | 576 | self.shell.find_line_magic('pdef')(arg, namespaces=namespaces) |
|
575 | 577 | |
|
576 | 578 | def do_pdoc(self, arg): |
|
577 | 579 | """Print the docstring for an object. |
|
578 | 580 | |
|
579 | 581 | The debugger interface to %pdoc.""" |
|
580 | 582 | namespaces = [('Locals', self.curframe.f_locals), |
|
581 | 583 | ('Globals', self.curframe.f_globals)] |
|
582 | 584 | self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces) |
|
583 | 585 | |
|
584 | 586 | def do_pfile(self, arg): |
|
585 | 587 | """Print (or run through pager) the file where an object is defined. |
|
586 | 588 | |
|
587 | 589 | The debugger interface to %pfile. |
|
588 | 590 | """ |
|
589 | 591 | namespaces = [('Locals', self.curframe.f_locals), |
|
590 | 592 | ('Globals', self.curframe.f_globals)] |
|
591 | 593 | self.shell.find_line_magic('pfile')(arg, namespaces=namespaces) |
|
592 | 594 | |
|
593 | 595 | def do_pinfo(self, arg): |
|
594 | 596 | """Provide detailed information about an object. |
|
595 | 597 | |
|
596 | 598 | The debugger interface to %pinfo, i.e., obj?.""" |
|
597 | 599 | namespaces = [('Locals', self.curframe.f_locals), |
|
598 | 600 | ('Globals', self.curframe.f_globals)] |
|
599 | 601 | self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces) |
|
600 | 602 | |
|
601 | 603 | def do_pinfo2(self, arg): |
|
602 | 604 | """Provide extra detailed information about an object. |
|
603 | 605 | |
|
604 | 606 | The debugger interface to %pinfo2, i.e., obj??.""" |
|
605 | 607 | namespaces = [('Locals', self.curframe.f_locals), |
|
606 | 608 | ('Globals', self.curframe.f_globals)] |
|
607 | 609 | self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces) |
|
608 | 610 | |
|
609 | 611 | def do_psource(self, arg): |
|
610 | 612 | """Print (or run through pager) the source code for an object.""" |
|
611 | 613 | namespaces = [('Locals', self.curframe.f_locals), |
|
612 | 614 | ('Globals', self.curframe.f_globals)] |
|
613 | 615 | self.shell.find_line_magic('psource')(arg, namespaces=namespaces) |
|
614 | 616 | |
|
615 | 617 | if sys.version_info > (3, ): |
|
616 | 618 | def do_where(self, arg): |
|
617 | 619 | """w(here) |
|
618 | 620 | Print a stack trace, with the most recent frame at the bottom. |
|
619 | 621 | An arrow indicates the "current frame", which determines the |
|
620 | 622 | context of most commands. 'bt' is an alias for this command. |
|
621 | 623 | |
|
622 | 624 | Take a number as argument as an (optional) number of context line to |
|
623 | 625 | print""" |
|
624 | 626 | if arg: |
|
625 | 627 | context = int(arg) |
|
626 | 628 | self.print_stack_trace(context) |
|
627 | 629 | else: |
|
628 | 630 | self.print_stack_trace() |
|
629 | 631 | |
|
630 | 632 | do_w = do_where |
@@ -1,481 +1,484 b'' | |||
|
1 | 1 | """IPython terminal interface using prompt_toolkit in place of readline""" |
|
2 | 2 | from __future__ import print_function |
|
3 | 3 | |
|
4 | 4 | import os |
|
5 | 5 | import sys |
|
6 | 6 | import signal |
|
7 | 7 | import unicodedata |
|
8 | 8 | from warnings import warn |
|
9 | 9 | from wcwidth import wcwidth |
|
10 | 10 | |
|
11 | 11 | from IPython.core.error import TryNext |
|
12 | 12 | from IPython.core.interactiveshell import InteractiveShell |
|
13 | 13 | from IPython.utils.py3compat import PY3, cast_unicode_py2, input |
|
14 | 14 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
15 | 15 | from IPython.utils.process import abbrev_cwd |
|
16 | 16 | from traitlets import Bool, Unicode, Dict, Integer, observe |
|
17 | 17 | |
|
18 | 18 | from prompt_toolkit.completion import Completer, Completion |
|
19 | 19 | from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode |
|
20 | 20 | from prompt_toolkit.filters import HasFocus, HasSelection, Condition, ViInsertMode, EmacsInsertMode, IsDone |
|
21 | 21 | from prompt_toolkit.history import InMemoryHistory |
|
22 | 22 | from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout |
|
23 | 23 | from prompt_toolkit.interface import CommandLineInterface |
|
24 | 24 | from prompt_toolkit.key_binding.manager import KeyBindingManager |
|
25 | 25 | from prompt_toolkit.keys import Keys |
|
26 | 26 | from prompt_toolkit.layout.lexers import Lexer |
|
27 | 27 | from prompt_toolkit.layout.lexers import PygmentsLexer |
|
28 | 28 | from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor |
|
29 | 29 | from prompt_toolkit.styles import PygmentsStyle, DynamicStyle |
|
30 | 30 | |
|
31 | 31 | from pygments.styles import get_style_by_name, get_all_styles |
|
32 | 32 | from pygments.lexers import Python3Lexer, BashLexer, PythonLexer |
|
33 | 33 | from pygments.token import Token |
|
34 | 34 | |
|
35 | 35 | from .pt_inputhooks import get_inputhook_func |
|
36 | 36 | from .interactiveshell import get_default_editor, TerminalMagics |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | class IPythonPTCompleter(Completer): |
|
40 | 40 | """Adaptor to provide IPython completions to prompt_toolkit""" |
|
41 | 41 | def __init__(self, ipy_completer): |
|
42 | 42 | self.ipy_completer = ipy_completer |
|
43 | 43 | |
|
44 | 44 | def get_completions(self, document, complete_event): |
|
45 | 45 | if not document.current_line.strip(): |
|
46 | 46 | return |
|
47 | 47 | |
|
48 | 48 | used, matches = self.ipy_completer.complete( |
|
49 | 49 | line_buffer=document.current_line, |
|
50 | 50 | cursor_pos=document.cursor_position_col |
|
51 | 51 | ) |
|
52 | 52 | start_pos = -len(used) |
|
53 | 53 | for m in matches: |
|
54 | 54 | m = unicodedata.normalize('NFC', m) |
|
55 | 55 | |
|
56 | 56 | # When the first character of the completion has a zero length, |
|
57 | 57 | # then it's probably a decomposed unicode character. E.g. caused by |
|
58 | 58 | # the "\dot" completion. Try to compose again with the previous |
|
59 | 59 | # character. |
|
60 | 60 | if wcwidth(m[0]) == 0: |
|
61 | 61 | if document.cursor_position + start_pos > 0: |
|
62 | 62 | char_before = document.text[document.cursor_position + start_pos - 1] |
|
63 | 63 | m = unicodedata.normalize('NFC', char_before + m) |
|
64 | 64 | |
|
65 | 65 | # Yield the modified completion instead, if this worked. |
|
66 | 66 | if wcwidth(m[0:1]) == 1: |
|
67 | 67 | yield Completion(m, start_position=start_pos - 1) |
|
68 | 68 | continue |
|
69 | 69 | |
|
70 | 70 | # TODO: Use Jedi to determine meta_text |
|
71 | 71 | # (Jedi currently has a bug that results in incorrect information.) |
|
72 | 72 | # meta_text = '' |
|
73 | 73 | # yield Completion(m, start_position=start_pos, |
|
74 | 74 | # display_meta=meta_text) |
|
75 | 75 | yield Completion(m, start_position=start_pos) |
|
76 | 76 | |
|
77 | 77 | class IPythonPTLexer(Lexer): |
|
78 | 78 | """ |
|
79 | 79 | Wrapper around PythonLexer and BashLexer. |
|
80 | 80 | """ |
|
81 | 81 | def __init__(self): |
|
82 | 82 | self.python_lexer = PygmentsLexer(Python3Lexer if PY3 else PythonLexer) |
|
83 | 83 | self.shell_lexer = PygmentsLexer(BashLexer) |
|
84 | 84 | |
|
85 | 85 | def lex_document(self, cli, document): |
|
86 | 86 | if document.text.startswith('!'): |
|
87 | 87 | return self.shell_lexer.lex_document(cli, document) |
|
88 | 88 | else: |
|
89 | 89 | return self.python_lexer.lex_document(cli, document) |
|
90 | 90 | |
|
91 | 91 | |
|
92 | 92 | class TerminalInteractiveShell(InteractiveShell): |
|
93 | 93 | colors_force = True |
|
94 | 94 | |
|
95 | 95 | space_for_menu = Integer(6, help='Number of line at the bottom of the screen ' |
|
96 | 96 | 'to reserve for the completion menu' |
|
97 | 97 | ).tag(config=True) |
|
98 | 98 | |
|
99 | 99 | def _space_for_menu_changed(self, old, new): |
|
100 | 100 | self._update_layout() |
|
101 | 101 | |
|
102 | 102 | pt_cli = None |
|
103 | debugger_history = None | |
|
103 | 104 | |
|
104 | 105 | autoedit_syntax = Bool(False, |
|
105 | 106 | help="auto editing of files with syntax errors.", |
|
106 | 107 | ).tag(config=True) |
|
107 | 108 | |
|
108 | 109 | |
|
109 | 110 | confirm_exit = Bool(True, |
|
110 | 111 | help=""" |
|
111 | 112 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
112 | 113 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
113 | 114 | you can force a direct exit without any confirmation.""", |
|
114 | 115 | ).tag(config=True) |
|
115 | 116 | |
|
116 | 117 | editing_mode = Unicode('emacs', |
|
117 | 118 | help="Shortcut style to use at the prompt. 'vi' or 'emacs'.", |
|
118 | 119 | ).tag(config=True) |
|
119 | 120 | |
|
120 | 121 | mouse_support = Bool(False, |
|
121 | 122 | help="Enable mouse support in the prompt" |
|
122 | 123 | ).tag(config=True) |
|
123 | 124 | |
|
124 | 125 | highlighting_style = Unicode('default', |
|
125 | 126 | help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles()) |
|
126 | 127 | ).tag(config=True) |
|
127 | 128 | |
|
128 | 129 | |
|
129 | 130 | @observe('highlighting_style') |
|
130 | 131 | def _highlighting_style_changed(self, change): |
|
131 | 132 | self._style = self._make_style_from_name(self.highlighting_style) |
|
132 | 133 | |
|
133 | 134 | highlighting_style_overrides = Dict( |
|
134 | 135 | help="Override highlighting format for specific tokens" |
|
135 | 136 | ).tag(config=True) |
|
136 | 137 | |
|
137 | 138 | editor = Unicode(get_default_editor(), |
|
138 | 139 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
139 | 140 | ).tag(config=True) |
|
140 | 141 | |
|
141 | 142 | term_title = Bool(True, |
|
142 | 143 | help="Automatically set the terminal title" |
|
143 | 144 | ).tag(config=True) |
|
144 | 145 | |
|
145 | 146 | display_completions_in_columns = Bool(False, |
|
146 | 147 | help="Display a multi column completion menu.", |
|
147 | 148 | ).tag(config=True) |
|
148 | 149 | |
|
149 | 150 | highlight_matching_brackets = Bool(True, |
|
150 | 151 | help="Highlight matching brackets .", |
|
151 | 152 | ).tag(config=True) |
|
152 | 153 | |
|
153 | 154 | @observe('term_title') |
|
154 | 155 | def init_term_title(self, change=None): |
|
155 | 156 | # Enable or disable the terminal title. |
|
156 | 157 | if self.term_title: |
|
157 | 158 | toggle_set_term_title(True) |
|
158 | 159 | set_term_title('IPython: ' + abbrev_cwd()) |
|
159 | 160 | else: |
|
160 | 161 | toggle_set_term_title(False) |
|
161 | 162 | |
|
162 | 163 | def get_prompt_tokens(self, cli): |
|
163 | 164 | return [ |
|
164 | 165 | (Token.Prompt, 'In ['), |
|
165 | 166 | (Token.PromptNum, str(self.execution_count)), |
|
166 | 167 | (Token.Prompt, ']: '), |
|
167 | 168 | ] |
|
168 | 169 | |
|
169 | 170 | def get_continuation_tokens(self, cli, width): |
|
170 | 171 | return [ |
|
171 | 172 | (Token.Prompt, (' ' * (width - 5)) + '...: '), |
|
172 | 173 | ] |
|
173 | 174 | |
|
174 | 175 | def init_prompt_toolkit_cli(self): |
|
175 | 176 | if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty(): |
|
176 | 177 | # Fall back to plain non-interactive output for tests. |
|
177 | 178 | # This is very limited, and only accepts a single line. |
|
178 | 179 | def prompt(): |
|
179 | 180 | return cast_unicode_py2(input('In [%d]: ' % self.execution_count)) |
|
180 | 181 | self.prompt_for_code = prompt |
|
181 | 182 | return |
|
182 | 183 | |
|
183 | 184 | kbmanager = KeyBindingManager.for_prompt() |
|
184 | 185 | insert_mode = ViInsertMode() | EmacsInsertMode() |
|
185 | 186 | # Ctrl+J == Enter, seemingly |
|
186 | 187 | @kbmanager.registry.add_binding(Keys.ControlJ, |
|
187 | 188 | filter=(HasFocus(DEFAULT_BUFFER) |
|
188 | 189 | & ~HasSelection() |
|
189 | 190 | & insert_mode |
|
190 | 191 | )) |
|
191 | 192 | def _(event): |
|
192 | 193 | b = event.current_buffer |
|
193 | 194 | d = b.document |
|
194 | 195 | if not (d.on_last_line or d.cursor_position_row >= d.line_count |
|
195 | 196 | - d.empty_line_count_at_the_end()): |
|
196 | 197 | b.newline() |
|
197 | 198 | return |
|
198 | 199 | |
|
199 | 200 | status, indent = self.input_splitter.check_complete(d.text) |
|
200 | 201 | |
|
201 | 202 | if (status != 'incomplete') and b.accept_action.is_returnable: |
|
202 | 203 | b.accept_action.validate_and_handle(event.cli, b) |
|
203 | 204 | else: |
|
204 | 205 | b.insert_text('\n' + (' ' * (indent or 0))) |
|
205 | 206 | |
|
206 | 207 | @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) |
|
207 | 208 | def _reset_buffer(event): |
|
208 | 209 | event.current_buffer.reset() |
|
209 | 210 | |
|
210 | 211 | @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)) |
|
211 | 212 | def _reset_search_buffer(event): |
|
212 | 213 | if event.current_buffer.document.text: |
|
213 | 214 | event.current_buffer.reset() |
|
214 | 215 | else: |
|
215 | 216 | event.cli.push_focus(DEFAULT_BUFFER) |
|
216 | 217 | |
|
217 | 218 | supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) |
|
218 | 219 | |
|
219 | 220 | @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend) |
|
220 | 221 | def _suspend_to_bg(event): |
|
221 | 222 | event.cli.suspend_to_background() |
|
222 | 223 | |
|
223 | 224 | @Condition |
|
224 | 225 | def cursor_in_leading_ws(cli): |
|
225 | 226 | before = cli.application.buffer.document.current_line_before_cursor |
|
226 | 227 | return (not before) or before.isspace() |
|
227 | 228 | |
|
228 | 229 | # Ctrl+I == Tab |
|
229 | 230 | @kbmanager.registry.add_binding(Keys.ControlI, |
|
230 | 231 | filter=(HasFocus(DEFAULT_BUFFER) |
|
231 | 232 | & ~HasSelection() |
|
232 | 233 | & insert_mode |
|
233 | 234 | & cursor_in_leading_ws |
|
234 | 235 | )) |
|
235 | 236 | def _indent_buffer(event): |
|
236 | 237 | event.current_buffer.insert_text(' ' * 4) |
|
237 | 238 | |
|
238 | 239 | # Pre-populate history from IPython's history database |
|
239 | 240 | history = InMemoryHistory() |
|
240 | 241 | last_cell = u"" |
|
241 | 242 | for __, ___, cell in self.history_manager.get_tail(self.history_load_length, |
|
242 | 243 | include_latest=True): |
|
243 | 244 | # Ignore blank lines and consecutive duplicates |
|
244 | 245 | cell = cell.rstrip() |
|
245 | 246 | if cell and (cell != last_cell): |
|
246 | 247 | history.append(cell) |
|
247 | 248 | |
|
248 | 249 | self._style = self._make_style_from_name(self.highlighting_style) |
|
249 | 250 | style = DynamicStyle(lambda: self._style) |
|
250 | 251 | |
|
251 | 252 | editing_mode = getattr(EditingMode, self.editing_mode.upper()) |
|
252 | 253 | |
|
253 | 254 | self._app = create_prompt_application( |
|
254 | 255 | editing_mode=editing_mode, |
|
255 | 256 | key_bindings_registry=kbmanager.registry, |
|
256 | 257 | history=history, |
|
257 | 258 | completer=IPythonPTCompleter(self.Completer), |
|
258 | 259 | enable_history_search=True, |
|
259 | 260 | style=style, |
|
260 | 261 | mouse_support=self.mouse_support, |
|
261 | 262 | **self._layout_options() |
|
262 | 263 | ) |
|
263 | 264 | self._eventloop = create_eventloop(self.inputhook) |
|
264 | 265 | self.pt_cli = CommandLineInterface(self._app, eventloop=self._eventloop) |
|
265 | 266 | |
|
266 | 267 | def _make_style_from_name(self, name): |
|
267 | 268 | """ |
|
268 | 269 | Small wrapper that make an IPython compatible style from a style name |
|
269 | 270 | |
|
270 | 271 | We need that to add style for prompt ... etc. |
|
271 | 272 | """ |
|
272 | 273 | style_cls = get_style_by_name(name) |
|
273 | 274 | style_overrides = { |
|
274 | 275 | Token.Prompt: '#009900', |
|
275 | 276 | Token.PromptNum: '#00ff00 bold', |
|
276 | 277 | } |
|
277 | 278 | if name == 'default': |
|
278 | 279 | style_cls = get_style_by_name('default') |
|
279 | 280 | # The default theme needs to be visible on both a dark background |
|
280 | 281 | # and a light background, because we can't tell what the terminal |
|
281 | 282 | # looks like. These tweaks to the default theme help with that. |
|
282 | 283 | style_overrides.update({ |
|
283 | 284 | Token.Number: '#007700', |
|
284 | 285 | Token.Operator: 'noinherit', |
|
285 | 286 | Token.String: '#BB6622', |
|
286 | 287 | Token.Name.Function: '#2080D0', |
|
287 | 288 | Token.Name.Class: 'bold #2080D0', |
|
288 | 289 | Token.Name.Namespace: 'bold #2080D0', |
|
289 | 290 | }) |
|
290 | 291 | style_overrides.update(self.highlighting_style_overrides) |
|
291 | 292 | style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, |
|
292 | 293 | style_dict=style_overrides) |
|
293 | 294 | |
|
294 | 295 | return style |
|
295 | 296 | |
|
296 | 297 | def _layout_options(self): |
|
297 | 298 | """ |
|
298 | 299 | Return the current layout option for the current Terminal InteractiveShell |
|
299 | 300 | """ |
|
300 | 301 | return { |
|
301 | 302 | 'lexer':IPythonPTLexer(), |
|
302 | 303 | 'reserve_space_for_menu':self.space_for_menu, |
|
303 | 304 | 'get_prompt_tokens':self.get_prompt_tokens, |
|
304 | 305 | 'get_continuation_tokens':self.get_continuation_tokens, |
|
305 | 306 | 'multiline':True, |
|
306 | 307 | 'display_completions_in_columns': self.display_completions_in_columns, |
|
307 | 308 | |
|
308 | 309 | # Highlight matching brackets, but only when this setting is |
|
309 | 310 | # enabled, and only when the DEFAULT_BUFFER has the focus. |
|
310 | 311 | 'extra_input_processors': [ConditionalProcessor( |
|
311 | 312 | processor=HighlightMatchingBracketProcessor(chars='[](){}'), |
|
312 | 313 | filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() & |
|
313 | 314 | Condition(lambda cli: self.highlight_matching_brackets))], |
|
314 | 315 | } |
|
315 | 316 | |
|
316 | 317 | def _update_layout(self): |
|
317 | 318 | """ |
|
318 | 319 | Ask for a re computation of the application layout, if for example , |
|
319 | 320 | some configuration options have changed. |
|
320 | 321 | """ |
|
321 | 322 | self._app.layout = create_prompt_layout(**self._layout_options()) |
|
322 | 323 | |
|
323 | 324 | def prompt_for_code(self): |
|
324 | 325 | document = self.pt_cli.run( |
|
325 | 326 | pre_run=self.pre_prompt, reset_current_buffer=True) |
|
326 | 327 | return document.text |
|
327 | 328 | |
|
328 | 329 | def init_io(self): |
|
329 | 330 | if sys.platform not in {'win32', 'cli'}: |
|
330 | 331 | return |
|
331 | 332 | |
|
332 | 333 | import colorama |
|
333 | 334 | colorama.init() |
|
334 | 335 | |
|
335 | 336 | # For some reason we make these wrappers around stdout/stderr. |
|
336 | 337 | # For now, we need to reset them so all output gets coloured. |
|
337 | 338 | # https://github.com/ipython/ipython/issues/8669 |
|
338 | 339 | from IPython.utils import io |
|
339 | 340 | io.stdout = io.IOStream(sys.stdout) |
|
340 | 341 | io.stderr = io.IOStream(sys.stderr) |
|
341 | 342 | |
|
342 | 343 | def init_magics(self): |
|
343 | 344 | super(TerminalInteractiveShell, self).init_magics() |
|
344 | 345 | self.register_magics(TerminalMagics) |
|
345 | 346 | |
|
346 | 347 | def init_alias(self): |
|
347 | 348 | # The parent class defines aliases that can be safely used with any |
|
348 | 349 | # frontend. |
|
349 | 350 | super(TerminalInteractiveShell, self).init_alias() |
|
350 | 351 | |
|
351 | 352 | # Now define aliases that only make sense on the terminal, because they |
|
352 | 353 | # need direct access to the console in a way that we can't emulate in |
|
353 | 354 | # GUI or web frontend |
|
354 | 355 | if os.name == 'posix': |
|
355 | 356 | for cmd in ['clear', 'more', 'less', 'man']: |
|
356 | 357 | self.alias_manager.soft_define_alias(cmd, cmd) |
|
357 | 358 | |
|
358 | 359 | |
|
359 | 360 | def __init__(self, *args, **kwargs): |
|
360 | 361 | super(TerminalInteractiveShell, self).__init__(*args, **kwargs) |
|
361 | 362 | self.init_prompt_toolkit_cli() |
|
362 | 363 | self.init_term_title() |
|
363 | 364 | self.keep_running = True |
|
364 | 365 | |
|
366 | self.debugger_history = InMemoryHistory() | |
|
367 | ||
|
365 | 368 | def ask_exit(self): |
|
366 | 369 | self.keep_running = False |
|
367 | 370 | |
|
368 | 371 | rl_next_input = None |
|
369 | 372 | |
|
370 | 373 | def pre_prompt(self): |
|
371 | 374 | if self.rl_next_input: |
|
372 | 375 | self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input) |
|
373 | 376 | self.rl_next_input = None |
|
374 | 377 | |
|
375 | 378 | def interact(self): |
|
376 | 379 | while self.keep_running: |
|
377 | 380 | print(self.separate_in, end='') |
|
378 | 381 | |
|
379 | 382 | try: |
|
380 | 383 | code = self.prompt_for_code() |
|
381 | 384 | except EOFError: |
|
382 | 385 | if (not self.confirm_exit) \ |
|
383 | 386 | or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): |
|
384 | 387 | self.ask_exit() |
|
385 | 388 | |
|
386 | 389 | else: |
|
387 | 390 | if code: |
|
388 | 391 | self.run_cell(code, store_history=True) |
|
389 | 392 | if self.autoedit_syntax and self.SyntaxTB.last_syntax_error: |
|
390 | 393 | self.edit_syntax_error() |
|
391 | 394 | |
|
392 | 395 | def mainloop(self): |
|
393 | 396 | # An extra layer of protection in case someone mashing Ctrl-C breaks |
|
394 | 397 | # out of our internal code. |
|
395 | 398 | while True: |
|
396 | 399 | try: |
|
397 | 400 | self.interact() |
|
398 | 401 | break |
|
399 | 402 | except KeyboardInterrupt: |
|
400 | 403 | print("\nKeyboardInterrupt escaped interact()\n") |
|
401 | 404 | |
|
402 | 405 | if hasattr(self, '_eventloop'): |
|
403 | 406 | self._eventloop.close() |
|
404 | 407 | |
|
405 | 408 | _inputhook = None |
|
406 | 409 | def inputhook(self, context): |
|
407 | 410 | if self._inputhook is not None: |
|
408 | 411 | self._inputhook(context) |
|
409 | 412 | |
|
410 | 413 | def enable_gui(self, gui=None): |
|
411 | 414 | if gui: |
|
412 | 415 | self._inputhook = get_inputhook_func(gui) |
|
413 | 416 | else: |
|
414 | 417 | self._inputhook = None |
|
415 | 418 | |
|
416 | 419 | # Methods to support auto-editing of SyntaxErrors: |
|
417 | 420 | |
|
418 | 421 | def edit_syntax_error(self): |
|
419 | 422 | """The bottom half of the syntax error handler called in the main loop. |
|
420 | 423 | |
|
421 | 424 | Loop until syntax error is fixed or user cancels. |
|
422 | 425 | """ |
|
423 | 426 | |
|
424 | 427 | while self.SyntaxTB.last_syntax_error: |
|
425 | 428 | # copy and clear last_syntax_error |
|
426 | 429 | err = self.SyntaxTB.clear_err_state() |
|
427 | 430 | if not self._should_recompile(err): |
|
428 | 431 | return |
|
429 | 432 | try: |
|
430 | 433 | # may set last_syntax_error again if a SyntaxError is raised |
|
431 | 434 | self.safe_execfile(err.filename, self.user_ns) |
|
432 | 435 | except: |
|
433 | 436 | self.showtraceback() |
|
434 | 437 | else: |
|
435 | 438 | try: |
|
436 | 439 | with open(err.filename) as f: |
|
437 | 440 | # This should be inside a display_trap block and I |
|
438 | 441 | # think it is. |
|
439 | 442 | sys.displayhook(f.read()) |
|
440 | 443 | except: |
|
441 | 444 | self.showtraceback() |
|
442 | 445 | |
|
443 | 446 | def _should_recompile(self, e): |
|
444 | 447 | """Utility routine for edit_syntax_error""" |
|
445 | 448 | |
|
446 | 449 | if e.filename in ('<ipython console>', '<input>', '<string>', |
|
447 | 450 | '<console>', '<BackgroundJob compilation>', |
|
448 | 451 | None): |
|
449 | 452 | return False |
|
450 | 453 | try: |
|
451 | 454 | if (self.autoedit_syntax and |
|
452 | 455 | not self.ask_yes_no( |
|
453 | 456 | 'Return to editor to correct syntax error? ' |
|
454 | 457 | '[Y/n] ', 'y')): |
|
455 | 458 | return False |
|
456 | 459 | except EOFError: |
|
457 | 460 | return False |
|
458 | 461 | |
|
459 | 462 | def int0(x): |
|
460 | 463 | try: |
|
461 | 464 | return int(x) |
|
462 | 465 | except TypeError: |
|
463 | 466 | return 0 |
|
464 | 467 | |
|
465 | 468 | # always pass integer line and offset values to editor hook |
|
466 | 469 | try: |
|
467 | 470 | self.hooks.fix_error_editor(e.filename, |
|
468 | 471 | int0(e.lineno), int0(e.offset), |
|
469 | 472 | e.msg) |
|
470 | 473 | except TryNext: |
|
471 | 474 | warn('Could not open editor') |
|
472 | 475 | return False |
|
473 | 476 | return True |
|
474 | 477 | |
|
475 | 478 | # Run !system commands directly, not through pipes, so terminal programs |
|
476 | 479 | # work correctly. |
|
477 | 480 | system = InteractiveShell.system_raw |
|
478 | 481 | |
|
479 | 482 | |
|
480 | 483 | if __name__ == '__main__': |
|
481 | 484 | TerminalInteractiveShell.instance().interact() |
General Comments 0
You need to be logged in to leave comments.
Login now