##// END OF EJS Templates
Fixes for metaclass syntax
Thomas Kluyver -
Show More
@@ -1,655 +1,654 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Display formatters.
3 3
4 4 Inheritance diagram:
5 5
6 6 .. inheritance-diagram:: IPython.core.formatters
7 7 :parts: 3
8 8
9 9 Authors:
10 10
11 11 * Robert Kern
12 12 * Brian Granger
13 13 """
14 14 #-----------------------------------------------------------------------------
15 15 # Copyright (C) 2010-2011, IPython Development Team.
16 16 #
17 17 # Distributed under the terms of the Modified BSD License.
18 18 #
19 19 # The full license is in the file COPYING.txt, distributed with this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 # Stdlib imports
27 27 import abc
28 28 import sys
29 29 import warnings
30 30 # We must use StringIO, as cStringIO doesn't handle unicode properly.
31 31 from io import StringIO
32 32
33 33 # Our own imports
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.lib import pretty
36 36 from IPython.utils.traitlets import (
37 37 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
38 38 )
39 from IPython.utils.py3compat import unicode_to_str
39 from IPython.utils.py3compat import unicode_to_str, with_metaclass
40 40
41 41
42 42 #-----------------------------------------------------------------------------
43 43 # The main DisplayFormatter class
44 44 #-----------------------------------------------------------------------------
45 45
46 46
47 47 class DisplayFormatter(Configurable):
48 48
49 49 # When set to true only the default plain text formatter will be used.
50 50 plain_text_only = Bool(False, config=True)
51 51 def _plain_text_only_changed(self, name, old, new):
52 52 warnings.warn("""DisplayFormatter.plain_text_only is deprecated.
53 53
54 54 Use DisplayFormatter.active_types = ['text/plain']
55 55 for the same effect.
56 56 """, DeprecationWarning)
57 57 if new:
58 58 self.active_types = ['text/plain']
59 59 else:
60 60 self.active_types = self.format_types
61 61
62 62 active_types = List(Unicode, config=True,
63 63 help="""List of currently active mime-types to display.
64 64 You can use this to set a white-list for formats to display.
65 65
66 66 Most users will not need to change this value.
67 67 """)
68 68 def _active_types_default(self):
69 69 return self.format_types
70 70
71 71 def _active_types_changed(self, name, old, new):
72 72 for key, formatter in self.formatters.items():
73 73 if key in new:
74 74 formatter.enabled = True
75 75 else:
76 76 formatter.enabled = False
77 77
78 78 # A dict of formatter whose keys are format types (MIME types) and whose
79 79 # values are subclasses of BaseFormatter.
80 80 formatters = Dict()
81 81 def _formatters_default(self):
82 82 """Activate the default formatters."""
83 83 formatter_classes = [
84 84 PlainTextFormatter,
85 85 HTMLFormatter,
86 86 SVGFormatter,
87 87 PNGFormatter,
88 88 JPEGFormatter,
89 89 LatexFormatter,
90 90 JSONFormatter,
91 91 JavascriptFormatter
92 92 ]
93 93 d = {}
94 94 for cls in formatter_classes:
95 95 f = cls(parent=self)
96 96 d[f.format_type] = f
97 97 return d
98 98
99 99 def format(self, obj, include=None, exclude=None):
100 100 """Return a format data dict for an object.
101 101
102 102 By default all format types will be computed.
103 103
104 104 The following MIME types are currently implemented:
105 105
106 106 * text/plain
107 107 * text/html
108 108 * text/latex
109 109 * application/json
110 110 * application/javascript
111 111 * image/png
112 112 * image/jpeg
113 113 * image/svg+xml
114 114
115 115 Parameters
116 116 ----------
117 117 obj : object
118 118 The Python object whose format data will be computed.
119 119 include : list or tuple, optional
120 120 A list of format type strings (MIME types) to include in the
121 121 format data dict. If this is set *only* the format types included
122 122 in this list will be computed.
123 123 exclude : list or tuple, optional
124 124 A list of format type string (MIME types) to exclude in the format
125 125 data dict. If this is set all format types will be computed,
126 126 except for those included in this argument.
127 127
128 128 Returns
129 129 -------
130 130 (format_dict, metadata_dict) : tuple of two dicts
131 131
132 132 format_dict is a dictionary of key/value pairs, one of each format that was
133 133 generated for the object. The keys are the format types, which
134 134 will usually be MIME type strings and the values and JSON'able
135 135 data structure containing the raw data for the representation in
136 136 that format.
137 137
138 138 metadata_dict is a dictionary of metadata about each mime-type output.
139 139 Its keys will be a strict subset of the keys in format_dict.
140 140 """
141 141 format_dict = {}
142 142 md_dict = {}
143 143
144 144 for format_type, formatter in self.formatters.items():
145 145 if include and format_type not in include:
146 146 continue
147 147 if exclude and format_type in exclude:
148 148 continue
149 149
150 150 md = None
151 151 try:
152 152 data = formatter(obj)
153 153 except:
154 154 # FIXME: log the exception
155 155 raise
156 156
157 157 # formatters can return raw data or (data, metadata)
158 158 if isinstance(data, tuple) and len(data) == 2:
159 159 data, md = data
160 160
161 161 if data is not None:
162 162 format_dict[format_type] = data
163 163 if md is not None:
164 164 md_dict[format_type] = md
165 165
166 166 return format_dict, md_dict
167 167
168 168 @property
169 169 def format_types(self):
170 170 """Return the format types (MIME types) of the active formatters."""
171 171 return self.formatters.keys()
172 172
173 173
174 174 #-----------------------------------------------------------------------------
175 175 # Formatters for specific format types (text, html, svg, etc.)
176 176 #-----------------------------------------------------------------------------
177 177
178 178
179 class FormatterABC(object):
179 class FormatterABC(with_metaclass(abc.ABCMeta, object)):
180 180 """ Abstract base class for Formatters.
181 181
182 182 A formatter is a callable class that is responsible for computing the
183 183 raw format data for a particular format type (MIME type). For example,
184 184 an HTML formatter would have a format type of `text/html` and would return
185 185 the HTML representation of the object when called.
186 186 """
187 __metaclass__ = abc.ABCMeta
188 187
189 188 # The format type of the data returned, usually a MIME type.
190 189 format_type = 'text/plain'
191 190
192 191 # Is the formatter enabled...
193 192 enabled = True
194 193
195 194 @abc.abstractmethod
196 195 def __call__(self, obj):
197 196 """Return a JSON'able representation of the object.
198 197
199 198 If the object cannot be formatted by this formatter, then return None
200 199 """
201 200 try:
202 201 return repr(obj)
203 202 except TypeError:
204 203 return None
205 204
206 205
207 206 class BaseFormatter(Configurable):
208 207 """A base formatter class that is configurable.
209 208
210 209 This formatter should usually be used as the base class of all formatters.
211 210 It is a traited :class:`Configurable` class and includes an extensible
212 211 API for users to determine how their objects are formatted. The following
213 212 logic is used to find a function to format an given object.
214 213
215 214 1. The object is introspected to see if it has a method with the name
216 215 :attr:`print_method`. If is does, that object is passed to that method
217 216 for formatting.
218 217 2. If no print method is found, three internal dictionaries are consulted
219 218 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
220 219 and :attr:`deferred_printers`.
221 220
222 221 Users should use these dictionaries to register functions that will be
223 222 used to compute the format data for their objects (if those objects don't
224 223 have the special print methods). The easiest way of using these
225 224 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
226 225 methods.
227 226
228 227 If no function/callable is found to compute the format data, ``None`` is
229 228 returned and this format type is not used.
230 229 """
231 230
232 231 format_type = Unicode('text/plain')
233 232
234 233 enabled = Bool(True, config=True)
235 234
236 235 print_method = ObjectName('__repr__')
237 236
238 237 # The singleton printers.
239 238 # Maps the IDs of the builtin singleton objects to the format functions.
240 239 singleton_printers = Dict(config=True)
241 240 def _singleton_printers_default(self):
242 241 return {}
243 242
244 243 # The type-specific printers.
245 244 # Map type objects to the format functions.
246 245 type_printers = Dict(config=True)
247 246 def _type_printers_default(self):
248 247 return {}
249 248
250 249 # The deferred-import type-specific printers.
251 250 # Map (modulename, classname) pairs to the format functions.
252 251 deferred_printers = Dict(config=True)
253 252 def _deferred_printers_default(self):
254 253 return {}
255 254
256 255 def __call__(self, obj):
257 256 """Compute the format for an object."""
258 257 if self.enabled:
259 258 obj_id = id(obj)
260 259 try:
261 260 obj_class = getattr(obj, '__class__', None) or type(obj)
262 261 # First try to find registered singleton printers for the type.
263 262 try:
264 263 printer = self.singleton_printers[obj_id]
265 264 except (TypeError, KeyError):
266 265 pass
267 266 else:
268 267 return printer(obj)
269 268 # Next look for type_printers.
270 269 for cls in pretty._get_mro(obj_class):
271 270 if cls in self.type_printers:
272 271 return self.type_printers[cls](obj)
273 272 else:
274 273 printer = self._in_deferred_types(cls)
275 274 if printer is not None:
276 275 return printer(obj)
277 276 # Finally look for special method names.
278 277 if hasattr(obj_class, self.print_method):
279 278 printer = getattr(obj_class, self.print_method)
280 279 return printer(obj)
281 280 return None
282 281 except Exception:
283 282 pass
284 283 else:
285 284 return None
286 285
287 286 def for_type(self, typ, func):
288 287 """Add a format function for a given type.
289 288
290 289 Parameters
291 290 -----------
292 291 typ : class
293 292 The class of the object that will be formatted using `func`.
294 293 func : callable
295 294 The callable that will be called to compute the format data. The
296 295 call signature of this function is simple, it must take the
297 296 object to be formatted and return the raw data for the given
298 297 format. Subclasses may use a different call signature for the
299 298 `func` argument.
300 299 """
301 300 oldfunc = self.type_printers.get(typ, None)
302 301 if func is not None:
303 302 # To support easy restoration of old printers, we need to ignore
304 303 # Nones.
305 304 self.type_printers[typ] = func
306 305 return oldfunc
307 306
308 307 def for_type_by_name(self, type_module, type_name, func):
309 308 """Add a format function for a type specified by the full dotted
310 309 module and name of the type, rather than the type of the object.
311 310
312 311 Parameters
313 312 ----------
314 313 type_module : str
315 314 The full dotted name of the module the type is defined in, like
316 315 ``numpy``.
317 316 type_name : str
318 317 The name of the type (the class name), like ``dtype``
319 318 func : callable
320 319 The callable that will be called to compute the format data. The
321 320 call signature of this function is simple, it must take the
322 321 object to be formatted and return the raw data for the given
323 322 format. Subclasses may use a different call signature for the
324 323 `func` argument.
325 324 """
326 325 key = (type_module, type_name)
327 326 oldfunc = self.deferred_printers.get(key, None)
328 327 if func is not None:
329 328 # To support easy restoration of old printers, we need to ignore
330 329 # Nones.
331 330 self.deferred_printers[key] = func
332 331 return oldfunc
333 332
334 333 def _in_deferred_types(self, cls):
335 334 """
336 335 Check if the given class is specified in the deferred type registry.
337 336
338 337 Returns the printer from the registry if it exists, and None if the
339 338 class is not in the registry. Successful matches will be moved to the
340 339 regular type registry for future use.
341 340 """
342 341 mod = getattr(cls, '__module__', None)
343 342 name = getattr(cls, '__name__', None)
344 343 key = (mod, name)
345 344 printer = None
346 345 if key in self.deferred_printers:
347 346 # Move the printer over to the regular registry.
348 347 printer = self.deferred_printers.pop(key)
349 348 self.type_printers[cls] = printer
350 349 return printer
351 350
352 351
353 352 class PlainTextFormatter(BaseFormatter):
354 353 """The default pretty-printer.
355 354
356 355 This uses :mod:`IPython.lib.pretty` to compute the format data of
357 356 the object. If the object cannot be pretty printed, :func:`repr` is used.
358 357 See the documentation of :mod:`IPython.lib.pretty` for details on
359 358 how to write pretty printers. Here is a simple example::
360 359
361 360 def dtype_pprinter(obj, p, cycle):
362 361 if cycle:
363 362 return p.text('dtype(...)')
364 363 if hasattr(obj, 'fields'):
365 364 if obj.fields is None:
366 365 p.text(repr(obj))
367 366 else:
368 367 p.begin_group(7, 'dtype([')
369 368 for i, field in enumerate(obj.descr):
370 369 if i > 0:
371 370 p.text(',')
372 371 p.breakable()
373 372 p.pretty(field)
374 373 p.end_group(7, '])')
375 374 """
376 375
377 376 # The format type of data returned.
378 377 format_type = Unicode('text/plain')
379 378
380 379 # This subclass ignores this attribute as it always need to return
381 380 # something.
382 381 enabled = Bool(True, config=False)
383 382
384 383 # Look for a _repr_pretty_ methods to use for pretty printing.
385 384 print_method = ObjectName('_repr_pretty_')
386 385
387 386 # Whether to pretty-print or not.
388 387 pprint = Bool(True, config=True)
389 388
390 389 # Whether to be verbose or not.
391 390 verbose = Bool(False, config=True)
392 391
393 392 # The maximum width.
394 393 max_width = Integer(79, config=True)
395 394
396 395 # The newline character.
397 396 newline = Unicode('\n', config=True)
398 397
399 398 # format-string for pprinting floats
400 399 float_format = Unicode('%r')
401 400 # setter for float precision, either int or direct format-string
402 401 float_precision = CUnicode('', config=True)
403 402
404 403 def _float_precision_changed(self, name, old, new):
405 404 """float_precision changed, set float_format accordingly.
406 405
407 406 float_precision can be set by int or str.
408 407 This will set float_format, after interpreting input.
409 408 If numpy has been imported, numpy print precision will also be set.
410 409
411 410 integer `n` sets format to '%.nf', otherwise, format set directly.
412 411
413 412 An empty string returns to defaults (repr for float, 8 for numpy).
414 413
415 414 This parameter can be set via the '%precision' magic.
416 415 """
417 416
418 417 if '%' in new:
419 418 # got explicit format string
420 419 fmt = new
421 420 try:
422 421 fmt%3.14159
423 422 except Exception:
424 423 raise ValueError("Precision must be int or format string, not %r"%new)
425 424 elif new:
426 425 # otherwise, should be an int
427 426 try:
428 427 i = int(new)
429 428 assert i >= 0
430 429 except ValueError:
431 430 raise ValueError("Precision must be int or format string, not %r"%new)
432 431 except AssertionError:
433 432 raise ValueError("int precision must be non-negative, not %r"%i)
434 433
435 434 fmt = '%%.%if'%i
436 435 if 'numpy' in sys.modules:
437 436 # set numpy precision if it has been imported
438 437 import numpy
439 438 numpy.set_printoptions(precision=i)
440 439 else:
441 440 # default back to repr
442 441 fmt = '%r'
443 442 if 'numpy' in sys.modules:
444 443 import numpy
445 444 # numpy default is 8
446 445 numpy.set_printoptions(precision=8)
447 446 self.float_format = fmt
448 447
449 448 # Use the default pretty printers from IPython.lib.pretty.
450 449 def _singleton_printers_default(self):
451 450 return pretty._singleton_pprinters.copy()
452 451
453 452 def _type_printers_default(self):
454 453 d = pretty._type_pprinters.copy()
455 454 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
456 455 return d
457 456
458 457 def _deferred_printers_default(self):
459 458 return pretty._deferred_type_pprinters.copy()
460 459
461 460 #### FormatterABC interface ####
462 461
463 462 def __call__(self, obj):
464 463 """Compute the pretty representation of the object."""
465 464 if not self.pprint:
466 465 try:
467 466 return repr(obj)
468 467 except TypeError:
469 468 return ''
470 469 else:
471 470 # This uses use StringIO, as cStringIO doesn't handle unicode.
472 471 stream = StringIO()
473 472 # self.newline.encode() is a quick fix for issue gh-597. We need to
474 473 # ensure that stream does not get a mix of unicode and bytestrings,
475 474 # or it will cause trouble.
476 475 printer = pretty.RepresentationPrinter(stream, self.verbose,
477 476 self.max_width, unicode_to_str(self.newline),
478 477 singleton_pprinters=self.singleton_printers,
479 478 type_pprinters=self.type_printers,
480 479 deferred_pprinters=self.deferred_printers)
481 480 printer.pretty(obj)
482 481 printer.flush()
483 482 return stream.getvalue()
484 483
485 484
486 485 class HTMLFormatter(BaseFormatter):
487 486 """An HTML formatter.
488 487
489 488 To define the callables that compute the HTML representation of your
490 489 objects, define a :meth:`_repr_html_` method or use the :meth:`for_type`
491 490 or :meth:`for_type_by_name` methods to register functions that handle
492 491 this.
493 492
494 493 The return value of this formatter should be a valid HTML snippet that
495 494 could be injected into an existing DOM. It should *not* include the
496 495 ```<html>`` or ```<body>`` tags.
497 496 """
498 497 format_type = Unicode('text/html')
499 498
500 499 print_method = ObjectName('_repr_html_')
501 500
502 501
503 502 class SVGFormatter(BaseFormatter):
504 503 """An SVG formatter.
505 504
506 505 To define the callables that compute the SVG representation of your
507 506 objects, define a :meth:`_repr_svg_` method or use the :meth:`for_type`
508 507 or :meth:`for_type_by_name` methods to register functions that handle
509 508 this.
510 509
511 510 The return value of this formatter should be valid SVG enclosed in
512 511 ```<svg>``` tags, that could be injected into an existing DOM. It should
513 512 *not* include the ```<html>`` or ```<body>`` tags.
514 513 """
515 514 format_type = Unicode('image/svg+xml')
516 515
517 516 print_method = ObjectName('_repr_svg_')
518 517
519 518
520 519 class PNGFormatter(BaseFormatter):
521 520 """A PNG formatter.
522 521
523 522 To define the callables that compute the PNG representation of your
524 523 objects, define a :meth:`_repr_png_` method or use the :meth:`for_type`
525 524 or :meth:`for_type_by_name` methods to register functions that handle
526 525 this.
527 526
528 527 The return value of this formatter should be raw PNG data, *not*
529 528 base64 encoded.
530 529 """
531 530 format_type = Unicode('image/png')
532 531
533 532 print_method = ObjectName('_repr_png_')
534 533
535 534
536 535 class JPEGFormatter(BaseFormatter):
537 536 """A JPEG formatter.
538 537
539 538 To define the callables that compute the JPEG representation of your
540 539 objects, define a :meth:`_repr_jpeg_` method or use the :meth:`for_type`
541 540 or :meth:`for_type_by_name` methods to register functions that handle
542 541 this.
543 542
544 543 The return value of this formatter should be raw JPEG data, *not*
545 544 base64 encoded.
546 545 """
547 546 format_type = Unicode('image/jpeg')
548 547
549 548 print_method = ObjectName('_repr_jpeg_')
550 549
551 550
552 551 class LatexFormatter(BaseFormatter):
553 552 """A LaTeX formatter.
554 553
555 554 To define the callables that compute the LaTeX representation of your
556 555 objects, define a :meth:`_repr_latex_` method or use the :meth:`for_type`
557 556 or :meth:`for_type_by_name` methods to register functions that handle
558 557 this.
559 558
560 559 The return value of this formatter should be a valid LaTeX equation,
561 560 enclosed in either ```$```, ```$$``` or another LaTeX equation
562 561 environment.
563 562 """
564 563 format_type = Unicode('text/latex')
565 564
566 565 print_method = ObjectName('_repr_latex_')
567 566
568 567
569 568 class JSONFormatter(BaseFormatter):
570 569 """A JSON string formatter.
571 570
572 571 To define the callables that compute the JSON string representation of
573 572 your objects, define a :meth:`_repr_json_` method or use the :meth:`for_type`
574 573 or :meth:`for_type_by_name` methods to register functions that handle
575 574 this.
576 575
577 576 The return value of this formatter should be a valid JSON string.
578 577 """
579 578 format_type = Unicode('application/json')
580 579
581 580 print_method = ObjectName('_repr_json_')
582 581
583 582
584 583 class JavascriptFormatter(BaseFormatter):
585 584 """A Javascript formatter.
586 585
587 586 To define the callables that compute the Javascript representation of
588 587 your objects, define a :meth:`_repr_javascript_` method or use the
589 588 :meth:`for_type` or :meth:`for_type_by_name` methods to register functions
590 589 that handle this.
591 590
592 591 The return value of this formatter should be valid Javascript code and
593 592 should *not* be enclosed in ```<script>``` tags.
594 593 """
595 594 format_type = Unicode('application/javascript')
596 595
597 596 print_method = ObjectName('_repr_javascript_')
598 597
599 598 FormatterABC.register(BaseFormatter)
600 599 FormatterABC.register(PlainTextFormatter)
601 600 FormatterABC.register(HTMLFormatter)
602 601 FormatterABC.register(SVGFormatter)
603 602 FormatterABC.register(PNGFormatter)
604 603 FormatterABC.register(JPEGFormatter)
605 604 FormatterABC.register(LatexFormatter)
606 605 FormatterABC.register(JSONFormatter)
607 606 FormatterABC.register(JavascriptFormatter)
608 607
609 608
610 609 def format_display_data(obj, include=None, exclude=None):
611 610 """Return a format data dict for an object.
612 611
613 612 By default all format types will be computed.
614 613
615 614 The following MIME types are currently implemented:
616 615
617 616 * text/plain
618 617 * text/html
619 618 * text/latex
620 619 * application/json
621 620 * application/javascript
622 621 * image/png
623 622 * image/jpeg
624 623 * image/svg+xml
625 624
626 625 Parameters
627 626 ----------
628 627 obj : object
629 628 The Python object whose format data will be computed.
630 629
631 630 Returns
632 631 -------
633 632 format_dict : dict
634 633 A dictionary of key/value pairs, one or each format that was
635 634 generated for the object. The keys are the format types, which
636 635 will usually be MIME type strings and the values and JSON'able
637 636 data structure containing the raw data for the representation in
638 637 that format.
639 638 include : list or tuple, optional
640 639 A list of format type strings (MIME types) to include in the
641 640 format data dict. If this is set *only* the format types included
642 641 in this list will be computed.
643 642 exclude : list or tuple, optional
644 643 A list of format type string (MIME types) to exclue in the format
645 644 data dict. If this is set all format types will be computed,
646 645 except for those included in this argument.
647 646 """
648 647 from IPython.core.interactiveshell import InteractiveShell
649 648
650 649 InteractiveShell.instance().display_formatter.format(
651 650 obj,
652 651 include,
653 652 exclude
654 653 )
655 654
@@ -1,531 +1,531 b''
1 1 import abc
2 2 import functools
3 3 import re
4 4 from io import StringIO
5 5
6 6 from IPython.core.splitinput import LineInfo
7 7 from IPython.utils import tokenize2
8 8 from IPython.utils.openpy import cookie_comment_re
9 from IPython.utils.py3compat import with_metaclass
9 10 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
10 11
11 12 #-----------------------------------------------------------------------------
12 13 # Globals
13 14 #-----------------------------------------------------------------------------
14 15
15 16 # The escape sequences that define the syntax transformations IPython will
16 17 # apply to user input. These can NOT be just changed here: many regular
17 18 # expressions and other parts of the code may use their hardcoded values, and
18 19 # for all intents and purposes they constitute the 'IPython syntax', so they
19 20 # should be considered fixed.
20 21
21 22 ESC_SHELL = '!' # Send line to underlying system shell
22 23 ESC_SH_CAP = '!!' # Send line to system shell and capture output
23 24 ESC_HELP = '?' # Find information about object
24 25 ESC_HELP2 = '??' # Find extra-detailed information about object
25 26 ESC_MAGIC = '%' # Call magic function
26 27 ESC_MAGIC2 = '%%' # Call cell-magic function
27 28 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
28 29 ESC_QUOTE2 = ';' # Quote all args as a single string, call
29 30 ESC_PAREN = '/' # Call first argument with rest of line as arguments
30 31
31 32 ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
32 33 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
33 34 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
34 35
35 36
36 class InputTransformer(object):
37 class InputTransformer(with_metaclass(abc.ABCMeta, object)):
37 38 """Abstract base class for line-based input transformers."""
38 __metaclass__ = abc.ABCMeta
39 39
40 40 @abc.abstractmethod
41 41 def push(self, line):
42 42 """Send a line of input to the transformer, returning the transformed
43 43 input or None if the transformer is waiting for more input.
44 44
45 45 Must be overridden by subclasses.
46 46 """
47 47 pass
48 48
49 49 @abc.abstractmethod
50 50 def reset(self):
51 51 """Return, transformed any lines that the transformer has accumulated,
52 52 and reset its internal state.
53 53
54 54 Must be overridden by subclasses.
55 55 """
56 56 pass
57 57
58 58 @classmethod
59 59 def wrap(cls, func):
60 60 """Can be used by subclasses as a decorator, to return a factory that
61 61 will allow instantiation with the decorated object.
62 62 """
63 63 @functools.wraps(func)
64 64 def transformer_factory(**kwargs):
65 65 return cls(func, **kwargs)
66 66
67 67 return transformer_factory
68 68
69 69 class StatelessInputTransformer(InputTransformer):
70 70 """Wrapper for a stateless input transformer implemented as a function."""
71 71 def __init__(self, func):
72 72 self.func = func
73 73
74 74 def __repr__(self):
75 75 return "StatelessInputTransformer(func={0!r})".format(self.func)
76 76
77 77 def push(self, line):
78 78 """Send a line of input to the transformer, returning the
79 79 transformed input."""
80 80 return self.func(line)
81 81
82 82 def reset(self):
83 83 """No-op - exists for compatibility."""
84 84 pass
85 85
86 86 class CoroutineInputTransformer(InputTransformer):
87 87 """Wrapper for an input transformer implemented as a coroutine."""
88 88 def __init__(self, coro, **kwargs):
89 89 # Prime it
90 90 self.coro = coro(**kwargs)
91 91 next(self.coro)
92 92
93 93 def __repr__(self):
94 94 return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
95 95
96 96 def push(self, line):
97 97 """Send a line of input to the transformer, returning the
98 98 transformed input or None if the transformer is waiting for more
99 99 input.
100 100 """
101 101 return self.coro.send(line)
102 102
103 103 def reset(self):
104 104 """Return, transformed any lines that the transformer has
105 105 accumulated, and reset its internal state.
106 106 """
107 107 return self.coro.send(None)
108 108
109 109 class TokenInputTransformer(InputTransformer):
110 110 """Wrapper for a token-based input transformer.
111 111
112 112 func should accept a list of tokens (5-tuples, see tokenize docs), and
113 113 return an iterable which can be passed to tokenize.untokenize().
114 114 """
115 115 def __init__(self, func):
116 116 self.func = func
117 117 self.current_line = ""
118 118 self.line_used = False
119 119 self.reset_tokenizer()
120 120
121 121 def reset_tokenizer(self):
122 122 self.tokenizer = generate_tokens(self.get_line)
123 123
124 124 def get_line(self):
125 125 if self.line_used:
126 126 raise TokenError
127 127 self.line_used = True
128 128 return self.current_line
129 129
130 130 def push(self, line):
131 131 self.current_line += line + "\n"
132 132 if self.current_line.isspace():
133 133 return self.reset()
134 134
135 135 self.line_used = False
136 136 tokens = []
137 137 stop_at_NL = False
138 138 try:
139 139 for intok in self.tokenizer:
140 140 tokens.append(intok)
141 141 t = intok[0]
142 142 if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
143 143 # Stop before we try to pull a line we don't have yet
144 144 break
145 145 elif t == tokenize2.ERRORTOKEN:
146 146 stop_at_NL = True
147 147 except TokenError:
148 148 # Multi-line statement - stop and try again with the next line
149 149 self.reset_tokenizer()
150 150 return None
151 151
152 152 return self.output(tokens)
153 153
154 154 def output(self, tokens):
155 155 self.current_line = ""
156 156 self.reset_tokenizer()
157 157 return untokenize(self.func(tokens)).rstrip('\n')
158 158
159 159 def reset(self):
160 160 l = self.current_line
161 161 self.current_line = ""
162 162 self.reset_tokenizer()
163 163 if l:
164 164 return l.rstrip('\n')
165 165
166 166 class assemble_python_lines(TokenInputTransformer):
167 167 def __init__(self):
168 168 super(assemble_python_lines, self).__init__(None)
169 169
170 170 def output(self, tokens):
171 171 return self.reset()
172 172
173 173 @CoroutineInputTransformer.wrap
174 174 def assemble_logical_lines():
175 175 """Join lines following explicit line continuations (\)"""
176 176 line = ''
177 177 while True:
178 178 line = (yield line)
179 179 if not line or line.isspace():
180 180 continue
181 181
182 182 parts = []
183 183 while line is not None:
184 184 if line.endswith('\\') and (not has_comment(line)):
185 185 parts.append(line[:-1])
186 186 line = (yield None) # Get another line
187 187 else:
188 188 parts.append(line)
189 189 break
190 190
191 191 # Output
192 192 line = ''.join(parts)
193 193
194 194 # Utilities
195 195 def _make_help_call(target, esc, lspace, next_input=None):
196 196 """Prepares a pinfo(2)/psearch call from a target name and the escape
197 197 (i.e. ? or ??)"""
198 198 method = 'pinfo2' if esc == '??' \
199 199 else 'psearch' if '*' in target \
200 200 else 'pinfo'
201 201 arg = " ".join([method, target])
202 202 if next_input is None:
203 203 return '%sget_ipython().magic(%r)' % (lspace, arg)
204 204 else:
205 205 return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
206 206 (lspace, next_input, arg)
207 207
208 208 # These define the transformations for the different escape characters.
209 209 def _tr_system(line_info):
210 210 "Translate lines escaped with: !"
211 211 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
212 212 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
213 213
214 214 def _tr_system2(line_info):
215 215 "Translate lines escaped with: !!"
216 216 cmd = line_info.line.lstrip()[2:]
217 217 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
218 218
219 219 def _tr_help(line_info):
220 220 "Translate lines escaped with: ?/??"
221 221 # A naked help line should just fire the intro help screen
222 222 if not line_info.line[1:]:
223 223 return 'get_ipython().show_usage()'
224 224
225 225 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
226 226
227 227 def _tr_magic(line_info):
228 228 "Translate lines escaped with: %"
229 229 tpl = '%sget_ipython().magic(%r)'
230 230 if line_info.line.startswith(ESC_MAGIC2):
231 231 return line_info.line
232 232 cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
233 233 return tpl % (line_info.pre, cmd)
234 234
235 235 def _tr_quote(line_info):
236 236 "Translate lines escaped with: ,"
237 237 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
238 238 '", "'.join(line_info.the_rest.split()) )
239 239
240 240 def _tr_quote2(line_info):
241 241 "Translate lines escaped with: ;"
242 242 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
243 243 line_info.the_rest)
244 244
245 245 def _tr_paren(line_info):
246 246 "Translate lines escaped with: /"
247 247 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
248 248 ", ".join(line_info.the_rest.split()))
249 249
250 250 tr = { ESC_SHELL : _tr_system,
251 251 ESC_SH_CAP : _tr_system2,
252 252 ESC_HELP : _tr_help,
253 253 ESC_HELP2 : _tr_help,
254 254 ESC_MAGIC : _tr_magic,
255 255 ESC_QUOTE : _tr_quote,
256 256 ESC_QUOTE2 : _tr_quote2,
257 257 ESC_PAREN : _tr_paren }
258 258
259 259 @StatelessInputTransformer.wrap
260 260 def escaped_commands(line):
261 261 """Transform escaped commands - %magic, !system, ?help + various autocalls.
262 262 """
263 263 if not line or line.isspace():
264 264 return line
265 265 lineinf = LineInfo(line)
266 266 if lineinf.esc not in tr:
267 267 return line
268 268
269 269 return tr[lineinf.esc](lineinf)
270 270
271 271 _initial_space_re = re.compile(r'\s*')
272 272
273 273 _help_end_re = re.compile(r"""(%{0,2}
274 274 [a-zA-Z_*][\w*]* # Variable name
275 275 (\.[a-zA-Z_*][\w*]*)* # .etc.etc
276 276 )
277 277 (\?\??)$ # ? or ??
278 278 """,
279 279 re.VERBOSE)
280 280
281 281 # Extra pseudotokens for multiline strings and data structures
282 282 _MULTILINE_STRING = object()
283 283 _MULTILINE_STRUCTURE = object()
284 284
285 285 def _line_tokens(line):
286 286 """Helper for has_comment and ends_in_comment_or_string."""
287 287 readline = StringIO(line).readline
288 288 toktypes = set()
289 289 try:
290 290 for t in generate_tokens(readline):
291 291 toktypes.add(t[0])
292 292 except TokenError as e:
293 293 # There are only two cases where a TokenError is raised.
294 294 if 'multi-line string' in e.args[0]:
295 295 toktypes.add(_MULTILINE_STRING)
296 296 else:
297 297 toktypes.add(_MULTILINE_STRUCTURE)
298 298 return toktypes
299 299
300 300 def has_comment(src):
301 301 """Indicate whether an input line has (i.e. ends in, or is) a comment.
302 302
303 303 This uses tokenize, so it can distinguish comments from # inside strings.
304 304
305 305 Parameters
306 306 ----------
307 307 src : string
308 308 A single line input string.
309 309
310 310 Returns
311 311 -------
312 312 comment : bool
313 313 True if source has a comment.
314 314 """
315 315 return (tokenize2.COMMENT in _line_tokens(src))
316 316
317 317 def ends_in_comment_or_string(src):
318 318 """Indicates whether or not an input line ends in a comment or within
319 319 a multiline string.
320 320
321 321 Parameters
322 322 ----------
323 323 src : string
324 324 A single line input string.
325 325
326 326 Returns
327 327 -------
328 328 comment : bool
329 329 True if source ends in a comment or multiline string.
330 330 """
331 331 toktypes = _line_tokens(src)
332 332 return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
333 333
334 334
335 335 @StatelessInputTransformer.wrap
336 336 def help_end(line):
337 337 """Translate lines with ?/?? at the end"""
338 338 m = _help_end_re.search(line)
339 339 if m is None or ends_in_comment_or_string(line):
340 340 return line
341 341 target = m.group(1)
342 342 esc = m.group(3)
343 343 lspace = _initial_space_re.match(line).group(0)
344 344
345 345 # If we're mid-command, put it back on the next prompt for the user.
346 346 next_input = line.rstrip('?') if line.strip() != m.group(0) else None
347 347
348 348 return _make_help_call(target, esc, lspace, next_input)
349 349
350 350
351 351 @CoroutineInputTransformer.wrap
352 352 def cellmagic(end_on_blank_line=False):
353 353 """Captures & transforms cell magics.
354 354
355 355 After a cell magic is started, this stores up any lines it gets until it is
356 356 reset (sent None).
357 357 """
358 358 tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
359 359 cellmagic_help_re = re.compile('%%\w+\?')
360 360 line = ''
361 361 while True:
362 362 line = (yield line)
363 363 # consume leading empty lines
364 364 while not line:
365 365 line = (yield line)
366 366
367 367 if not line.startswith(ESC_MAGIC2):
368 368 # This isn't a cell magic, idle waiting for reset then start over
369 369 while line is not None:
370 370 line = (yield line)
371 371 continue
372 372
373 373 if cellmagic_help_re.match(line):
374 374 # This case will be handled by help_end
375 375 continue
376 376
377 377 first = line
378 378 body = []
379 379 line = (yield None)
380 380 while (line is not None) and \
381 381 ((line.strip() != '') or not end_on_blank_line):
382 382 body.append(line)
383 383 line = (yield None)
384 384
385 385 # Output
386 386 magic_name, _, first = first.partition(' ')
387 387 magic_name = magic_name.lstrip(ESC_MAGIC2)
388 388 line = tpl % (magic_name, first, u'\n'.join(body))
389 389
390 390
391 391 def _strip_prompts(prompt_re, initial_re=None):
392 392 """Remove matching input prompts from a block of input.
393 393
394 394 Parameters
395 395 ----------
396 396 prompt_re : regular expression
397 397 A regular expression matching any input prompt (including continuation)
398 398 initial_re : regular expression, optional
399 399 A regular expression matching only the initial prompt, but not continuation.
400 400 If no initial expression is given, prompt_re will be used everywhere.
401 401 Used mainly for plain Python prompts, where the continuation prompt
402 402 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
403 403
404 404 If initial_re and prompt_re differ,
405 405 only initial_re will be tested against the first line.
406 406 If any prompt is found on the first two lines,
407 407 prompts will be stripped from the rest of the block.
408 408 """
409 409 if initial_re is None:
410 410 initial_re = prompt_re
411 411 line = ''
412 412 while True:
413 413 line = (yield line)
414 414
415 415 # First line of cell
416 416 if line is None:
417 417 continue
418 418 out, n1 = initial_re.subn('', line, count=1)
419 419 line = (yield out)
420 420
421 421 if line is None:
422 422 continue
423 423 # check for any prompt on the second line of the cell,
424 424 # because people often copy from just after the first prompt,
425 425 # so we might not see it in the first line.
426 426 out, n2 = prompt_re.subn('', line, count=1)
427 427 line = (yield out)
428 428
429 429 if n1 or n2:
430 430 # Found a prompt in the first two lines - check for it in
431 431 # the rest of the cell as well.
432 432 while line is not None:
433 433 line = (yield prompt_re.sub('', line, count=1))
434 434
435 435 else:
436 436 # Prompts not in input - wait for reset
437 437 while line is not None:
438 438 line = (yield line)
439 439
440 440 @CoroutineInputTransformer.wrap
441 441 def classic_prompt():
442 442 """Strip the >>>/... prompts of the Python interactive shell."""
443 443 # FIXME: non-capturing version (?:...) usable?
444 444 prompt_re = re.compile(r'^(>>> ?|\.\.\. ?)')
445 445 initial_re = re.compile(r'^(>>> ?)')
446 446 return _strip_prompts(prompt_re, initial_re)
447 447
448 448 @CoroutineInputTransformer.wrap
449 449 def ipy_prompt():
450 450 """Strip IPython's In [1]:/...: prompts."""
451 451 # FIXME: non-capturing version (?:...) usable?
452 452 # FIXME: r'^(In \[\d+\]: | {3}\.{3,}: )' clearer?
453 453 prompt_re = re.compile(r'^(In \[\d+\]: |\ \ \ \.\.\.+: )')
454 454 return _strip_prompts(prompt_re)
455 455
456 456
457 457 @CoroutineInputTransformer.wrap
458 458 def leading_indent():
459 459 """Remove leading indentation.
460 460
461 461 If the first line starts with a spaces or tabs, the same whitespace will be
462 462 removed from each following line until it is reset.
463 463 """
464 464 space_re = re.compile(r'^[ \t]+')
465 465 line = ''
466 466 while True:
467 467 line = (yield line)
468 468
469 469 if line is None:
470 470 continue
471 471
472 472 m = space_re.match(line)
473 473 if m:
474 474 space = m.group(0)
475 475 while line is not None:
476 476 if line.startswith(space):
477 477 line = line[len(space):]
478 478 line = (yield line)
479 479 else:
480 480 # No leading spaces - wait for reset
481 481 while line is not None:
482 482 line = (yield line)
483 483
484 484
485 485 @CoroutineInputTransformer.wrap
486 486 def strip_encoding_cookie():
487 487 """Remove encoding comment if found in first two lines
488 488
489 489 If the first or second line has the `# coding: utf-8` comment,
490 490 it will be removed.
491 491 """
492 492 line = ''
493 493 while True:
494 494 line = (yield line)
495 495 # check comment on first two lines
496 496 for i in range(2):
497 497 if line is None:
498 498 break
499 499 if cookie_comment_re.match(line):
500 500 line = (yield "")
501 501 else:
502 502 line = (yield line)
503 503
504 504 # no-op on the rest of the cell
505 505 while line is not None:
506 506 line = (yield line)
507 507
508 508
509 509 assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
510 510 r'\s*=\s*!\s*(?P<cmd>.*)')
511 511 assign_system_template = '%s = get_ipython().getoutput(%r)'
512 512 @StatelessInputTransformer.wrap
513 513 def assign_from_system(line):
514 514 """Transform assignment from system commands (e.g. files = !ls)"""
515 515 m = assign_system_re.match(line)
516 516 if m is None:
517 517 return line
518 518
519 519 return assign_system_template % m.group('lhs', 'cmd')
520 520
521 521 assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
522 522 r'\s*=\s*%\s*(?P<cmd>.*)')
523 523 assign_magic_template = '%s = get_ipython().magic(%r)'
524 524 @StatelessInputTransformer.wrap
525 525 def assign_from_magic(line):
526 526 """Transform assignment from magic commands (e.g. a = %who_ls)"""
527 527 m = assign_magic_re.match(line)
528 528 if m is None:
529 529 return line
530 530
531 531 return assign_magic_template % m.group('lhs', 'cmd')
@@ -1,3164 +1,3164 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import absolute_import
18 18 from __future__ import print_function
19 19
20 20 import __future__
21 21 import abc
22 22 import ast
23 23 import atexit
24 24 import functools
25 25 import os
26 26 import re
27 27 import runpy
28 28 import sys
29 29 import tempfile
30 30 import types
31 31 import subprocess
32 32 from io import open as io_open
33 33
34 34 from IPython.config.configurable import SingletonConfigurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import magic
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager, AliasError
42 42 from IPython.core.autocall import ExitAutocall
43 43 from IPython.core.builtin_trap import BuiltinTrap
44 44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 45 from IPython.core.display_trap import DisplayTrap
46 46 from IPython.core.displayhook import DisplayHook
47 47 from IPython.core.displaypub import DisplayPublisher
48 48 from IPython.core.error import UsageError
49 49 from IPython.core.extensions import ExtensionManager
50 50 from IPython.core.formatters import DisplayFormatter
51 51 from IPython.core.history import HistoryManager
52 52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
53 53 from IPython.core.logger import Logger
54 54 from IPython.core.macro import Macro
55 55 from IPython.core.payload import PayloadManager
56 56 from IPython.core.prefilter import PrefilterManager
57 57 from IPython.core.profiledir import ProfileDir
58 58 from IPython.core.prompts import PromptManager
59 59 from IPython.lib.latextools import LaTeXTool
60 60 from IPython.testing.skipdoctest import skip_doctest
61 61 from IPython.utils import PyColorize
62 62 from IPython.utils import io
63 63 from IPython.utils import py3compat
64 64 from IPython.utils import openpy
65 65 from IPython.utils.decorators import undoc
66 66 from IPython.utils.io import ask_yes_no
67 67 from IPython.utils.ipstruct import Struct
68 68 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
69 69 from IPython.utils.pickleshare import PickleShareDB
70 70 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import builtin_mod, unicode_type, string_types
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 with_metaclass)
72 73 from IPython.utils.strdispatch import StrDispatch
73 74 from IPython.utils.syspathcontext import prepended_to_syspath
74 75 from IPython.utils.text import (format_screen, LSString, SList,
75 76 DollarFormatter)
76 77 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
77 78 List, Unicode, Instance, Type)
78 79 from IPython.utils.warn import warn, error
79 80 import IPython.core.hooks
80 81
81 82 #-----------------------------------------------------------------------------
82 83 # Globals
83 84 #-----------------------------------------------------------------------------
84 85
85 86 # compiled regexps for autoindent management
86 87 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 88
88 89 #-----------------------------------------------------------------------------
89 90 # Utilities
90 91 #-----------------------------------------------------------------------------
91 92
92 93 @undoc
93 94 def softspace(file, newvalue):
94 95 """Copied from code.py, to remove the dependency"""
95 96
96 97 oldvalue = 0
97 98 try:
98 99 oldvalue = file.softspace
99 100 except AttributeError:
100 101 pass
101 102 try:
102 103 file.softspace = newvalue
103 104 except (AttributeError, TypeError):
104 105 # "attribute-less object" or "read-only attributes"
105 106 pass
106 107 return oldvalue
107 108
108 109 @undoc
109 110 def no_op(*a, **kw): pass
110 111
111 112 @undoc
112 113 class NoOpContext(object):
113 114 def __enter__(self): pass
114 115 def __exit__(self, type, value, traceback): pass
115 116 no_op_context = NoOpContext()
116 117
117 118 class SpaceInInput(Exception): pass
118 119
119 120 @undoc
120 121 class Bunch: pass
121 122
122 123
123 124 def get_default_colors():
124 125 if sys.platform=='darwin':
125 126 return "LightBG"
126 127 elif os.name=='nt':
127 128 return 'Linux'
128 129 else:
129 130 return 'Linux'
130 131
131 132
132 133 class SeparateUnicode(Unicode):
133 134 """A Unicode subclass to validate separate_in, separate_out, etc.
134 135
135 136 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
136 137 """
137 138
138 139 def validate(self, obj, value):
139 140 if value == '0': value = ''
140 141 value = value.replace('\\n','\n')
141 142 return super(SeparateUnicode, self).validate(obj, value)
142 143
143 144
144 145 class ReadlineNoRecord(object):
145 146 """Context manager to execute some code, then reload readline history
146 147 so that interactive input to the code doesn't appear when pressing up."""
147 148 def __init__(self, shell):
148 149 self.shell = shell
149 150 self._nested_level = 0
150 151
151 152 def __enter__(self):
152 153 if self._nested_level == 0:
153 154 try:
154 155 self.orig_length = self.current_length()
155 156 self.readline_tail = self.get_readline_tail()
156 157 except (AttributeError, IndexError): # Can fail with pyreadline
157 158 self.orig_length, self.readline_tail = 999999, []
158 159 self._nested_level += 1
159 160
160 161 def __exit__(self, type, value, traceback):
161 162 self._nested_level -= 1
162 163 if self._nested_level == 0:
163 164 # Try clipping the end if it's got longer
164 165 try:
165 166 e = self.current_length() - self.orig_length
166 167 if e > 0:
167 168 for _ in range(e):
168 169 self.shell.readline.remove_history_item(self.orig_length)
169 170
170 171 # If it still doesn't match, just reload readline history.
171 172 if self.current_length() != self.orig_length \
172 173 or self.get_readline_tail() != self.readline_tail:
173 174 self.shell.refill_readline_hist()
174 175 except (AttributeError, IndexError):
175 176 pass
176 177 # Returning False will cause exceptions to propagate
177 178 return False
178 179
179 180 def current_length(self):
180 181 return self.shell.readline.get_current_history_length()
181 182
182 183 def get_readline_tail(self, n=10):
183 184 """Get the last n items in readline history."""
184 185 end = self.shell.readline.get_current_history_length() + 1
185 186 start = max(end-n, 1)
186 187 ghi = self.shell.readline.get_history_item
187 188 return [ghi(x) for x in range(start, end)]
188 189
189 190
190 191 @undoc
191 192 class DummyMod(object):
192 193 """A dummy module used for IPython's interactive module when
193 194 a namespace must be assigned to the module's __dict__."""
194 195 pass
195 196
196 197 #-----------------------------------------------------------------------------
197 198 # Main IPython class
198 199 #-----------------------------------------------------------------------------
199 200
200 201 class InteractiveShell(SingletonConfigurable):
201 202 """An enhanced, interactive shell for Python."""
202 203
203 204 _instance = None
204 205
205 206 ast_transformers = List([], config=True, help=
206 207 """
207 208 A list of ast.NodeTransformer subclass instances, which will be applied
208 209 to user input before code is run.
209 210 """
210 211 )
211 212
212 213 autocall = Enum((0,1,2), default_value=0, config=True, help=
213 214 """
214 215 Make IPython automatically call any callable object even if you didn't
215 216 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
216 217 automatically. The value can be '0' to disable the feature, '1' for
217 218 'smart' autocall, where it is not applied if there are no more
218 219 arguments on the line, and '2' for 'full' autocall, where all callable
219 220 objects are automatically called (even if no arguments are present).
220 221 """
221 222 )
222 223 # TODO: remove all autoindent logic and put into frontends.
223 224 # We can't do this yet because even runlines uses the autoindent.
224 225 autoindent = CBool(True, config=True, help=
225 226 """
226 227 Autoindent IPython code entered interactively.
227 228 """
228 229 )
229 230 automagic = CBool(True, config=True, help=
230 231 """
231 232 Enable magic commands to be called without the leading %.
232 233 """
233 234 )
234 235 cache_size = Integer(1000, config=True, help=
235 236 """
236 237 Set the size of the output cache. The default is 1000, you can
237 238 change it permanently in your config file. Setting it to 0 completely
238 239 disables the caching system, and the minimum value accepted is 20 (if
239 240 you provide a value less than 20, it is reset to 0 and a warning is
240 241 issued). This limit is defined because otherwise you'll spend more
241 242 time re-flushing a too small cache than working
242 243 """
243 244 )
244 245 color_info = CBool(True, config=True, help=
245 246 """
246 247 Use colors for displaying information about objects. Because this
247 248 information is passed through a pager (like 'less'), and some pagers
248 249 get confused with color codes, this capability can be turned off.
249 250 """
250 251 )
251 252 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
252 253 default_value=get_default_colors(), config=True,
253 254 help="Set the color scheme (NoColor, Linux, or LightBG)."
254 255 )
255 256 colors_force = CBool(False, help=
256 257 """
257 258 Force use of ANSI color codes, regardless of OS and readline
258 259 availability.
259 260 """
260 261 # FIXME: This is essentially a hack to allow ZMQShell to show colors
261 262 # without readline on Win32. When the ZMQ formatting system is
262 263 # refactored, this should be removed.
263 264 )
264 265 debug = CBool(False, config=True)
265 266 deep_reload = CBool(False, config=True, help=
266 267 """
267 268 Enable deep (recursive) reloading by default. IPython can use the
268 269 deep_reload module which reloads changes in modules recursively (it
269 270 replaces the reload() function, so you don't need to change anything to
270 271 use it). deep_reload() forces a full reload of modules whose code may
271 272 have changed, which the default reload() function does not. When
272 273 deep_reload is off, IPython will use the normal reload(), but
273 274 deep_reload will still be available as dreload().
274 275 """
275 276 )
276 277 disable_failing_post_execute = CBool(False, config=True,
277 278 help="Don't call post-execute functions that have failed in the past."
278 279 )
279 280 display_formatter = Instance(DisplayFormatter)
280 281 displayhook_class = Type(DisplayHook)
281 282 display_pub_class = Type(DisplayPublisher)
282 283 data_pub_class = None
283 284
284 285 exit_now = CBool(False)
285 286 exiter = Instance(ExitAutocall)
286 287 def _exiter_default(self):
287 288 return ExitAutocall(self)
288 289 # Monotonically increasing execution counter
289 290 execution_count = Integer(1)
290 291 filename = Unicode("<ipython console>")
291 292 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
292 293
293 294 # Input splitter, to transform input line by line and detect when a block
294 295 # is ready to be executed.
295 296 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
296 297 (), {'line_input_checker': True})
297 298
298 299 # This InputSplitter instance is used to transform completed cells before
299 300 # running them. It allows cell magics to contain blank lines.
300 301 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
301 302 (), {'line_input_checker': False})
302 303
303 304 logstart = CBool(False, config=True, help=
304 305 """
305 306 Start logging to the default log file.
306 307 """
307 308 )
308 309 logfile = Unicode('', config=True, help=
309 310 """
310 311 The name of the logfile to use.
311 312 """
312 313 )
313 314 logappend = Unicode('', config=True, help=
314 315 """
315 316 Start logging to the given file in append mode.
316 317 """
317 318 )
318 319 object_info_string_level = Enum((0,1,2), default_value=0,
319 320 config=True)
320 321 pdb = CBool(False, config=True, help=
321 322 """
322 323 Automatically call the pdb debugger after every exception.
323 324 """
324 325 )
325 326 multiline_history = CBool(sys.platform != 'win32', config=True,
326 327 help="Save multi-line entries as one entry in readline history"
327 328 )
328 329
329 330 # deprecated prompt traits:
330 331
331 332 prompt_in1 = Unicode('In [\\#]: ', config=True,
332 333 help="Deprecated, use PromptManager.in_template")
333 334 prompt_in2 = Unicode(' .\\D.: ', config=True,
334 335 help="Deprecated, use PromptManager.in2_template")
335 336 prompt_out = Unicode('Out[\\#]: ', config=True,
336 337 help="Deprecated, use PromptManager.out_template")
337 338 prompts_pad_left = CBool(True, config=True,
338 339 help="Deprecated, use PromptManager.justify")
339 340
340 341 def _prompt_trait_changed(self, name, old, new):
341 342 table = {
342 343 'prompt_in1' : 'in_template',
343 344 'prompt_in2' : 'in2_template',
344 345 'prompt_out' : 'out_template',
345 346 'prompts_pad_left' : 'justify',
346 347 }
347 348 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
348 349 name=name, newname=table[name])
349 350 )
350 351 # protect against weird cases where self.config may not exist:
351 352 if self.config is not None:
352 353 # propagate to corresponding PromptManager trait
353 354 setattr(self.config.PromptManager, table[name], new)
354 355
355 356 _prompt_in1_changed = _prompt_trait_changed
356 357 _prompt_in2_changed = _prompt_trait_changed
357 358 _prompt_out_changed = _prompt_trait_changed
358 359 _prompt_pad_left_changed = _prompt_trait_changed
359 360
360 361 show_rewritten_input = CBool(True, config=True,
361 362 help="Show rewritten input, e.g. for autocall."
362 363 )
363 364
364 365 quiet = CBool(False, config=True)
365 366
366 367 history_length = Integer(10000, config=True)
367 368
368 369 # The readline stuff will eventually be moved to the terminal subclass
369 370 # but for now, we can't do that as readline is welded in everywhere.
370 371 readline_use = CBool(True, config=True)
371 372 readline_remove_delims = Unicode('-/~', config=True)
372 373 readline_delims = Unicode() # set by init_readline()
373 374 # don't use \M- bindings by default, because they
374 375 # conflict with 8-bit encodings. See gh-58,gh-88
375 376 readline_parse_and_bind = List([
376 377 'tab: complete',
377 378 '"\C-l": clear-screen',
378 379 'set show-all-if-ambiguous on',
379 380 '"\C-o": tab-insert',
380 381 '"\C-r": reverse-search-history',
381 382 '"\C-s": forward-search-history',
382 383 '"\C-p": history-search-backward',
383 384 '"\C-n": history-search-forward',
384 385 '"\e[A": history-search-backward',
385 386 '"\e[B": history-search-forward',
386 387 '"\C-k": kill-line',
387 388 '"\C-u": unix-line-discard',
388 389 ], allow_none=False, config=True)
389 390
390 391 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
391 392 default_value='last_expr', config=True,
392 393 help="""
393 394 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
394 395 run interactively (displaying output from expressions).""")
395 396
396 397 # TODO: this part of prompt management should be moved to the frontends.
397 398 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
398 399 separate_in = SeparateUnicode('\n', config=True)
399 400 separate_out = SeparateUnicode('', config=True)
400 401 separate_out2 = SeparateUnicode('', config=True)
401 402 wildcards_case_sensitive = CBool(True, config=True)
402 403 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
403 404 default_value='Context', config=True)
404 405
405 406 # Subcomponents of InteractiveShell
406 407 alias_manager = Instance('IPython.core.alias.AliasManager')
407 408 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
408 409 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
409 410 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
410 411 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
411 412 payload_manager = Instance('IPython.core.payload.PayloadManager')
412 413 history_manager = Instance('IPython.core.history.HistoryManager')
413 414 magics_manager = Instance('IPython.core.magic.MagicsManager')
414 415
415 416 profile_dir = Instance('IPython.core.application.ProfileDir')
416 417 @property
417 418 def profile(self):
418 419 if self.profile_dir is not None:
419 420 name = os.path.basename(self.profile_dir.location)
420 421 return name.replace('profile_','')
421 422
422 423
423 424 # Private interface
424 425 _post_execute = Instance(dict)
425 426
426 427 # Tracks any GUI loop loaded for pylab
427 428 pylab_gui_select = None
428 429
429 430 def __init__(self, ipython_dir=None, profile_dir=None,
430 431 user_module=None, user_ns=None,
431 432 custom_exceptions=((), None), **kwargs):
432 433
433 434 # This is where traits with a config_key argument are updated
434 435 # from the values on config.
435 436 super(InteractiveShell, self).__init__(**kwargs)
436 437 self.configurables = [self]
437 438
438 439 # These are relatively independent and stateless
439 440 self.init_ipython_dir(ipython_dir)
440 441 self.init_profile_dir(profile_dir)
441 442 self.init_instance_attrs()
442 443 self.init_environment()
443 444
444 445 # Check if we're in a virtualenv, and set up sys.path.
445 446 self.init_virtualenv()
446 447
447 448 # Create namespaces (user_ns, user_global_ns, etc.)
448 449 self.init_create_namespaces(user_module, user_ns)
449 450 # This has to be done after init_create_namespaces because it uses
450 451 # something in self.user_ns, but before init_sys_modules, which
451 452 # is the first thing to modify sys.
452 453 # TODO: When we override sys.stdout and sys.stderr before this class
453 454 # is created, we are saving the overridden ones here. Not sure if this
454 455 # is what we want to do.
455 456 self.save_sys_module_state()
456 457 self.init_sys_modules()
457 458
458 459 # While we're trying to have each part of the code directly access what
459 460 # it needs without keeping redundant references to objects, we have too
460 461 # much legacy code that expects ip.db to exist.
461 462 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
462 463
463 464 self.init_history()
464 465 self.init_encoding()
465 466 self.init_prefilter()
466 467
467 468 self.init_syntax_highlighting()
468 469 self.init_hooks()
469 470 self.init_pushd_popd_magic()
470 471 # self.init_traceback_handlers use to be here, but we moved it below
471 472 # because it and init_io have to come after init_readline.
472 473 self.init_user_ns()
473 474 self.init_logger()
474 475 self.init_builtins()
475 476
476 477 # The following was in post_config_initialization
477 478 self.init_inspector()
478 479 # init_readline() must come before init_io(), because init_io uses
479 480 # readline related things.
480 481 self.init_readline()
481 482 # We save this here in case user code replaces raw_input, but it needs
482 483 # to be after init_readline(), because PyPy's readline works by replacing
483 484 # raw_input.
484 485 if py3compat.PY3:
485 486 self.raw_input_original = input
486 487 else:
487 488 self.raw_input_original = raw_input
488 489 # init_completer must come after init_readline, because it needs to
489 490 # know whether readline is present or not system-wide to configure the
490 491 # completers, since the completion machinery can now operate
491 492 # independently of readline (e.g. over the network)
492 493 self.init_completer()
493 494 # TODO: init_io() needs to happen before init_traceback handlers
494 495 # because the traceback handlers hardcode the stdout/stderr streams.
495 496 # This logic in in debugger.Pdb and should eventually be changed.
496 497 self.init_io()
497 498 self.init_traceback_handlers(custom_exceptions)
498 499 self.init_prompts()
499 500 self.init_display_formatter()
500 501 self.init_display_pub()
501 502 self.init_data_pub()
502 503 self.init_displayhook()
503 504 self.init_latextool()
504 505 self.init_magics()
505 506 self.init_alias()
506 507 self.init_logstart()
507 508 self.init_pdb()
508 509 self.init_extension_manager()
509 510 self.init_payload()
510 511 self.init_comms()
511 512 self.hooks.late_startup_hook()
512 513 atexit.register(self.atexit_operations)
513 514
514 515 def get_ipython(self):
515 516 """Return the currently running IPython instance."""
516 517 return self
517 518
518 519 #-------------------------------------------------------------------------
519 520 # Trait changed handlers
520 521 #-------------------------------------------------------------------------
521 522
522 523 def _ipython_dir_changed(self, name, new):
523 524 if not os.path.isdir(new):
524 525 os.makedirs(new, mode = 0o777)
525 526
526 527 def set_autoindent(self,value=None):
527 528 """Set the autoindent flag, checking for readline support.
528 529
529 530 If called with no arguments, it acts as a toggle."""
530 531
531 532 if value != 0 and not self.has_readline:
532 533 if os.name == 'posix':
533 534 warn("The auto-indent feature requires the readline library")
534 535 self.autoindent = 0
535 536 return
536 537 if value is None:
537 538 self.autoindent = not self.autoindent
538 539 else:
539 540 self.autoindent = value
540 541
541 542 #-------------------------------------------------------------------------
542 543 # init_* methods called by __init__
543 544 #-------------------------------------------------------------------------
544 545
545 546 def init_ipython_dir(self, ipython_dir):
546 547 if ipython_dir is not None:
547 548 self.ipython_dir = ipython_dir
548 549 return
549 550
550 551 self.ipython_dir = get_ipython_dir()
551 552
552 553 def init_profile_dir(self, profile_dir):
553 554 if profile_dir is not None:
554 555 self.profile_dir = profile_dir
555 556 return
556 557 self.profile_dir =\
557 558 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
558 559
559 560 def init_instance_attrs(self):
560 561 self.more = False
561 562
562 563 # command compiler
563 564 self.compile = CachingCompiler()
564 565
565 566 # Make an empty namespace, which extension writers can rely on both
566 567 # existing and NEVER being used by ipython itself. This gives them a
567 568 # convenient location for storing additional information and state
568 569 # their extensions may require, without fear of collisions with other
569 570 # ipython names that may develop later.
570 571 self.meta = Struct()
571 572
572 573 # Temporary files used for various purposes. Deleted at exit.
573 574 self.tempfiles = []
574 575
575 576 # Keep track of readline usage (later set by init_readline)
576 577 self.has_readline = False
577 578
578 579 # keep track of where we started running (mainly for crash post-mortem)
579 580 # This is not being used anywhere currently.
580 581 self.starting_dir = os.getcwdu()
581 582
582 583 # Indentation management
583 584 self.indent_current_nsp = 0
584 585
585 586 # Dict to track post-execution functions that have been registered
586 587 self._post_execute = {}
587 588
588 589 def init_environment(self):
589 590 """Any changes we need to make to the user's environment."""
590 591 pass
591 592
592 593 def init_encoding(self):
593 594 # Get system encoding at startup time. Certain terminals (like Emacs
594 595 # under Win32 have it set to None, and we need to have a known valid
595 596 # encoding to use in the raw_input() method
596 597 try:
597 598 self.stdin_encoding = sys.stdin.encoding or 'ascii'
598 599 except AttributeError:
599 600 self.stdin_encoding = 'ascii'
600 601
601 602 def init_syntax_highlighting(self):
602 603 # Python source parser/formatter for syntax highlighting
603 604 pyformat = PyColorize.Parser().format
604 605 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
605 606
606 607 def init_pushd_popd_magic(self):
607 608 # for pushd/popd management
608 609 self.home_dir = get_home_dir()
609 610
610 611 self.dir_stack = []
611 612
612 613 def init_logger(self):
613 614 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
614 615 logmode='rotate')
615 616
616 617 def init_logstart(self):
617 618 """Initialize logging in case it was requested at the command line.
618 619 """
619 620 if self.logappend:
620 621 self.magic('logstart %s append' % self.logappend)
621 622 elif self.logfile:
622 623 self.magic('logstart %s' % self.logfile)
623 624 elif self.logstart:
624 625 self.magic('logstart')
625 626
626 627 def init_builtins(self):
627 628 # A single, static flag that we set to True. Its presence indicates
628 629 # that an IPython shell has been created, and we make no attempts at
629 630 # removing on exit or representing the existence of more than one
630 631 # IPython at a time.
631 632 builtin_mod.__dict__['__IPYTHON__'] = True
632 633
633 634 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
634 635 # manage on enter/exit, but with all our shells it's virtually
635 636 # impossible to get all the cases right. We're leaving the name in for
636 637 # those who adapted their codes to check for this flag, but will
637 638 # eventually remove it after a few more releases.
638 639 builtin_mod.__dict__['__IPYTHON__active'] = \
639 640 'Deprecated, check for __IPYTHON__'
640 641
641 642 self.builtin_trap = BuiltinTrap(shell=self)
642 643
643 644 def init_inspector(self):
644 645 # Object inspector
645 646 self.inspector = oinspect.Inspector(oinspect.InspectColors,
646 647 PyColorize.ANSICodeColors,
647 648 'NoColor',
648 649 self.object_info_string_level)
649 650
650 651 def init_io(self):
651 652 # This will just use sys.stdout and sys.stderr. If you want to
652 653 # override sys.stdout and sys.stderr themselves, you need to do that
653 654 # *before* instantiating this class, because io holds onto
654 655 # references to the underlying streams.
655 656 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
656 657 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
657 658 else:
658 659 io.stdout = io.IOStream(sys.stdout)
659 660 io.stderr = io.IOStream(sys.stderr)
660 661
661 662 def init_prompts(self):
662 663 self.prompt_manager = PromptManager(shell=self, parent=self)
663 664 self.configurables.append(self.prompt_manager)
664 665 # Set system prompts, so that scripts can decide if they are running
665 666 # interactively.
666 667 sys.ps1 = 'In : '
667 668 sys.ps2 = '...: '
668 669 sys.ps3 = 'Out: '
669 670
670 671 def init_display_formatter(self):
671 672 self.display_formatter = DisplayFormatter(parent=self)
672 673 self.configurables.append(self.display_formatter)
673 674
674 675 def init_display_pub(self):
675 676 self.display_pub = self.display_pub_class(parent=self)
676 677 self.configurables.append(self.display_pub)
677 678
678 679 def init_data_pub(self):
679 680 if not self.data_pub_class:
680 681 self.data_pub = None
681 682 return
682 683 self.data_pub = self.data_pub_class(parent=self)
683 684 self.configurables.append(self.data_pub)
684 685
685 686 def init_displayhook(self):
686 687 # Initialize displayhook, set in/out prompts and printing system
687 688 self.displayhook = self.displayhook_class(
688 689 parent=self,
689 690 shell=self,
690 691 cache_size=self.cache_size,
691 692 )
692 693 self.configurables.append(self.displayhook)
693 694 # This is a context manager that installs/revmoes the displayhook at
694 695 # the appropriate time.
695 696 self.display_trap = DisplayTrap(hook=self.displayhook)
696 697
697 698 def init_latextool(self):
698 699 """Configure LaTeXTool."""
699 700 cfg = LaTeXTool.instance(parent=self)
700 701 if cfg not in self.configurables:
701 702 self.configurables.append(cfg)
702 703
703 704 def init_virtualenv(self):
704 705 """Add a virtualenv to sys.path so the user can import modules from it.
705 706 This isn't perfect: it doesn't use the Python interpreter with which the
706 707 virtualenv was built, and it ignores the --no-site-packages option. A
707 708 warning will appear suggesting the user installs IPython in the
708 709 virtualenv, but for many cases, it probably works well enough.
709 710
710 711 Adapted from code snippets online.
711 712
712 713 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
713 714 """
714 715 if 'VIRTUAL_ENV' not in os.environ:
715 716 # Not in a virtualenv
716 717 return
717 718
718 719 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
719 720 # Running properly in the virtualenv, don't need to do anything
720 721 return
721 722
722 723 warn("Attempting to work in a virtualenv. If you encounter problems, please "
723 724 "install IPython inside the virtualenv.")
724 725 if sys.platform == "win32":
725 726 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
726 727 else:
727 728 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
728 729 'python%d.%d' % sys.version_info[:2], 'site-packages')
729 730
730 731 import site
731 732 sys.path.insert(0, virtual_env)
732 733 site.addsitedir(virtual_env)
733 734
734 735 #-------------------------------------------------------------------------
735 736 # Things related to injections into the sys module
736 737 #-------------------------------------------------------------------------
737 738
738 739 def save_sys_module_state(self):
739 740 """Save the state of hooks in the sys module.
740 741
741 742 This has to be called after self.user_module is created.
742 743 """
743 744 self._orig_sys_module_state = {}
744 745 self._orig_sys_module_state['stdin'] = sys.stdin
745 746 self._orig_sys_module_state['stdout'] = sys.stdout
746 747 self._orig_sys_module_state['stderr'] = sys.stderr
747 748 self._orig_sys_module_state['excepthook'] = sys.excepthook
748 749 self._orig_sys_modules_main_name = self.user_module.__name__
749 750 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
750 751
751 752 def restore_sys_module_state(self):
752 753 """Restore the state of the sys module."""
753 754 try:
754 755 for k, v in self._orig_sys_module_state.iteritems():
755 756 setattr(sys, k, v)
756 757 except AttributeError:
757 758 pass
758 759 # Reset what what done in self.init_sys_modules
759 760 if self._orig_sys_modules_main_mod is not None:
760 761 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
761 762
762 763 #-------------------------------------------------------------------------
763 764 # Things related to hooks
764 765 #-------------------------------------------------------------------------
765 766
766 767 def init_hooks(self):
767 768 # hooks holds pointers used for user-side customizations
768 769 self.hooks = Struct()
769 770
770 771 self.strdispatchers = {}
771 772
772 773 # Set all default hooks, defined in the IPython.hooks module.
773 774 hooks = IPython.core.hooks
774 775 for hook_name in hooks.__all__:
775 776 # default hooks have priority 100, i.e. low; user hooks should have
776 777 # 0-100 priority
777 778 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
778 779
779 780 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
780 781 """set_hook(name,hook) -> sets an internal IPython hook.
781 782
782 783 IPython exposes some of its internal API as user-modifiable hooks. By
783 784 adding your function to one of these hooks, you can modify IPython's
784 785 behavior to call at runtime your own routines."""
785 786
786 787 # At some point in the future, this should validate the hook before it
787 788 # accepts it. Probably at least check that the hook takes the number
788 789 # of args it's supposed to.
789 790
790 791 f = types.MethodType(hook,self)
791 792
792 793 # check if the hook is for strdispatcher first
793 794 if str_key is not None:
794 795 sdp = self.strdispatchers.get(name, StrDispatch())
795 796 sdp.add_s(str_key, f, priority )
796 797 self.strdispatchers[name] = sdp
797 798 return
798 799 if re_key is not None:
799 800 sdp = self.strdispatchers.get(name, StrDispatch())
800 801 sdp.add_re(re.compile(re_key), f, priority )
801 802 self.strdispatchers[name] = sdp
802 803 return
803 804
804 805 dp = getattr(self.hooks, name, None)
805 806 if name not in IPython.core.hooks.__all__:
806 807 print("Warning! Hook '%s' is not one of %s" % \
807 808 (name, IPython.core.hooks.__all__ ))
808 809 if not dp:
809 810 dp = IPython.core.hooks.CommandChainDispatcher()
810 811
811 812 try:
812 813 dp.add(f,priority)
813 814 except AttributeError:
814 815 # it was not commandchain, plain old func - replace
815 816 dp = f
816 817
817 818 setattr(self.hooks,name, dp)
818 819
819 820 def register_post_execute(self, func):
820 821 """Register a function for calling after code execution.
821 822 """
822 823 if not callable(func):
823 824 raise ValueError('argument %s must be callable' % func)
824 825 self._post_execute[func] = True
825 826
826 827 #-------------------------------------------------------------------------
827 828 # Things related to the "main" module
828 829 #-------------------------------------------------------------------------
829 830
830 831 def new_main_mod(self, filename, modname):
831 832 """Return a new 'main' module object for user code execution.
832 833
833 834 ``filename`` should be the path of the script which will be run in the
834 835 module. Requests with the same filename will get the same module, with
835 836 its namespace cleared.
836 837
837 838 ``modname`` should be the module name - normally either '__main__' or
838 839 the basename of the file without the extension.
839 840
840 841 When scripts are executed via %run, we must keep a reference to their
841 842 __main__ module around so that Python doesn't
842 843 clear it, rendering references to module globals useless.
843 844
844 845 This method keeps said reference in a private dict, keyed by the
845 846 absolute path of the script. This way, for multiple executions of the
846 847 same script we only keep one copy of the namespace (the last one),
847 848 thus preventing memory leaks from old references while allowing the
848 849 objects from the last execution to be accessible.
849 850 """
850 851 filename = os.path.abspath(filename)
851 852 try:
852 853 main_mod = self._main_mod_cache[filename]
853 854 except KeyError:
854 855 main_mod = self._main_mod_cache[filename] = types.ModuleType(modname,
855 856 doc="Module created for script run in IPython")
856 857 else:
857 858 main_mod.__dict__.clear()
858 859 main_mod.__name__ = modname
859 860
860 861 main_mod.__file__ = filename
861 862 # It seems pydoc (and perhaps others) needs any module instance to
862 863 # implement a __nonzero__ method
863 864 main_mod.__nonzero__ = lambda : True
864 865
865 866 return main_mod
866 867
867 868 def clear_main_mod_cache(self):
868 869 """Clear the cache of main modules.
869 870
870 871 Mainly for use by utilities like %reset.
871 872
872 873 Examples
873 874 --------
874 875
875 876 In [15]: import IPython
876 877
877 878 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
878 879
879 880 In [17]: len(_ip._main_mod_cache) > 0
880 881 Out[17]: True
881 882
882 883 In [18]: _ip.clear_main_mod_cache()
883 884
884 885 In [19]: len(_ip._main_mod_cache) == 0
885 886 Out[19]: True
886 887 """
887 888 self._main_mod_cache.clear()
888 889
889 890 #-------------------------------------------------------------------------
890 891 # Things related to debugging
891 892 #-------------------------------------------------------------------------
892 893
893 894 def init_pdb(self):
894 895 # Set calling of pdb on exceptions
895 896 # self.call_pdb is a property
896 897 self.call_pdb = self.pdb
897 898
898 899 def _get_call_pdb(self):
899 900 return self._call_pdb
900 901
901 902 def _set_call_pdb(self,val):
902 903
903 904 if val not in (0,1,False,True):
904 905 raise ValueError('new call_pdb value must be boolean')
905 906
906 907 # store value in instance
907 908 self._call_pdb = val
908 909
909 910 # notify the actual exception handlers
910 911 self.InteractiveTB.call_pdb = val
911 912
912 913 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
913 914 'Control auto-activation of pdb at exceptions')
914 915
915 916 def debugger(self,force=False):
916 917 """Call the pydb/pdb debugger.
917 918
918 919 Keywords:
919 920
920 921 - force(False): by default, this routine checks the instance call_pdb
921 922 flag and does not actually invoke the debugger if the flag is false.
922 923 The 'force' option forces the debugger to activate even if the flag
923 924 is false.
924 925 """
925 926
926 927 if not (force or self.call_pdb):
927 928 return
928 929
929 930 if not hasattr(sys,'last_traceback'):
930 931 error('No traceback has been produced, nothing to debug.')
931 932 return
932 933
933 934 # use pydb if available
934 935 if debugger.has_pydb:
935 936 from pydb import pm
936 937 else:
937 938 # fallback to our internal debugger
938 939 pm = lambda : self.InteractiveTB.debugger(force=True)
939 940
940 941 with self.readline_no_record:
941 942 pm()
942 943
943 944 #-------------------------------------------------------------------------
944 945 # Things related to IPython's various namespaces
945 946 #-------------------------------------------------------------------------
946 947 default_user_namespaces = True
947 948
948 949 def init_create_namespaces(self, user_module=None, user_ns=None):
949 950 # Create the namespace where the user will operate. user_ns is
950 951 # normally the only one used, and it is passed to the exec calls as
951 952 # the locals argument. But we do carry a user_global_ns namespace
952 953 # given as the exec 'globals' argument, This is useful in embedding
953 954 # situations where the ipython shell opens in a context where the
954 955 # distinction between locals and globals is meaningful. For
955 956 # non-embedded contexts, it is just the same object as the user_ns dict.
956 957
957 958 # FIXME. For some strange reason, __builtins__ is showing up at user
958 959 # level as a dict instead of a module. This is a manual fix, but I
959 960 # should really track down where the problem is coming from. Alex
960 961 # Schmolck reported this problem first.
961 962
962 963 # A useful post by Alex Martelli on this topic:
963 964 # Re: inconsistent value from __builtins__
964 965 # Von: Alex Martelli <aleaxit@yahoo.com>
965 966 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
966 967 # Gruppen: comp.lang.python
967 968
968 969 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
969 970 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
970 971 # > <type 'dict'>
971 972 # > >>> print type(__builtins__)
972 973 # > <type 'module'>
973 974 # > Is this difference in return value intentional?
974 975
975 976 # Well, it's documented that '__builtins__' can be either a dictionary
976 977 # or a module, and it's been that way for a long time. Whether it's
977 978 # intentional (or sensible), I don't know. In any case, the idea is
978 979 # that if you need to access the built-in namespace directly, you
979 980 # should start with "import __builtin__" (note, no 's') which will
980 981 # definitely give you a module. Yeah, it's somewhat confusing:-(.
981 982
982 983 # These routines return a properly built module and dict as needed by
983 984 # the rest of the code, and can also be used by extension writers to
984 985 # generate properly initialized namespaces.
985 986 if (user_ns is not None) or (user_module is not None):
986 987 self.default_user_namespaces = False
987 988 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
988 989
989 990 # A record of hidden variables we have added to the user namespace, so
990 991 # we can list later only variables defined in actual interactive use.
991 992 self.user_ns_hidden = {}
992 993
993 994 # Now that FakeModule produces a real module, we've run into a nasty
994 995 # problem: after script execution (via %run), the module where the user
995 996 # code ran is deleted. Now that this object is a true module (needed
996 997 # so docetst and other tools work correctly), the Python module
997 998 # teardown mechanism runs over it, and sets to None every variable
998 999 # present in that module. Top-level references to objects from the
999 1000 # script survive, because the user_ns is updated with them. However,
1000 1001 # calling functions defined in the script that use other things from
1001 1002 # the script will fail, because the function's closure had references
1002 1003 # to the original objects, which are now all None. So we must protect
1003 1004 # these modules from deletion by keeping a cache.
1004 1005 #
1005 1006 # To avoid keeping stale modules around (we only need the one from the
1006 1007 # last run), we use a dict keyed with the full path to the script, so
1007 1008 # only the last version of the module is held in the cache. Note,
1008 1009 # however, that we must cache the module *namespace contents* (their
1009 1010 # __dict__). Because if we try to cache the actual modules, old ones
1010 1011 # (uncached) could be destroyed while still holding references (such as
1011 1012 # those held by GUI objects that tend to be long-lived)>
1012 1013 #
1013 1014 # The %reset command will flush this cache. See the cache_main_mod()
1014 1015 # and clear_main_mod_cache() methods for details on use.
1015 1016
1016 1017 # This is the cache used for 'main' namespaces
1017 1018 self._main_mod_cache = {}
1018 1019
1019 1020 # A table holding all the namespaces IPython deals with, so that
1020 1021 # introspection facilities can search easily.
1021 1022 self.ns_table = {'user_global':self.user_module.__dict__,
1022 1023 'user_local':self.user_ns,
1023 1024 'builtin':builtin_mod.__dict__
1024 1025 }
1025 1026
1026 1027 @property
1027 1028 def user_global_ns(self):
1028 1029 return self.user_module.__dict__
1029 1030
1030 1031 def prepare_user_module(self, user_module=None, user_ns=None):
1031 1032 """Prepare the module and namespace in which user code will be run.
1032 1033
1033 1034 When IPython is started normally, both parameters are None: a new module
1034 1035 is created automatically, and its __dict__ used as the namespace.
1035 1036
1036 1037 If only user_module is provided, its __dict__ is used as the namespace.
1037 1038 If only user_ns is provided, a dummy module is created, and user_ns
1038 1039 becomes the global namespace. If both are provided (as they may be
1039 1040 when embedding), user_ns is the local namespace, and user_module
1040 1041 provides the global namespace.
1041 1042
1042 1043 Parameters
1043 1044 ----------
1044 1045 user_module : module, optional
1045 1046 The current user module in which IPython is being run. If None,
1046 1047 a clean module will be created.
1047 1048 user_ns : dict, optional
1048 1049 A namespace in which to run interactive commands.
1049 1050
1050 1051 Returns
1051 1052 -------
1052 1053 A tuple of user_module and user_ns, each properly initialised.
1053 1054 """
1054 1055 if user_module is None and user_ns is not None:
1055 1056 user_ns.setdefault("__name__", "__main__")
1056 1057 user_module = DummyMod()
1057 1058 user_module.__dict__ = user_ns
1058 1059
1059 1060 if user_module is None:
1060 1061 user_module = types.ModuleType("__main__",
1061 1062 doc="Automatically created module for IPython interactive environment")
1062 1063
1063 1064 # We must ensure that __builtin__ (without the final 's') is always
1064 1065 # available and pointing to the __builtin__ *module*. For more details:
1065 1066 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1066 1067 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1067 1068 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1068 1069
1069 1070 if user_ns is None:
1070 1071 user_ns = user_module.__dict__
1071 1072
1072 1073 return user_module, user_ns
1073 1074
1074 1075 def init_sys_modules(self):
1075 1076 # We need to insert into sys.modules something that looks like a
1076 1077 # module but which accesses the IPython namespace, for shelve and
1077 1078 # pickle to work interactively. Normally they rely on getting
1078 1079 # everything out of __main__, but for embedding purposes each IPython
1079 1080 # instance has its own private namespace, so we can't go shoving
1080 1081 # everything into __main__.
1081 1082
1082 1083 # note, however, that we should only do this for non-embedded
1083 1084 # ipythons, which really mimic the __main__.__dict__ with their own
1084 1085 # namespace. Embedded instances, on the other hand, should not do
1085 1086 # this because they need to manage the user local/global namespaces
1086 1087 # only, but they live within a 'normal' __main__ (meaning, they
1087 1088 # shouldn't overtake the execution environment of the script they're
1088 1089 # embedded in).
1089 1090
1090 1091 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1091 1092 main_name = self.user_module.__name__
1092 1093 sys.modules[main_name] = self.user_module
1093 1094
1094 1095 def init_user_ns(self):
1095 1096 """Initialize all user-visible namespaces to their minimum defaults.
1096 1097
1097 1098 Certain history lists are also initialized here, as they effectively
1098 1099 act as user namespaces.
1099 1100
1100 1101 Notes
1101 1102 -----
1102 1103 All data structures here are only filled in, they are NOT reset by this
1103 1104 method. If they were not empty before, data will simply be added to
1104 1105 therm.
1105 1106 """
1106 1107 # This function works in two parts: first we put a few things in
1107 1108 # user_ns, and we sync that contents into user_ns_hidden so that these
1108 1109 # initial variables aren't shown by %who. After the sync, we add the
1109 1110 # rest of what we *do* want the user to see with %who even on a new
1110 1111 # session (probably nothing, so theye really only see their own stuff)
1111 1112
1112 1113 # The user dict must *always* have a __builtin__ reference to the
1113 1114 # Python standard __builtin__ namespace, which must be imported.
1114 1115 # This is so that certain operations in prompt evaluation can be
1115 1116 # reliably executed with builtins. Note that we can NOT use
1116 1117 # __builtins__ (note the 's'), because that can either be a dict or a
1117 1118 # module, and can even mutate at runtime, depending on the context
1118 1119 # (Python makes no guarantees on it). In contrast, __builtin__ is
1119 1120 # always a module object, though it must be explicitly imported.
1120 1121
1121 1122 # For more details:
1122 1123 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1123 1124 ns = dict()
1124 1125
1125 1126 # Put 'help' in the user namespace
1126 1127 try:
1127 1128 from site import _Helper
1128 1129 ns['help'] = _Helper()
1129 1130 except ImportError:
1130 1131 warn('help() not available - check site.py')
1131 1132
1132 1133 # make global variables for user access to the histories
1133 1134 ns['_ih'] = self.history_manager.input_hist_parsed
1134 1135 ns['_oh'] = self.history_manager.output_hist
1135 1136 ns['_dh'] = self.history_manager.dir_hist
1136 1137
1137 1138 ns['_sh'] = shadowns
1138 1139
1139 1140 # user aliases to input and output histories. These shouldn't show up
1140 1141 # in %who, as they can have very large reprs.
1141 1142 ns['In'] = self.history_manager.input_hist_parsed
1142 1143 ns['Out'] = self.history_manager.output_hist
1143 1144
1144 1145 # Store myself as the public api!!!
1145 1146 ns['get_ipython'] = self.get_ipython
1146 1147
1147 1148 ns['exit'] = self.exiter
1148 1149 ns['quit'] = self.exiter
1149 1150
1150 1151 # Sync what we've added so far to user_ns_hidden so these aren't seen
1151 1152 # by %who
1152 1153 self.user_ns_hidden.update(ns)
1153 1154
1154 1155 # Anything put into ns now would show up in %who. Think twice before
1155 1156 # putting anything here, as we really want %who to show the user their
1156 1157 # stuff, not our variables.
1157 1158
1158 1159 # Finally, update the real user's namespace
1159 1160 self.user_ns.update(ns)
1160 1161
1161 1162 @property
1162 1163 def all_ns_refs(self):
1163 1164 """Get a list of references to all the namespace dictionaries in which
1164 1165 IPython might store a user-created object.
1165 1166
1166 1167 Note that this does not include the displayhook, which also caches
1167 1168 objects from the output."""
1168 1169 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1169 1170 [m.__dict__ for m in self._main_mod_cache.values()]
1170 1171
1171 1172 def reset(self, new_session=True):
1172 1173 """Clear all internal namespaces, and attempt to release references to
1173 1174 user objects.
1174 1175
1175 1176 If new_session is True, a new history session will be opened.
1176 1177 """
1177 1178 # Clear histories
1178 1179 self.history_manager.reset(new_session)
1179 1180 # Reset counter used to index all histories
1180 1181 if new_session:
1181 1182 self.execution_count = 1
1182 1183
1183 1184 # Flush cached output items
1184 1185 if self.displayhook.do_full_cache:
1185 1186 self.displayhook.flush()
1186 1187
1187 1188 # The main execution namespaces must be cleared very carefully,
1188 1189 # skipping the deletion of the builtin-related keys, because doing so
1189 1190 # would cause errors in many object's __del__ methods.
1190 1191 if self.user_ns is not self.user_global_ns:
1191 1192 self.user_ns.clear()
1192 1193 ns = self.user_global_ns
1193 1194 drop_keys = set(ns.keys())
1194 1195 drop_keys.discard('__builtin__')
1195 1196 drop_keys.discard('__builtins__')
1196 1197 drop_keys.discard('__name__')
1197 1198 for k in drop_keys:
1198 1199 del ns[k]
1199 1200
1200 1201 self.user_ns_hidden.clear()
1201 1202
1202 1203 # Restore the user namespaces to minimal usability
1203 1204 self.init_user_ns()
1204 1205
1205 1206 # Restore the default and user aliases
1206 1207 self.alias_manager.clear_aliases()
1207 1208 self.alias_manager.init_aliases()
1208 1209
1209 1210 # Flush the private list of module references kept for script
1210 1211 # execution protection
1211 1212 self.clear_main_mod_cache()
1212 1213
1213 1214 def del_var(self, varname, by_name=False):
1214 1215 """Delete a variable from the various namespaces, so that, as
1215 1216 far as possible, we're not keeping any hidden references to it.
1216 1217
1217 1218 Parameters
1218 1219 ----------
1219 1220 varname : str
1220 1221 The name of the variable to delete.
1221 1222 by_name : bool
1222 1223 If True, delete variables with the given name in each
1223 1224 namespace. If False (default), find the variable in the user
1224 1225 namespace, and delete references to it.
1225 1226 """
1226 1227 if varname in ('__builtin__', '__builtins__'):
1227 1228 raise ValueError("Refusing to delete %s" % varname)
1228 1229
1229 1230 ns_refs = self.all_ns_refs
1230 1231
1231 1232 if by_name: # Delete by name
1232 1233 for ns in ns_refs:
1233 1234 try:
1234 1235 del ns[varname]
1235 1236 except KeyError:
1236 1237 pass
1237 1238 else: # Delete by object
1238 1239 try:
1239 1240 obj = self.user_ns[varname]
1240 1241 except KeyError:
1241 1242 raise NameError("name '%s' is not defined" % varname)
1242 1243 # Also check in output history
1243 1244 ns_refs.append(self.history_manager.output_hist)
1244 1245 for ns in ns_refs:
1245 1246 to_delete = [n for n, o in ns.iteritems() if o is obj]
1246 1247 for name in to_delete:
1247 1248 del ns[name]
1248 1249
1249 1250 # displayhook keeps extra references, but not in a dictionary
1250 1251 for name in ('_', '__', '___'):
1251 1252 if getattr(self.displayhook, name) is obj:
1252 1253 setattr(self.displayhook, name, None)
1253 1254
1254 1255 def reset_selective(self, regex=None):
1255 1256 """Clear selective variables from internal namespaces based on a
1256 1257 specified regular expression.
1257 1258
1258 1259 Parameters
1259 1260 ----------
1260 1261 regex : string or compiled pattern, optional
1261 1262 A regular expression pattern that will be used in searching
1262 1263 variable names in the users namespaces.
1263 1264 """
1264 1265 if regex is not None:
1265 1266 try:
1266 1267 m = re.compile(regex)
1267 1268 except TypeError:
1268 1269 raise TypeError('regex must be a string or compiled pattern')
1269 1270 # Search for keys in each namespace that match the given regex
1270 1271 # If a match is found, delete the key/value pair.
1271 1272 for ns in self.all_ns_refs:
1272 1273 for var in ns:
1273 1274 if m.search(var):
1274 1275 del ns[var]
1275 1276
1276 1277 def push(self, variables, interactive=True):
1277 1278 """Inject a group of variables into the IPython user namespace.
1278 1279
1279 1280 Parameters
1280 1281 ----------
1281 1282 variables : dict, str or list/tuple of str
1282 1283 The variables to inject into the user's namespace. If a dict, a
1283 1284 simple update is done. If a str, the string is assumed to have
1284 1285 variable names separated by spaces. A list/tuple of str can also
1285 1286 be used to give the variable names. If just the variable names are
1286 1287 give (list/tuple/str) then the variable values looked up in the
1287 1288 callers frame.
1288 1289 interactive : bool
1289 1290 If True (default), the variables will be listed with the ``who``
1290 1291 magic.
1291 1292 """
1292 1293 vdict = None
1293 1294
1294 1295 # We need a dict of name/value pairs to do namespace updates.
1295 1296 if isinstance(variables, dict):
1296 1297 vdict = variables
1297 1298 elif isinstance(variables, string_types+(list, tuple)):
1298 1299 if isinstance(variables, string_types):
1299 1300 vlist = variables.split()
1300 1301 else:
1301 1302 vlist = variables
1302 1303 vdict = {}
1303 1304 cf = sys._getframe(1)
1304 1305 for name in vlist:
1305 1306 try:
1306 1307 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1307 1308 except:
1308 1309 print('Could not get variable %s from %s' %
1309 1310 (name,cf.f_code.co_name))
1310 1311 else:
1311 1312 raise ValueError('variables must be a dict/str/list/tuple')
1312 1313
1313 1314 # Propagate variables to user namespace
1314 1315 self.user_ns.update(vdict)
1315 1316
1316 1317 # And configure interactive visibility
1317 1318 user_ns_hidden = self.user_ns_hidden
1318 1319 if interactive:
1319 1320 for name in vdict:
1320 1321 user_ns_hidden.pop(name, None)
1321 1322 else:
1322 1323 user_ns_hidden.update(vdict)
1323 1324
1324 1325 def drop_by_id(self, variables):
1325 1326 """Remove a dict of variables from the user namespace, if they are the
1326 1327 same as the values in the dictionary.
1327 1328
1328 1329 This is intended for use by extensions: variables that they've added can
1329 1330 be taken back out if they are unloaded, without removing any that the
1330 1331 user has overwritten.
1331 1332
1332 1333 Parameters
1333 1334 ----------
1334 1335 variables : dict
1335 1336 A dictionary mapping object names (as strings) to the objects.
1336 1337 """
1337 1338 for name, obj in variables.iteritems():
1338 1339 if name in self.user_ns and self.user_ns[name] is obj:
1339 1340 del self.user_ns[name]
1340 1341 self.user_ns_hidden.pop(name, None)
1341 1342
1342 1343 #-------------------------------------------------------------------------
1343 1344 # Things related to object introspection
1344 1345 #-------------------------------------------------------------------------
1345 1346
1346 1347 def _ofind(self, oname, namespaces=None):
1347 1348 """Find an object in the available namespaces.
1348 1349
1349 1350 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1350 1351
1351 1352 Has special code to detect magic functions.
1352 1353 """
1353 1354 oname = oname.strip()
1354 1355 #print '1- oname: <%r>' % oname # dbg
1355 1356 if not oname.startswith(ESC_MAGIC) and \
1356 1357 not oname.startswith(ESC_MAGIC2) and \
1357 1358 not py3compat.isidentifier(oname, dotted=True):
1358 1359 return dict(found=False)
1359 1360
1360 1361 alias_ns = None
1361 1362 if namespaces is None:
1362 1363 # Namespaces to search in:
1363 1364 # Put them in a list. The order is important so that we
1364 1365 # find things in the same order that Python finds them.
1365 1366 namespaces = [ ('Interactive', self.user_ns),
1366 1367 ('Interactive (global)', self.user_global_ns),
1367 1368 ('Python builtin', builtin_mod.__dict__),
1368 1369 ]
1369 1370
1370 1371 # initialize results to 'null'
1371 1372 found = False; obj = None; ospace = None; ds = None;
1372 1373 ismagic = False; isalias = False; parent = None
1373 1374
1374 1375 # We need to special-case 'print', which as of python2.6 registers as a
1375 1376 # function but should only be treated as one if print_function was
1376 1377 # loaded with a future import. In this case, just bail.
1377 1378 if (oname == 'print' and not py3compat.PY3 and not \
1378 1379 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1379 1380 return {'found':found, 'obj':obj, 'namespace':ospace,
1380 1381 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1381 1382
1382 1383 # Look for the given name by splitting it in parts. If the head is
1383 1384 # found, then we look for all the remaining parts as members, and only
1384 1385 # declare success if we can find them all.
1385 1386 oname_parts = oname.split('.')
1386 1387 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1387 1388 for nsname,ns in namespaces:
1388 1389 try:
1389 1390 obj = ns[oname_head]
1390 1391 except KeyError:
1391 1392 continue
1392 1393 else:
1393 1394 #print 'oname_rest:', oname_rest # dbg
1394 1395 for part in oname_rest:
1395 1396 try:
1396 1397 parent = obj
1397 1398 obj = getattr(obj,part)
1398 1399 except:
1399 1400 # Blanket except b/c some badly implemented objects
1400 1401 # allow __getattr__ to raise exceptions other than
1401 1402 # AttributeError, which then crashes IPython.
1402 1403 break
1403 1404 else:
1404 1405 # If we finish the for loop (no break), we got all members
1405 1406 found = True
1406 1407 ospace = nsname
1407 1408 break # namespace loop
1408 1409
1409 1410 # Try to see if it's magic
1410 1411 if not found:
1411 1412 obj = None
1412 1413 if oname.startswith(ESC_MAGIC2):
1413 1414 oname = oname.lstrip(ESC_MAGIC2)
1414 1415 obj = self.find_cell_magic(oname)
1415 1416 elif oname.startswith(ESC_MAGIC):
1416 1417 oname = oname.lstrip(ESC_MAGIC)
1417 1418 obj = self.find_line_magic(oname)
1418 1419 else:
1419 1420 # search without prefix, so run? will find %run?
1420 1421 obj = self.find_line_magic(oname)
1421 1422 if obj is None:
1422 1423 obj = self.find_cell_magic(oname)
1423 1424 if obj is not None:
1424 1425 found = True
1425 1426 ospace = 'IPython internal'
1426 1427 ismagic = True
1427 1428
1428 1429 # Last try: special-case some literals like '', [], {}, etc:
1429 1430 if not found and oname_head in ["''",'""','[]','{}','()']:
1430 1431 obj = eval(oname_head)
1431 1432 found = True
1432 1433 ospace = 'Interactive'
1433 1434
1434 1435 return {'found':found, 'obj':obj, 'namespace':ospace,
1435 1436 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1436 1437
1437 1438 def _ofind_property(self, oname, info):
1438 1439 """Second part of object finding, to look for property details."""
1439 1440 if info.found:
1440 1441 # Get the docstring of the class property if it exists.
1441 1442 path = oname.split('.')
1442 1443 root = '.'.join(path[:-1])
1443 1444 if info.parent is not None:
1444 1445 try:
1445 1446 target = getattr(info.parent, '__class__')
1446 1447 # The object belongs to a class instance.
1447 1448 try:
1448 1449 target = getattr(target, path[-1])
1449 1450 # The class defines the object.
1450 1451 if isinstance(target, property):
1451 1452 oname = root + '.__class__.' + path[-1]
1452 1453 info = Struct(self._ofind(oname))
1453 1454 except AttributeError: pass
1454 1455 except AttributeError: pass
1455 1456
1456 1457 # We return either the new info or the unmodified input if the object
1457 1458 # hadn't been found
1458 1459 return info
1459 1460
1460 1461 def _object_find(self, oname, namespaces=None):
1461 1462 """Find an object and return a struct with info about it."""
1462 1463 inf = Struct(self._ofind(oname, namespaces))
1463 1464 return Struct(self._ofind_property(oname, inf))
1464 1465
1465 1466 def _inspect(self, meth, oname, namespaces=None, **kw):
1466 1467 """Generic interface to the inspector system.
1467 1468
1468 1469 This function is meant to be called by pdef, pdoc & friends."""
1469 1470 info = self._object_find(oname, namespaces)
1470 1471 if info.found:
1471 1472 pmethod = getattr(self.inspector, meth)
1472 1473 formatter = format_screen if info.ismagic else None
1473 1474 if meth == 'pdoc':
1474 1475 pmethod(info.obj, oname, formatter)
1475 1476 elif meth == 'pinfo':
1476 1477 pmethod(info.obj, oname, formatter, info, **kw)
1477 1478 else:
1478 1479 pmethod(info.obj, oname)
1479 1480 else:
1480 1481 print('Object `%s` not found.' % oname)
1481 1482 return 'not found' # so callers can take other action
1482 1483
1483 1484 def object_inspect(self, oname, detail_level=0):
1484 1485 with self.builtin_trap:
1485 1486 info = self._object_find(oname)
1486 1487 if info.found:
1487 1488 return self.inspector.info(info.obj, oname, info=info,
1488 1489 detail_level=detail_level
1489 1490 )
1490 1491 else:
1491 1492 return oinspect.object_info(name=oname, found=False)
1492 1493
1493 1494 #-------------------------------------------------------------------------
1494 1495 # Things related to history management
1495 1496 #-------------------------------------------------------------------------
1496 1497
1497 1498 def init_history(self):
1498 1499 """Sets up the command history, and starts regular autosaves."""
1499 1500 self.history_manager = HistoryManager(shell=self, parent=self)
1500 1501 self.configurables.append(self.history_manager)
1501 1502
1502 1503 #-------------------------------------------------------------------------
1503 1504 # Things related to exception handling and tracebacks (not debugging)
1504 1505 #-------------------------------------------------------------------------
1505 1506
1506 1507 def init_traceback_handlers(self, custom_exceptions):
1507 1508 # Syntax error handler.
1508 1509 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1509 1510
1510 1511 # The interactive one is initialized with an offset, meaning we always
1511 1512 # want to remove the topmost item in the traceback, which is our own
1512 1513 # internal code. Valid modes: ['Plain','Context','Verbose']
1513 1514 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1514 1515 color_scheme='NoColor',
1515 1516 tb_offset = 1,
1516 1517 check_cache=check_linecache_ipython)
1517 1518
1518 1519 # The instance will store a pointer to the system-wide exception hook,
1519 1520 # so that runtime code (such as magics) can access it. This is because
1520 1521 # during the read-eval loop, it may get temporarily overwritten.
1521 1522 self.sys_excepthook = sys.excepthook
1522 1523
1523 1524 # and add any custom exception handlers the user may have specified
1524 1525 self.set_custom_exc(*custom_exceptions)
1525 1526
1526 1527 # Set the exception mode
1527 1528 self.InteractiveTB.set_mode(mode=self.xmode)
1528 1529
1529 1530 def set_custom_exc(self, exc_tuple, handler):
1530 1531 """set_custom_exc(exc_tuple,handler)
1531 1532
1532 1533 Set a custom exception handler, which will be called if any of the
1533 1534 exceptions in exc_tuple occur in the mainloop (specifically, in the
1534 1535 run_code() method).
1535 1536
1536 1537 Parameters
1537 1538 ----------
1538 1539
1539 1540 exc_tuple : tuple of exception classes
1540 1541 A *tuple* of exception classes, for which to call the defined
1541 1542 handler. It is very important that you use a tuple, and NOT A
1542 1543 LIST here, because of the way Python's except statement works. If
1543 1544 you only want to trap a single exception, use a singleton tuple::
1544 1545
1545 1546 exc_tuple == (MyCustomException,)
1546 1547
1547 1548 handler : callable
1548 1549 handler must have the following signature::
1549 1550
1550 1551 def my_handler(self, etype, value, tb, tb_offset=None):
1551 1552 ...
1552 1553 return structured_traceback
1553 1554
1554 1555 Your handler must return a structured traceback (a list of strings),
1555 1556 or None.
1556 1557
1557 1558 This will be made into an instance method (via types.MethodType)
1558 1559 of IPython itself, and it will be called if any of the exceptions
1559 1560 listed in the exc_tuple are caught. If the handler is None, an
1560 1561 internal basic one is used, which just prints basic info.
1561 1562
1562 1563 To protect IPython from crashes, if your handler ever raises an
1563 1564 exception or returns an invalid result, it will be immediately
1564 1565 disabled.
1565 1566
1566 1567 WARNING: by putting in your own exception handler into IPython's main
1567 1568 execution loop, you run a very good chance of nasty crashes. This
1568 1569 facility should only be used if you really know what you are doing."""
1569 1570
1570 1571 assert type(exc_tuple)==type(()) , \
1571 1572 "The custom exceptions must be given AS A TUPLE."
1572 1573
1573 1574 def dummy_handler(self,etype,value,tb,tb_offset=None):
1574 1575 print('*** Simple custom exception handler ***')
1575 1576 print('Exception type :',etype)
1576 1577 print('Exception value:',value)
1577 1578 print('Traceback :',tb)
1578 1579 #print 'Source code :','\n'.join(self.buffer)
1579 1580
1580 1581 def validate_stb(stb):
1581 1582 """validate structured traceback return type
1582 1583
1583 1584 return type of CustomTB *should* be a list of strings, but allow
1584 1585 single strings or None, which are harmless.
1585 1586
1586 1587 This function will *always* return a list of strings,
1587 1588 and will raise a TypeError if stb is inappropriate.
1588 1589 """
1589 1590 msg = "CustomTB must return list of strings, not %r" % stb
1590 1591 if stb is None:
1591 1592 return []
1592 1593 elif isinstance(stb, string_types):
1593 1594 return [stb]
1594 1595 elif not isinstance(stb, list):
1595 1596 raise TypeError(msg)
1596 1597 # it's a list
1597 1598 for line in stb:
1598 1599 # check every element
1599 1600 if not isinstance(line, string_types):
1600 1601 raise TypeError(msg)
1601 1602 return stb
1602 1603
1603 1604 if handler is None:
1604 1605 wrapped = dummy_handler
1605 1606 else:
1606 1607 def wrapped(self,etype,value,tb,tb_offset=None):
1607 1608 """wrap CustomTB handler, to protect IPython from user code
1608 1609
1609 1610 This makes it harder (but not impossible) for custom exception
1610 1611 handlers to crash IPython.
1611 1612 """
1612 1613 try:
1613 1614 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1614 1615 return validate_stb(stb)
1615 1616 except:
1616 1617 # clear custom handler immediately
1617 1618 self.set_custom_exc((), None)
1618 1619 print("Custom TB Handler failed, unregistering", file=io.stderr)
1619 1620 # show the exception in handler first
1620 1621 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1621 1622 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1622 1623 print("The original exception:", file=io.stdout)
1623 1624 stb = self.InteractiveTB.structured_traceback(
1624 1625 (etype,value,tb), tb_offset=tb_offset
1625 1626 )
1626 1627 return stb
1627 1628
1628 1629 self.CustomTB = types.MethodType(wrapped,self)
1629 1630 self.custom_exceptions = exc_tuple
1630 1631
1631 1632 def excepthook(self, etype, value, tb):
1632 1633 """One more defense for GUI apps that call sys.excepthook.
1633 1634
1634 1635 GUI frameworks like wxPython trap exceptions and call
1635 1636 sys.excepthook themselves. I guess this is a feature that
1636 1637 enables them to keep running after exceptions that would
1637 1638 otherwise kill their mainloop. This is a bother for IPython
1638 1639 which excepts to catch all of the program exceptions with a try:
1639 1640 except: statement.
1640 1641
1641 1642 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1642 1643 any app directly invokes sys.excepthook, it will look to the user like
1643 1644 IPython crashed. In order to work around this, we can disable the
1644 1645 CrashHandler and replace it with this excepthook instead, which prints a
1645 1646 regular traceback using our InteractiveTB. In this fashion, apps which
1646 1647 call sys.excepthook will generate a regular-looking exception from
1647 1648 IPython, and the CrashHandler will only be triggered by real IPython
1648 1649 crashes.
1649 1650
1650 1651 This hook should be used sparingly, only in places which are not likely
1651 1652 to be true IPython errors.
1652 1653 """
1653 1654 self.showtraceback((etype,value,tb),tb_offset=0)
1654 1655
1655 1656 def _get_exc_info(self, exc_tuple=None):
1656 1657 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1657 1658
1658 1659 Ensures sys.last_type,value,traceback hold the exc_info we found,
1659 1660 from whichever source.
1660 1661
1661 1662 raises ValueError if none of these contain any information
1662 1663 """
1663 1664 if exc_tuple is None:
1664 1665 etype, value, tb = sys.exc_info()
1665 1666 else:
1666 1667 etype, value, tb = exc_tuple
1667 1668
1668 1669 if etype is None:
1669 1670 if hasattr(sys, 'last_type'):
1670 1671 etype, value, tb = sys.last_type, sys.last_value, \
1671 1672 sys.last_traceback
1672 1673
1673 1674 if etype is None:
1674 1675 raise ValueError("No exception to find")
1675 1676
1676 1677 # Now store the exception info in sys.last_type etc.
1677 1678 # WARNING: these variables are somewhat deprecated and not
1678 1679 # necessarily safe to use in a threaded environment, but tools
1679 1680 # like pdb depend on their existence, so let's set them. If we
1680 1681 # find problems in the field, we'll need to revisit their use.
1681 1682 sys.last_type = etype
1682 1683 sys.last_value = value
1683 1684 sys.last_traceback = tb
1684 1685
1685 1686 return etype, value, tb
1686 1687
1687 1688 def show_usage_error(self, exc):
1688 1689 """Show a short message for UsageErrors
1689 1690
1690 1691 These are special exceptions that shouldn't show a traceback.
1691 1692 """
1692 1693 self.write_err("UsageError: %s" % exc)
1693 1694
1694 1695 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1695 1696 exception_only=False):
1696 1697 """Display the exception that just occurred.
1697 1698
1698 1699 If nothing is known about the exception, this is the method which
1699 1700 should be used throughout the code for presenting user tracebacks,
1700 1701 rather than directly invoking the InteractiveTB object.
1701 1702
1702 1703 A specific showsyntaxerror() also exists, but this method can take
1703 1704 care of calling it if needed, so unless you are explicitly catching a
1704 1705 SyntaxError exception, don't try to analyze the stack manually and
1705 1706 simply call this method."""
1706 1707
1707 1708 try:
1708 1709 try:
1709 1710 etype, value, tb = self._get_exc_info(exc_tuple)
1710 1711 except ValueError:
1711 1712 self.write_err('No traceback available to show.\n')
1712 1713 return
1713 1714
1714 1715 if issubclass(etype, SyntaxError):
1715 1716 # Though this won't be called by syntax errors in the input
1716 1717 # line, there may be SyntaxError cases with imported code.
1717 1718 self.showsyntaxerror(filename)
1718 1719 elif etype is UsageError:
1719 1720 self.show_usage_error(value)
1720 1721 else:
1721 1722 if exception_only:
1722 1723 stb = ['An exception has occurred, use %tb to see '
1723 1724 'the full traceback.\n']
1724 1725 stb.extend(self.InteractiveTB.get_exception_only(etype,
1725 1726 value))
1726 1727 else:
1727 1728 try:
1728 1729 # Exception classes can customise their traceback - we
1729 1730 # use this in IPython.parallel for exceptions occurring
1730 1731 # in the engines. This should return a list of strings.
1731 1732 stb = value._render_traceback_()
1732 1733 except Exception:
1733 1734 stb = self.InteractiveTB.structured_traceback(etype,
1734 1735 value, tb, tb_offset=tb_offset)
1735 1736
1736 1737 self._showtraceback(etype, value, stb)
1737 1738 if self.call_pdb:
1738 1739 # drop into debugger
1739 1740 self.debugger(force=True)
1740 1741 return
1741 1742
1742 1743 # Actually show the traceback
1743 1744 self._showtraceback(etype, value, stb)
1744 1745
1745 1746 except KeyboardInterrupt:
1746 1747 self.write_err("\nKeyboardInterrupt\n")
1747 1748
1748 1749 def _showtraceback(self, etype, evalue, stb):
1749 1750 """Actually show a traceback.
1750 1751
1751 1752 Subclasses may override this method to put the traceback on a different
1752 1753 place, like a side channel.
1753 1754 """
1754 1755 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1755 1756
1756 1757 def showsyntaxerror(self, filename=None):
1757 1758 """Display the syntax error that just occurred.
1758 1759
1759 1760 This doesn't display a stack trace because there isn't one.
1760 1761
1761 1762 If a filename is given, it is stuffed in the exception instead
1762 1763 of what was there before (because Python's parser always uses
1763 1764 "<string>" when reading from a string).
1764 1765 """
1765 1766 etype, value, last_traceback = self._get_exc_info()
1766 1767
1767 1768 if filename and issubclass(etype, SyntaxError):
1768 1769 try:
1769 1770 value.filename = filename
1770 1771 except:
1771 1772 # Not the format we expect; leave it alone
1772 1773 pass
1773 1774
1774 1775 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1775 1776 self._showtraceback(etype, value, stb)
1776 1777
1777 1778 # This is overridden in TerminalInteractiveShell to show a message about
1778 1779 # the %paste magic.
1779 1780 def showindentationerror(self):
1780 1781 """Called by run_cell when there's an IndentationError in code entered
1781 1782 at the prompt.
1782 1783
1783 1784 This is overridden in TerminalInteractiveShell to show a message about
1784 1785 the %paste magic."""
1785 1786 self.showsyntaxerror()
1786 1787
1787 1788 #-------------------------------------------------------------------------
1788 1789 # Things related to readline
1789 1790 #-------------------------------------------------------------------------
1790 1791
1791 1792 def init_readline(self):
1792 1793 """Command history completion/saving/reloading."""
1793 1794
1794 1795 if self.readline_use:
1795 1796 import IPython.utils.rlineimpl as readline
1796 1797
1797 1798 self.rl_next_input = None
1798 1799 self.rl_do_indent = False
1799 1800
1800 1801 if not self.readline_use or not readline.have_readline:
1801 1802 self.has_readline = False
1802 1803 self.readline = None
1803 1804 # Set a number of methods that depend on readline to be no-op
1804 1805 self.readline_no_record = no_op_context
1805 1806 self.set_readline_completer = no_op
1806 1807 self.set_custom_completer = no_op
1807 1808 if self.readline_use:
1808 1809 warn('Readline services not available or not loaded.')
1809 1810 else:
1810 1811 self.has_readline = True
1811 1812 self.readline = readline
1812 1813 sys.modules['readline'] = readline
1813 1814
1814 1815 # Platform-specific configuration
1815 1816 if os.name == 'nt':
1816 1817 # FIXME - check with Frederick to see if we can harmonize
1817 1818 # naming conventions with pyreadline to avoid this
1818 1819 # platform-dependent check
1819 1820 self.readline_startup_hook = readline.set_pre_input_hook
1820 1821 else:
1821 1822 self.readline_startup_hook = readline.set_startup_hook
1822 1823
1823 1824 # Load user's initrc file (readline config)
1824 1825 # Or if libedit is used, load editrc.
1825 1826 inputrc_name = os.environ.get('INPUTRC')
1826 1827 if inputrc_name is None:
1827 1828 inputrc_name = '.inputrc'
1828 1829 if readline.uses_libedit:
1829 1830 inputrc_name = '.editrc'
1830 1831 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1831 1832 if os.path.isfile(inputrc_name):
1832 1833 try:
1833 1834 readline.read_init_file(inputrc_name)
1834 1835 except:
1835 1836 warn('Problems reading readline initialization file <%s>'
1836 1837 % inputrc_name)
1837 1838
1838 1839 # Configure readline according to user's prefs
1839 1840 # This is only done if GNU readline is being used. If libedit
1840 1841 # is being used (as on Leopard) the readline config is
1841 1842 # not run as the syntax for libedit is different.
1842 1843 if not readline.uses_libedit:
1843 1844 for rlcommand in self.readline_parse_and_bind:
1844 1845 #print "loading rl:",rlcommand # dbg
1845 1846 readline.parse_and_bind(rlcommand)
1846 1847
1847 1848 # Remove some chars from the delimiters list. If we encounter
1848 1849 # unicode chars, discard them.
1849 1850 delims = readline.get_completer_delims()
1850 1851 if not py3compat.PY3:
1851 1852 delims = delims.encode("ascii", "ignore")
1852 1853 for d in self.readline_remove_delims:
1853 1854 delims = delims.replace(d, "")
1854 1855 delims = delims.replace(ESC_MAGIC, '')
1855 1856 readline.set_completer_delims(delims)
1856 1857 # Store these so we can restore them if something like rpy2 modifies
1857 1858 # them.
1858 1859 self.readline_delims = delims
1859 1860 # otherwise we end up with a monster history after a while:
1860 1861 readline.set_history_length(self.history_length)
1861 1862
1862 1863 self.refill_readline_hist()
1863 1864 self.readline_no_record = ReadlineNoRecord(self)
1864 1865
1865 1866 # Configure auto-indent for all platforms
1866 1867 self.set_autoindent(self.autoindent)
1867 1868
1868 1869 def refill_readline_hist(self):
1869 1870 # Load the last 1000 lines from history
1870 1871 self.readline.clear_history()
1871 1872 stdin_encoding = sys.stdin.encoding or "utf-8"
1872 1873 last_cell = u""
1873 1874 for _, _, cell in self.history_manager.get_tail(1000,
1874 1875 include_latest=True):
1875 1876 # Ignore blank lines and consecutive duplicates
1876 1877 cell = cell.rstrip()
1877 1878 if cell and (cell != last_cell):
1878 1879 try:
1879 1880 if self.multiline_history:
1880 1881 self.readline.add_history(py3compat.unicode_to_str(cell,
1881 1882 stdin_encoding))
1882 1883 else:
1883 1884 for line in cell.splitlines():
1884 1885 self.readline.add_history(py3compat.unicode_to_str(line,
1885 1886 stdin_encoding))
1886 1887 last_cell = cell
1887 1888
1888 1889 except TypeError:
1889 1890 # The history DB can get corrupted so it returns strings
1890 1891 # containing null bytes, which readline objects to.
1891 1892 continue
1892 1893
1893 1894 @skip_doctest
1894 1895 def set_next_input(self, s):
1895 1896 """ Sets the 'default' input string for the next command line.
1896 1897
1897 1898 Requires readline.
1898 1899
1899 1900 Example::
1900 1901
1901 1902 In [1]: _ip.set_next_input("Hello Word")
1902 1903 In [2]: Hello Word_ # cursor is here
1903 1904 """
1904 1905 self.rl_next_input = py3compat.cast_bytes_py2(s)
1905 1906
1906 1907 # Maybe move this to the terminal subclass?
1907 1908 def pre_readline(self):
1908 1909 """readline hook to be used at the start of each line.
1909 1910
1910 1911 Currently it handles auto-indent only."""
1911 1912
1912 1913 if self.rl_do_indent:
1913 1914 self.readline.insert_text(self._indent_current_str())
1914 1915 if self.rl_next_input is not None:
1915 1916 self.readline.insert_text(self.rl_next_input)
1916 1917 self.rl_next_input = None
1917 1918
1918 1919 def _indent_current_str(self):
1919 1920 """return the current level of indentation as a string"""
1920 1921 return self.input_splitter.indent_spaces * ' '
1921 1922
1922 1923 #-------------------------------------------------------------------------
1923 1924 # Things related to text completion
1924 1925 #-------------------------------------------------------------------------
1925 1926
1926 1927 def init_completer(self):
1927 1928 """Initialize the completion machinery.
1928 1929
1929 1930 This creates completion machinery that can be used by client code,
1930 1931 either interactively in-process (typically triggered by the readline
1931 1932 library), programatically (such as in test suites) or out-of-prcess
1932 1933 (typically over the network by remote frontends).
1933 1934 """
1934 1935 from IPython.core.completer import IPCompleter
1935 1936 from IPython.core.completerlib import (module_completer,
1936 1937 magic_run_completer, cd_completer, reset_completer)
1937 1938
1938 1939 self.Completer = IPCompleter(shell=self,
1939 1940 namespace=self.user_ns,
1940 1941 global_namespace=self.user_global_ns,
1941 1942 use_readline=self.has_readline,
1942 1943 parent=self,
1943 1944 )
1944 1945 self.configurables.append(self.Completer)
1945 1946
1946 1947 # Add custom completers to the basic ones built into IPCompleter
1947 1948 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1948 1949 self.strdispatchers['complete_command'] = sdisp
1949 1950 self.Completer.custom_completers = sdisp
1950 1951
1951 1952 self.set_hook('complete_command', module_completer, str_key = 'import')
1952 1953 self.set_hook('complete_command', module_completer, str_key = 'from')
1953 1954 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1954 1955 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1955 1956 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1956 1957
1957 1958 # Only configure readline if we truly are using readline. IPython can
1958 1959 # do tab-completion over the network, in GUIs, etc, where readline
1959 1960 # itself may be absent
1960 1961 if self.has_readline:
1961 1962 self.set_readline_completer()
1962 1963
1963 1964 def complete(self, text, line=None, cursor_pos=None):
1964 1965 """Return the completed text and a list of completions.
1965 1966
1966 1967 Parameters
1967 1968 ----------
1968 1969
1969 1970 text : string
1970 1971 A string of text to be completed on. It can be given as empty and
1971 1972 instead a line/position pair are given. In this case, the
1972 1973 completer itself will split the line like readline does.
1973 1974
1974 1975 line : string, optional
1975 1976 The complete line that text is part of.
1976 1977
1977 1978 cursor_pos : int, optional
1978 1979 The position of the cursor on the input line.
1979 1980
1980 1981 Returns
1981 1982 -------
1982 1983 text : string
1983 1984 The actual text that was completed.
1984 1985
1985 1986 matches : list
1986 1987 A sorted list with all possible completions.
1987 1988
1988 1989 The optional arguments allow the completion to take more context into
1989 1990 account, and are part of the low-level completion API.
1990 1991
1991 1992 This is a wrapper around the completion mechanism, similar to what
1992 1993 readline does at the command line when the TAB key is hit. By
1993 1994 exposing it as a method, it can be used by other non-readline
1994 1995 environments (such as GUIs) for text completion.
1995 1996
1996 1997 Simple usage example:
1997 1998
1998 1999 In [1]: x = 'hello'
1999 2000
2000 2001 In [2]: _ip.complete('x.l')
2001 2002 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2002 2003 """
2003 2004
2004 2005 # Inject names into __builtin__ so we can complete on the added names.
2005 2006 with self.builtin_trap:
2006 2007 return self.Completer.complete(text, line, cursor_pos)
2007 2008
2008 2009 def set_custom_completer(self, completer, pos=0):
2009 2010 """Adds a new custom completer function.
2010 2011
2011 2012 The position argument (defaults to 0) is the index in the completers
2012 2013 list where you want the completer to be inserted."""
2013 2014
2014 2015 newcomp = types.MethodType(completer,self.Completer)
2015 2016 self.Completer.matchers.insert(pos,newcomp)
2016 2017
2017 2018 def set_readline_completer(self):
2018 2019 """Reset readline's completer to be our own."""
2019 2020 self.readline.set_completer(self.Completer.rlcomplete)
2020 2021
2021 2022 def set_completer_frame(self, frame=None):
2022 2023 """Set the frame of the completer."""
2023 2024 if frame:
2024 2025 self.Completer.namespace = frame.f_locals
2025 2026 self.Completer.global_namespace = frame.f_globals
2026 2027 else:
2027 2028 self.Completer.namespace = self.user_ns
2028 2029 self.Completer.global_namespace = self.user_global_ns
2029 2030
2030 2031 #-------------------------------------------------------------------------
2031 2032 # Things related to magics
2032 2033 #-------------------------------------------------------------------------
2033 2034
2034 2035 def init_magics(self):
2035 2036 from IPython.core import magics as m
2036 2037 self.magics_manager = magic.MagicsManager(shell=self,
2037 2038 parent=self,
2038 2039 user_magics=m.UserMagics(self))
2039 2040 self.configurables.append(self.magics_manager)
2040 2041
2041 2042 # Expose as public API from the magics manager
2042 2043 self.register_magics = self.magics_manager.register
2043 2044 self.define_magic = self.magics_manager.define_magic
2044 2045
2045 2046 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2046 2047 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2047 2048 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2048 2049 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2049 2050 )
2050 2051
2051 2052 # Register Magic Aliases
2052 2053 mman = self.magics_manager
2053 2054 # FIXME: magic aliases should be defined by the Magics classes
2054 2055 # or in MagicsManager, not here
2055 2056 mman.register_alias('ed', 'edit')
2056 2057 mman.register_alias('hist', 'history')
2057 2058 mman.register_alias('rep', 'recall')
2058 2059 mman.register_alias('SVG', 'svg', 'cell')
2059 2060 mman.register_alias('HTML', 'html', 'cell')
2060 2061 mman.register_alias('file', 'writefile', 'cell')
2061 2062
2062 2063 # FIXME: Move the color initialization to the DisplayHook, which
2063 2064 # should be split into a prompt manager and displayhook. We probably
2064 2065 # even need a centralize colors management object.
2065 2066 self.magic('colors %s' % self.colors)
2066 2067
2067 2068 # Defined here so that it's included in the documentation
2068 2069 @functools.wraps(magic.MagicsManager.register_function)
2069 2070 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2070 2071 self.magics_manager.register_function(func,
2071 2072 magic_kind=magic_kind, magic_name=magic_name)
2072 2073
2073 2074 def run_line_magic(self, magic_name, line):
2074 2075 """Execute the given line magic.
2075 2076
2076 2077 Parameters
2077 2078 ----------
2078 2079 magic_name : str
2079 2080 Name of the desired magic function, without '%' prefix.
2080 2081
2081 2082 line : str
2082 2083 The rest of the input line as a single string.
2083 2084 """
2084 2085 fn = self.find_line_magic(magic_name)
2085 2086 if fn is None:
2086 2087 cm = self.find_cell_magic(magic_name)
2087 2088 etpl = "Line magic function `%%%s` not found%s."
2088 2089 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2089 2090 'did you mean that instead?)' % magic_name )
2090 2091 error(etpl % (magic_name, extra))
2091 2092 else:
2092 2093 # Note: this is the distance in the stack to the user's frame.
2093 2094 # This will need to be updated if the internal calling logic gets
2094 2095 # refactored, or else we'll be expanding the wrong variables.
2095 2096 stack_depth = 2
2096 2097 magic_arg_s = self.var_expand(line, stack_depth)
2097 2098 # Put magic args in a list so we can call with f(*a) syntax
2098 2099 args = [magic_arg_s]
2099 2100 kwargs = {}
2100 2101 # Grab local namespace if we need it:
2101 2102 if getattr(fn, "needs_local_scope", False):
2102 2103 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2103 2104 with self.builtin_trap:
2104 2105 result = fn(*args,**kwargs)
2105 2106 return result
2106 2107
2107 2108 def run_cell_magic(self, magic_name, line, cell):
2108 2109 """Execute the given cell magic.
2109 2110
2110 2111 Parameters
2111 2112 ----------
2112 2113 magic_name : str
2113 2114 Name of the desired magic function, without '%' prefix.
2114 2115
2115 2116 line : str
2116 2117 The rest of the first input line as a single string.
2117 2118
2118 2119 cell : str
2119 2120 The body of the cell as a (possibly multiline) string.
2120 2121 """
2121 2122 fn = self.find_cell_magic(magic_name)
2122 2123 if fn is None:
2123 2124 lm = self.find_line_magic(magic_name)
2124 2125 etpl = "Cell magic `%%{0}` not found{1}."
2125 2126 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2126 2127 'did you mean that instead?)'.format(magic_name))
2127 2128 error(etpl.format(magic_name, extra))
2128 2129 elif cell == '':
2129 2130 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2130 2131 if self.find_line_magic(magic_name) is not None:
2131 2132 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2132 2133 raise UsageError(message)
2133 2134 else:
2134 2135 # Note: this is the distance in the stack to the user's frame.
2135 2136 # This will need to be updated if the internal calling logic gets
2136 2137 # refactored, or else we'll be expanding the wrong variables.
2137 2138 stack_depth = 2
2138 2139 magic_arg_s = self.var_expand(line, stack_depth)
2139 2140 with self.builtin_trap:
2140 2141 result = fn(magic_arg_s, cell)
2141 2142 return result
2142 2143
2143 2144 def find_line_magic(self, magic_name):
2144 2145 """Find and return a line magic by name.
2145 2146
2146 2147 Returns None if the magic isn't found."""
2147 2148 return self.magics_manager.magics['line'].get(magic_name)
2148 2149
2149 2150 def find_cell_magic(self, magic_name):
2150 2151 """Find and return a cell magic by name.
2151 2152
2152 2153 Returns None if the magic isn't found."""
2153 2154 return self.magics_manager.magics['cell'].get(magic_name)
2154 2155
2155 2156 def find_magic(self, magic_name, magic_kind='line'):
2156 2157 """Find and return a magic of the given type by name.
2157 2158
2158 2159 Returns None if the magic isn't found."""
2159 2160 return self.magics_manager.magics[magic_kind].get(magic_name)
2160 2161
2161 2162 def magic(self, arg_s):
2162 2163 """DEPRECATED. Use run_line_magic() instead.
2163 2164
2164 2165 Call a magic function by name.
2165 2166
2166 2167 Input: a string containing the name of the magic function to call and
2167 2168 any additional arguments to be passed to the magic.
2168 2169
2169 2170 magic('name -opt foo bar') is equivalent to typing at the ipython
2170 2171 prompt:
2171 2172
2172 2173 In[1]: %name -opt foo bar
2173 2174
2174 2175 To call a magic without arguments, simply use magic('name').
2175 2176
2176 2177 This provides a proper Python function to call IPython's magics in any
2177 2178 valid Python code you can type at the interpreter, including loops and
2178 2179 compound statements.
2179 2180 """
2180 2181 # TODO: should we issue a loud deprecation warning here?
2181 2182 magic_name, _, magic_arg_s = arg_s.partition(' ')
2182 2183 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2183 2184 return self.run_line_magic(magic_name, magic_arg_s)
2184 2185
2185 2186 #-------------------------------------------------------------------------
2186 2187 # Things related to macros
2187 2188 #-------------------------------------------------------------------------
2188 2189
2189 2190 def define_macro(self, name, themacro):
2190 2191 """Define a new macro
2191 2192
2192 2193 Parameters
2193 2194 ----------
2194 2195 name : str
2195 2196 The name of the macro.
2196 2197 themacro : str or Macro
2197 2198 The action to do upon invoking the macro. If a string, a new
2198 2199 Macro object is created by passing the string to it.
2199 2200 """
2200 2201
2201 2202 from IPython.core import macro
2202 2203
2203 2204 if isinstance(themacro, string_types):
2204 2205 themacro = macro.Macro(themacro)
2205 2206 if not isinstance(themacro, macro.Macro):
2206 2207 raise ValueError('A macro must be a string or a Macro instance.')
2207 2208 self.user_ns[name] = themacro
2208 2209
2209 2210 #-------------------------------------------------------------------------
2210 2211 # Things related to the running of system commands
2211 2212 #-------------------------------------------------------------------------
2212 2213
2213 2214 def system_piped(self, cmd):
2214 2215 """Call the given cmd in a subprocess, piping stdout/err
2215 2216
2216 2217 Parameters
2217 2218 ----------
2218 2219 cmd : str
2219 2220 Command to execute (can not end in '&', as background processes are
2220 2221 not supported. Should not be a command that expects input
2221 2222 other than simple text.
2222 2223 """
2223 2224 if cmd.rstrip().endswith('&'):
2224 2225 # this is *far* from a rigorous test
2225 2226 # We do not support backgrounding processes because we either use
2226 2227 # pexpect or pipes to read from. Users can always just call
2227 2228 # os.system() or use ip.system=ip.system_raw
2228 2229 # if they really want a background process.
2229 2230 raise OSError("Background processes not supported.")
2230 2231
2231 2232 # we explicitly do NOT return the subprocess status code, because
2232 2233 # a non-None value would trigger :func:`sys.displayhook` calls.
2233 2234 # Instead, we store the exit_code in user_ns.
2234 2235 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2235 2236
2236 2237 def system_raw(self, cmd):
2237 2238 """Call the given cmd in a subprocess using os.system on Windows or
2238 2239 subprocess.call using the system shell on other platforms.
2239 2240
2240 2241 Parameters
2241 2242 ----------
2242 2243 cmd : str
2243 2244 Command to execute.
2244 2245 """
2245 2246 cmd = self.var_expand(cmd, depth=1)
2246 2247 # protect os.system from UNC paths on Windows, which it can't handle:
2247 2248 if sys.platform == 'win32':
2248 2249 from IPython.utils._process_win32 import AvoidUNCPath
2249 2250 with AvoidUNCPath() as path:
2250 2251 if path is not None:
2251 2252 cmd = '"pushd %s &&"%s' % (path, cmd)
2252 2253 cmd = py3compat.unicode_to_str(cmd)
2253 2254 ec = os.system(cmd)
2254 2255 else:
2255 2256 cmd = py3compat.unicode_to_str(cmd)
2256 2257 # Call the cmd using the OS shell, instead of the default /bin/sh, if set.
2257 2258 ec = subprocess.call(cmd, shell=True, executable=os.environ.get('SHELL', None))
2258 2259 # exit code is positive for program failure, or negative for
2259 2260 # terminating signal number.
2260 2261
2261 2262 # We explicitly do NOT return the subprocess status code, because
2262 2263 # a non-None value would trigger :func:`sys.displayhook` calls.
2263 2264 # Instead, we store the exit_code in user_ns.
2264 2265 self.user_ns['_exit_code'] = ec
2265 2266
2266 2267 # use piped system by default, because it is better behaved
2267 2268 system = system_piped
2268 2269
2269 2270 def getoutput(self, cmd, split=True, depth=0):
2270 2271 """Get output (possibly including stderr) from a subprocess.
2271 2272
2272 2273 Parameters
2273 2274 ----------
2274 2275 cmd : str
2275 2276 Command to execute (can not end in '&', as background processes are
2276 2277 not supported.
2277 2278 split : bool, optional
2278 2279 If True, split the output into an IPython SList. Otherwise, an
2279 2280 IPython LSString is returned. These are objects similar to normal
2280 2281 lists and strings, with a few convenience attributes for easier
2281 2282 manipulation of line-based output. You can use '?' on them for
2282 2283 details.
2283 2284 depth : int, optional
2284 2285 How many frames above the caller are the local variables which should
2285 2286 be expanded in the command string? The default (0) assumes that the
2286 2287 expansion variables are in the stack frame calling this function.
2287 2288 """
2288 2289 if cmd.rstrip().endswith('&'):
2289 2290 # this is *far* from a rigorous test
2290 2291 raise OSError("Background processes not supported.")
2291 2292 out = getoutput(self.var_expand(cmd, depth=depth+1))
2292 2293 if split:
2293 2294 out = SList(out.splitlines())
2294 2295 else:
2295 2296 out = LSString(out)
2296 2297 return out
2297 2298
2298 2299 #-------------------------------------------------------------------------
2299 2300 # Things related to aliases
2300 2301 #-------------------------------------------------------------------------
2301 2302
2302 2303 def init_alias(self):
2303 2304 self.alias_manager = AliasManager(shell=self, parent=self)
2304 2305 self.configurables.append(self.alias_manager)
2305 2306
2306 2307 #-------------------------------------------------------------------------
2307 2308 # Things related to extensions
2308 2309 #-------------------------------------------------------------------------
2309 2310
2310 2311 def init_extension_manager(self):
2311 2312 self.extension_manager = ExtensionManager(shell=self, parent=self)
2312 2313 self.configurables.append(self.extension_manager)
2313 2314
2314 2315 #-------------------------------------------------------------------------
2315 2316 # Things related to payloads
2316 2317 #-------------------------------------------------------------------------
2317 2318
2318 2319 def init_payload(self):
2319 2320 self.payload_manager = PayloadManager(parent=self)
2320 2321 self.configurables.append(self.payload_manager)
2321 2322
2322 2323 #-------------------------------------------------------------------------
2323 2324 # Things related to widgets
2324 2325 #-------------------------------------------------------------------------
2325 2326
2326 2327 def init_comms(self):
2327 2328 # not implemented in the base class
2328 2329 pass
2329 2330
2330 2331 #-------------------------------------------------------------------------
2331 2332 # Things related to the prefilter
2332 2333 #-------------------------------------------------------------------------
2333 2334
2334 2335 def init_prefilter(self):
2335 2336 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2336 2337 self.configurables.append(self.prefilter_manager)
2337 2338 # Ultimately this will be refactored in the new interpreter code, but
2338 2339 # for now, we should expose the main prefilter method (there's legacy
2339 2340 # code out there that may rely on this).
2340 2341 self.prefilter = self.prefilter_manager.prefilter_lines
2341 2342
2342 2343 def auto_rewrite_input(self, cmd):
2343 2344 """Print to the screen the rewritten form of the user's command.
2344 2345
2345 2346 This shows visual feedback by rewriting input lines that cause
2346 2347 automatic calling to kick in, like::
2347 2348
2348 2349 /f x
2349 2350
2350 2351 into::
2351 2352
2352 2353 ------> f(x)
2353 2354
2354 2355 after the user's input prompt. This helps the user understand that the
2355 2356 input line was transformed automatically by IPython.
2356 2357 """
2357 2358 if not self.show_rewritten_input:
2358 2359 return
2359 2360
2360 2361 rw = self.prompt_manager.render('rewrite') + cmd
2361 2362
2362 2363 try:
2363 2364 # plain ascii works better w/ pyreadline, on some machines, so
2364 2365 # we use it and only print uncolored rewrite if we have unicode
2365 2366 rw = str(rw)
2366 2367 print(rw, file=io.stdout)
2367 2368 except UnicodeEncodeError:
2368 2369 print("------> " + cmd)
2369 2370
2370 2371 #-------------------------------------------------------------------------
2371 2372 # Things related to extracting values/expressions from kernel and user_ns
2372 2373 #-------------------------------------------------------------------------
2373 2374
2374 2375 def _user_obj_error(self):
2375 2376 """return simple exception dict
2376 2377
2377 2378 for use in user_variables / expressions
2378 2379 """
2379 2380
2380 2381 etype, evalue, tb = self._get_exc_info()
2381 2382 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2382 2383
2383 2384 exc_info = {
2384 2385 u'status' : 'error',
2385 2386 u'traceback' : stb,
2386 2387 u'ename' : unicode_type(etype.__name__),
2387 2388 u'evalue' : py3compat.safe_unicode(evalue),
2388 2389 }
2389 2390
2390 2391 return exc_info
2391 2392
2392 2393 def _format_user_obj(self, obj):
2393 2394 """format a user object to display dict
2394 2395
2395 2396 for use in user_expressions / variables
2396 2397 """
2397 2398
2398 2399 data, md = self.display_formatter.format(obj)
2399 2400 value = {
2400 2401 'status' : 'ok',
2401 2402 'data' : data,
2402 2403 'metadata' : md,
2403 2404 }
2404 2405 return value
2405 2406
2406 2407 def user_variables(self, names):
2407 2408 """Get a list of variable names from the user's namespace.
2408 2409
2409 2410 Parameters
2410 2411 ----------
2411 2412 names : list of strings
2412 2413 A list of names of variables to be read from the user namespace.
2413 2414
2414 2415 Returns
2415 2416 -------
2416 2417 A dict, keyed by the input names and with the rich mime-type repr(s) of each value.
2417 2418 Each element will be a sub-dict of the same form as a display_data message.
2418 2419 """
2419 2420 out = {}
2420 2421 user_ns = self.user_ns
2421 2422
2422 2423 for varname in names:
2423 2424 try:
2424 2425 value = self._format_user_obj(user_ns[varname])
2425 2426 except:
2426 2427 value = self._user_obj_error()
2427 2428 out[varname] = value
2428 2429 return out
2429 2430
2430 2431 def user_expressions(self, expressions):
2431 2432 """Evaluate a dict of expressions in the user's namespace.
2432 2433
2433 2434 Parameters
2434 2435 ----------
2435 2436 expressions : dict
2436 2437 A dict with string keys and string values. The expression values
2437 2438 should be valid Python expressions, each of which will be evaluated
2438 2439 in the user namespace.
2439 2440
2440 2441 Returns
2441 2442 -------
2442 2443 A dict, keyed like the input expressions dict, with the rich mime-typed
2443 2444 display_data of each value.
2444 2445 """
2445 2446 out = {}
2446 2447 user_ns = self.user_ns
2447 2448 global_ns = self.user_global_ns
2448 2449
2449 2450 for key, expr in expressions.iteritems():
2450 2451 try:
2451 2452 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2452 2453 except:
2453 2454 value = self._user_obj_error()
2454 2455 out[key] = value
2455 2456 return out
2456 2457
2457 2458 #-------------------------------------------------------------------------
2458 2459 # Things related to the running of code
2459 2460 #-------------------------------------------------------------------------
2460 2461
2461 2462 def ex(self, cmd):
2462 2463 """Execute a normal python statement in user namespace."""
2463 2464 with self.builtin_trap:
2464 2465 exec(cmd, self.user_global_ns, self.user_ns)
2465 2466
2466 2467 def ev(self, expr):
2467 2468 """Evaluate python expression expr in user namespace.
2468 2469
2469 2470 Returns the result of evaluation
2470 2471 """
2471 2472 with self.builtin_trap:
2472 2473 return eval(expr, self.user_global_ns, self.user_ns)
2473 2474
2474 2475 def safe_execfile(self, fname, *where, **kw):
2475 2476 """A safe version of the builtin execfile().
2476 2477
2477 2478 This version will never throw an exception, but instead print
2478 2479 helpful error messages to the screen. This only works on pure
2479 2480 Python files with the .py extension.
2480 2481
2481 2482 Parameters
2482 2483 ----------
2483 2484 fname : string
2484 2485 The name of the file to be executed.
2485 2486 where : tuple
2486 2487 One or two namespaces, passed to execfile() as (globals,locals).
2487 2488 If only one is given, it is passed as both.
2488 2489 exit_ignore : bool (False)
2489 2490 If True, then silence SystemExit for non-zero status (it is always
2490 2491 silenced for zero status, as it is so common).
2491 2492 raise_exceptions : bool (False)
2492 2493 If True raise exceptions everywhere. Meant for testing.
2493 2494
2494 2495 """
2495 2496 kw.setdefault('exit_ignore', False)
2496 2497 kw.setdefault('raise_exceptions', False)
2497 2498
2498 2499 fname = os.path.abspath(os.path.expanduser(fname))
2499 2500
2500 2501 # Make sure we can open the file
2501 2502 try:
2502 2503 with open(fname) as thefile:
2503 2504 pass
2504 2505 except:
2505 2506 warn('Could not open file <%s> for safe execution.' % fname)
2506 2507 return
2507 2508
2508 2509 # Find things also in current directory. This is needed to mimic the
2509 2510 # behavior of running a script from the system command line, where
2510 2511 # Python inserts the script's directory into sys.path
2511 2512 dname = os.path.dirname(fname)
2512 2513
2513 2514 with prepended_to_syspath(dname):
2514 2515 try:
2515 2516 py3compat.execfile(fname,*where)
2516 2517 except SystemExit as status:
2517 2518 # If the call was made with 0 or None exit status (sys.exit(0)
2518 2519 # or sys.exit() ), don't bother showing a traceback, as both of
2519 2520 # these are considered normal by the OS:
2520 2521 # > python -c'import sys;sys.exit(0)'; echo $?
2521 2522 # 0
2522 2523 # > python -c'import sys;sys.exit()'; echo $?
2523 2524 # 0
2524 2525 # For other exit status, we show the exception unless
2525 2526 # explicitly silenced, but only in short form.
2526 2527 if kw['raise_exceptions']:
2527 2528 raise
2528 2529 if status.code and not kw['exit_ignore']:
2529 2530 self.showtraceback(exception_only=True)
2530 2531 except:
2531 2532 if kw['raise_exceptions']:
2532 2533 raise
2533 2534 self.showtraceback()
2534 2535
2535 2536 def safe_execfile_ipy(self, fname):
2536 2537 """Like safe_execfile, but for .ipy files with IPython syntax.
2537 2538
2538 2539 Parameters
2539 2540 ----------
2540 2541 fname : str
2541 2542 The name of the file to execute. The filename must have a
2542 2543 .ipy extension.
2543 2544 """
2544 2545 fname = os.path.abspath(os.path.expanduser(fname))
2545 2546
2546 2547 # Make sure we can open the file
2547 2548 try:
2548 2549 with open(fname) as thefile:
2549 2550 pass
2550 2551 except:
2551 2552 warn('Could not open file <%s> for safe execution.' % fname)
2552 2553 return
2553 2554
2554 2555 # Find things also in current directory. This is needed to mimic the
2555 2556 # behavior of running a script from the system command line, where
2556 2557 # Python inserts the script's directory into sys.path
2557 2558 dname = os.path.dirname(fname)
2558 2559
2559 2560 with prepended_to_syspath(dname):
2560 2561 try:
2561 2562 with open(fname) as thefile:
2562 2563 # self.run_cell currently captures all exceptions
2563 2564 # raised in user code. It would be nice if there were
2564 2565 # versions of runlines, execfile that did raise, so
2565 2566 # we could catch the errors.
2566 2567 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2567 2568 except:
2568 2569 self.showtraceback()
2569 2570 warn('Unknown failure executing file: <%s>' % fname)
2570 2571
2571 2572 def safe_run_module(self, mod_name, where):
2572 2573 """A safe version of runpy.run_module().
2573 2574
2574 2575 This version will never throw an exception, but instead print
2575 2576 helpful error messages to the screen.
2576 2577
2577 2578 `SystemExit` exceptions with status code 0 or None are ignored.
2578 2579
2579 2580 Parameters
2580 2581 ----------
2581 2582 mod_name : string
2582 2583 The name of the module to be executed.
2583 2584 where : dict
2584 2585 The globals namespace.
2585 2586 """
2586 2587 try:
2587 2588 try:
2588 2589 where.update(
2589 2590 runpy.run_module(str(mod_name), run_name="__main__",
2590 2591 alter_sys=True)
2591 2592 )
2592 2593 except SystemExit as status:
2593 2594 if status.code:
2594 2595 raise
2595 2596 except:
2596 2597 self.showtraceback()
2597 2598 warn('Unknown failure executing module: <%s>' % mod_name)
2598 2599
2599 2600 def _run_cached_cell_magic(self, magic_name, line):
2600 2601 """Special method to call a cell magic with the data stored in self.
2601 2602 """
2602 2603 cell = self._current_cell_magic_body
2603 2604 self._current_cell_magic_body = None
2604 2605 return self.run_cell_magic(magic_name, line, cell)
2605 2606
2606 2607 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2607 2608 """Run a complete IPython cell.
2608 2609
2609 2610 Parameters
2610 2611 ----------
2611 2612 raw_cell : str
2612 2613 The code (including IPython code such as %magic functions) to run.
2613 2614 store_history : bool
2614 2615 If True, the raw and translated cell will be stored in IPython's
2615 2616 history. For user code calling back into IPython's machinery, this
2616 2617 should be set to False.
2617 2618 silent : bool
2618 2619 If True, avoid side-effects, such as implicit displayhooks and
2619 2620 and logging. silent=True forces store_history=False.
2620 2621 shell_futures : bool
2621 2622 If True, the code will share future statements with the interactive
2622 2623 shell. It will both be affected by previous __future__ imports, and
2623 2624 any __future__ imports in the code will affect the shell. If False,
2624 2625 __future__ imports are not shared in either direction.
2625 2626 """
2626 2627 if (not raw_cell) or raw_cell.isspace():
2627 2628 return
2628 2629
2629 2630 if silent:
2630 2631 store_history = False
2631 2632
2632 2633 self.input_transformer_manager.push(raw_cell)
2633 2634 cell = self.input_transformer_manager.source_reset()
2634 2635
2635 2636 # Our own compiler remembers the __future__ environment. If we want to
2636 2637 # run code with a separate __future__ environment, use the default
2637 2638 # compiler
2638 2639 compiler = self.compile if shell_futures else CachingCompiler()
2639 2640
2640 2641 with self.builtin_trap:
2641 2642 prefilter_failed = False
2642 2643 if len(cell.splitlines()) == 1:
2643 2644 try:
2644 2645 # use prefilter_lines to handle trailing newlines
2645 2646 # restore trailing newline for ast.parse
2646 2647 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2647 2648 except AliasError as e:
2648 2649 error(e)
2649 2650 prefilter_failed = True
2650 2651 except Exception:
2651 2652 # don't allow prefilter errors to crash IPython
2652 2653 self.showtraceback()
2653 2654 prefilter_failed = True
2654 2655
2655 2656 # Store raw and processed history
2656 2657 if store_history:
2657 2658 self.history_manager.store_inputs(self.execution_count,
2658 2659 cell, raw_cell)
2659 2660 if not silent:
2660 2661 self.logger.log(cell, raw_cell)
2661 2662
2662 2663 if not prefilter_failed:
2663 2664 # don't run if prefilter failed
2664 2665 cell_name = self.compile.cache(cell, self.execution_count)
2665 2666
2666 2667 with self.display_trap:
2667 2668 try:
2668 2669 code_ast = compiler.ast_parse(cell, filename=cell_name)
2669 2670 except IndentationError:
2670 2671 self.showindentationerror()
2671 2672 if store_history:
2672 2673 self.execution_count += 1
2673 2674 return None
2674 2675 except (OverflowError, SyntaxError, ValueError, TypeError,
2675 2676 MemoryError):
2676 2677 self.showsyntaxerror()
2677 2678 if store_history:
2678 2679 self.execution_count += 1
2679 2680 return None
2680 2681
2681 2682 code_ast = self.transform_ast(code_ast)
2682 2683
2683 2684 interactivity = "none" if silent else self.ast_node_interactivity
2684 2685 self.run_ast_nodes(code_ast.body, cell_name,
2685 2686 interactivity=interactivity, compiler=compiler)
2686 2687
2687 2688 # Execute any registered post-execution functions.
2688 2689 # unless we are silent
2689 2690 post_exec = [] if silent else self._post_execute.iteritems()
2690 2691
2691 2692 for func, status in post_exec:
2692 2693 if self.disable_failing_post_execute and not status:
2693 2694 continue
2694 2695 try:
2695 2696 func()
2696 2697 except KeyboardInterrupt:
2697 2698 print("\nKeyboardInterrupt", file=io.stderr)
2698 2699 except Exception:
2699 2700 # register as failing:
2700 2701 self._post_execute[func] = False
2701 2702 self.showtraceback()
2702 2703 print('\n'.join([
2703 2704 "post-execution function %r produced an error." % func,
2704 2705 "If this problem persists, you can disable failing post-exec functions with:",
2705 2706 "",
2706 2707 " get_ipython().disable_failing_post_execute = True"
2707 2708 ]), file=io.stderr)
2708 2709
2709 2710 if store_history:
2710 2711 # Write output to the database. Does nothing unless
2711 2712 # history output logging is enabled.
2712 2713 self.history_manager.store_output(self.execution_count)
2713 2714 # Each cell is a *single* input, regardless of how many lines it has
2714 2715 self.execution_count += 1
2715 2716
2716 2717 def transform_ast(self, node):
2717 2718 """Apply the AST transformations from self.ast_transformers
2718 2719
2719 2720 Parameters
2720 2721 ----------
2721 2722 node : ast.Node
2722 2723 The root node to be transformed. Typically called with the ast.Module
2723 2724 produced by parsing user input.
2724 2725
2725 2726 Returns
2726 2727 -------
2727 2728 An ast.Node corresponding to the node it was called with. Note that it
2728 2729 may also modify the passed object, so don't rely on references to the
2729 2730 original AST.
2730 2731 """
2731 2732 for transformer in self.ast_transformers:
2732 2733 try:
2733 2734 node = transformer.visit(node)
2734 2735 except Exception:
2735 2736 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2736 2737 self.ast_transformers.remove(transformer)
2737 2738
2738 2739 if self.ast_transformers:
2739 2740 ast.fix_missing_locations(node)
2740 2741 return node
2741 2742
2742 2743
2743 2744 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2744 2745 compiler=compile):
2745 2746 """Run a sequence of AST nodes. The execution mode depends on the
2746 2747 interactivity parameter.
2747 2748
2748 2749 Parameters
2749 2750 ----------
2750 2751 nodelist : list
2751 2752 A sequence of AST nodes to run.
2752 2753 cell_name : str
2753 2754 Will be passed to the compiler as the filename of the cell. Typically
2754 2755 the value returned by ip.compile.cache(cell).
2755 2756 interactivity : str
2756 2757 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2757 2758 run interactively (displaying output from expressions). 'last_expr'
2758 2759 will run the last node interactively only if it is an expression (i.e.
2759 2760 expressions in loops or other blocks are not displayed. Other values
2760 2761 for this parameter will raise a ValueError.
2761 2762 compiler : callable
2762 2763 A function with the same interface as the built-in compile(), to turn
2763 2764 the AST nodes into code objects. Default is the built-in compile().
2764 2765 """
2765 2766 if not nodelist:
2766 2767 return
2767 2768
2768 2769 if interactivity == 'last_expr':
2769 2770 if isinstance(nodelist[-1], ast.Expr):
2770 2771 interactivity = "last"
2771 2772 else:
2772 2773 interactivity = "none"
2773 2774
2774 2775 if interactivity == 'none':
2775 2776 to_run_exec, to_run_interactive = nodelist, []
2776 2777 elif interactivity == 'last':
2777 2778 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2778 2779 elif interactivity == 'all':
2779 2780 to_run_exec, to_run_interactive = [], nodelist
2780 2781 else:
2781 2782 raise ValueError("Interactivity was %r" % interactivity)
2782 2783
2783 2784 exec_count = self.execution_count
2784 2785
2785 2786 try:
2786 2787 for i, node in enumerate(to_run_exec):
2787 2788 mod = ast.Module([node])
2788 2789 code = compiler(mod, cell_name, "exec")
2789 2790 if self.run_code(code):
2790 2791 return True
2791 2792
2792 2793 for i, node in enumerate(to_run_interactive):
2793 2794 mod = ast.Interactive([node])
2794 2795 code = compiler(mod, cell_name, "single")
2795 2796 if self.run_code(code):
2796 2797 return True
2797 2798
2798 2799 # Flush softspace
2799 2800 if softspace(sys.stdout, 0):
2800 2801 print()
2801 2802
2802 2803 except:
2803 2804 # It's possible to have exceptions raised here, typically by
2804 2805 # compilation of odd code (such as a naked 'return' outside a
2805 2806 # function) that did parse but isn't valid. Typically the exception
2806 2807 # is a SyntaxError, but it's safest just to catch anything and show
2807 2808 # the user a traceback.
2808 2809
2809 2810 # We do only one try/except outside the loop to minimize the impact
2810 2811 # on runtime, and also because if any node in the node list is
2811 2812 # broken, we should stop execution completely.
2812 2813 self.showtraceback()
2813 2814
2814 2815 return False
2815 2816
2816 2817 def run_code(self, code_obj):
2817 2818 """Execute a code object.
2818 2819
2819 2820 When an exception occurs, self.showtraceback() is called to display a
2820 2821 traceback.
2821 2822
2822 2823 Parameters
2823 2824 ----------
2824 2825 code_obj : code object
2825 2826 A compiled code object, to be executed
2826 2827
2827 2828 Returns
2828 2829 -------
2829 2830 False : successful execution.
2830 2831 True : an error occurred.
2831 2832 """
2832 2833
2833 2834 # Set our own excepthook in case the user code tries to call it
2834 2835 # directly, so that the IPython crash handler doesn't get triggered
2835 2836 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2836 2837
2837 2838 # we save the original sys.excepthook in the instance, in case config
2838 2839 # code (such as magics) needs access to it.
2839 2840 self.sys_excepthook = old_excepthook
2840 2841 outflag = 1 # happens in more places, so it's easier as default
2841 2842 try:
2842 2843 try:
2843 2844 self.hooks.pre_run_code_hook()
2844 2845 #rprint('Running code', repr(code_obj)) # dbg
2845 2846 exec(code_obj, self.user_global_ns, self.user_ns)
2846 2847 finally:
2847 2848 # Reset our crash handler in place
2848 2849 sys.excepthook = old_excepthook
2849 2850 except SystemExit:
2850 2851 self.showtraceback(exception_only=True)
2851 2852 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2852 2853 except self.custom_exceptions:
2853 2854 etype,value,tb = sys.exc_info()
2854 2855 self.CustomTB(etype,value,tb)
2855 2856 except:
2856 2857 self.showtraceback()
2857 2858 else:
2858 2859 outflag = 0
2859 2860 return outflag
2860 2861
2861 2862 # For backwards compatibility
2862 2863 runcode = run_code
2863 2864
2864 2865 #-------------------------------------------------------------------------
2865 2866 # Things related to GUI support and pylab
2866 2867 #-------------------------------------------------------------------------
2867 2868
2868 2869 def enable_gui(self, gui=None):
2869 2870 raise NotImplementedError('Implement enable_gui in a subclass')
2870 2871
2871 2872 def enable_matplotlib(self, gui=None):
2872 2873 """Enable interactive matplotlib and inline figure support.
2873 2874
2874 2875 This takes the following steps:
2875 2876
2876 2877 1. select the appropriate eventloop and matplotlib backend
2877 2878 2. set up matplotlib for interactive use with that backend
2878 2879 3. configure formatters for inline figure display
2879 2880 4. enable the selected gui eventloop
2880 2881
2881 2882 Parameters
2882 2883 ----------
2883 2884 gui : optional, string
2884 2885 If given, dictates the choice of matplotlib GUI backend to use
2885 2886 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2886 2887 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2887 2888 matplotlib (as dictated by the matplotlib build-time options plus the
2888 2889 user's matplotlibrc configuration file). Note that not all backends
2889 2890 make sense in all contexts, for example a terminal ipython can't
2890 2891 display figures inline.
2891 2892 """
2892 2893 from IPython.core import pylabtools as pt
2893 2894 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2894 2895
2895 2896 if gui != 'inline':
2896 2897 # If we have our first gui selection, store it
2897 2898 if self.pylab_gui_select is None:
2898 2899 self.pylab_gui_select = gui
2899 2900 # Otherwise if they are different
2900 2901 elif gui != self.pylab_gui_select:
2901 2902 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2902 2903 ' Using %s instead.' % (gui, self.pylab_gui_select))
2903 2904 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2904 2905
2905 2906 pt.activate_matplotlib(backend)
2906 2907 pt.configure_inline_support(self, backend)
2907 2908
2908 2909 # Now we must activate the gui pylab wants to use, and fix %run to take
2909 2910 # plot updates into account
2910 2911 self.enable_gui(gui)
2911 2912 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2912 2913 pt.mpl_runner(self.safe_execfile)
2913 2914
2914 2915 return gui, backend
2915 2916
2916 2917 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2917 2918 """Activate pylab support at runtime.
2918 2919
2919 2920 This turns on support for matplotlib, preloads into the interactive
2920 2921 namespace all of numpy and pylab, and configures IPython to correctly
2921 2922 interact with the GUI event loop. The GUI backend to be used can be
2922 2923 optionally selected with the optional ``gui`` argument.
2923 2924
2924 2925 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2925 2926
2926 2927 Parameters
2927 2928 ----------
2928 2929 gui : optional, string
2929 2930 If given, dictates the choice of matplotlib GUI backend to use
2930 2931 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2931 2932 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2932 2933 matplotlib (as dictated by the matplotlib build-time options plus the
2933 2934 user's matplotlibrc configuration file). Note that not all backends
2934 2935 make sense in all contexts, for example a terminal ipython can't
2935 2936 display figures inline.
2936 2937 import_all : optional, bool, default: True
2937 2938 Whether to do `from numpy import *` and `from pylab import *`
2938 2939 in addition to module imports.
2939 2940 welcome_message : deprecated
2940 2941 This argument is ignored, no welcome message will be displayed.
2941 2942 """
2942 2943 from IPython.core.pylabtools import import_pylab
2943 2944
2944 2945 gui, backend = self.enable_matplotlib(gui)
2945 2946
2946 2947 # We want to prevent the loading of pylab to pollute the user's
2947 2948 # namespace as shown by the %who* magics, so we execute the activation
2948 2949 # code in an empty namespace, and we update *both* user_ns and
2949 2950 # user_ns_hidden with this information.
2950 2951 ns = {}
2951 2952 import_pylab(ns, import_all)
2952 2953 # warn about clobbered names
2953 2954 ignored = set(["__builtins__"])
2954 2955 both = set(ns).intersection(self.user_ns).difference(ignored)
2955 2956 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2956 2957 self.user_ns.update(ns)
2957 2958 self.user_ns_hidden.update(ns)
2958 2959 return gui, backend, clobbered
2959 2960
2960 2961 #-------------------------------------------------------------------------
2961 2962 # Utilities
2962 2963 #-------------------------------------------------------------------------
2963 2964
2964 2965 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2965 2966 """Expand python variables in a string.
2966 2967
2967 2968 The depth argument indicates how many frames above the caller should
2968 2969 be walked to look for the local namespace where to expand variables.
2969 2970
2970 2971 The global namespace for expansion is always the user's interactive
2971 2972 namespace.
2972 2973 """
2973 2974 ns = self.user_ns.copy()
2974 2975 ns.update(sys._getframe(depth+1).f_locals)
2975 2976 try:
2976 2977 # We have to use .vformat() here, because 'self' is a valid and common
2977 2978 # name, and expanding **ns for .format() would make it collide with
2978 2979 # the 'self' argument of the method.
2979 2980 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2980 2981 except Exception:
2981 2982 # if formatter couldn't format, just let it go untransformed
2982 2983 pass
2983 2984 return cmd
2984 2985
2985 2986 def mktempfile(self, data=None, prefix='ipython_edit_'):
2986 2987 """Make a new tempfile and return its filename.
2987 2988
2988 2989 This makes a call to tempfile.mktemp, but it registers the created
2989 2990 filename internally so ipython cleans it up at exit time.
2990 2991
2991 2992 Optional inputs:
2992 2993
2993 2994 - data(None): if data is given, it gets written out to the temp file
2994 2995 immediately, and the file is closed again."""
2995 2996
2996 2997 filename = tempfile.mktemp('.py', prefix)
2997 2998 self.tempfiles.append(filename)
2998 2999
2999 3000 if data:
3000 3001 tmp_file = open(filename,'w')
3001 3002 tmp_file.write(data)
3002 3003 tmp_file.close()
3003 3004 return filename
3004 3005
3005 3006 # TODO: This should be removed when Term is refactored.
3006 3007 def write(self,data):
3007 3008 """Write a string to the default output"""
3008 3009 io.stdout.write(data)
3009 3010
3010 3011 # TODO: This should be removed when Term is refactored.
3011 3012 def write_err(self,data):
3012 3013 """Write a string to the default error output"""
3013 3014 io.stderr.write(data)
3014 3015
3015 3016 def ask_yes_no(self, prompt, default=None):
3016 3017 if self.quiet:
3017 3018 return True
3018 3019 return ask_yes_no(prompt,default)
3019 3020
3020 3021 def show_usage(self):
3021 3022 """Show a usage message"""
3022 3023 page.page(IPython.core.usage.interactive_usage)
3023 3024
3024 3025 def extract_input_lines(self, range_str, raw=False):
3025 3026 """Return as a string a set of input history slices.
3026 3027
3027 3028 Parameters
3028 3029 ----------
3029 3030 range_str : string
3030 3031 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3031 3032 since this function is for use by magic functions which get their
3032 3033 arguments as strings. The number before the / is the session
3033 3034 number: ~n goes n back from the current session.
3034 3035
3035 3036 Optional Parameters:
3036 3037 - raw(False): by default, the processed input is used. If this is
3037 3038 true, the raw input history is used instead.
3038 3039
3039 3040 Note that slices can be called with two notations:
3040 3041
3041 3042 N:M -> standard python form, means including items N...(M-1).
3042 3043
3043 3044 N-M -> include items N..M (closed endpoint).
3044 3045 """
3045 3046 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3046 3047 return "\n".join(x for _, _, x in lines)
3047 3048
3048 3049 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
3049 3050 """Get a code string from history, file, url, or a string or macro.
3050 3051
3051 3052 This is mainly used by magic functions.
3052 3053
3053 3054 Parameters
3054 3055 ----------
3055 3056
3056 3057 target : str
3057 3058
3058 3059 A string specifying code to retrieve. This will be tried respectively
3059 3060 as: ranges of input history (see %history for syntax), url,
3060 3061 correspnding .py file, filename, or an expression evaluating to a
3061 3062 string or Macro in the user namespace.
3062 3063
3063 3064 raw : bool
3064 3065 If true (default), retrieve raw history. Has no effect on the other
3065 3066 retrieval mechanisms.
3066 3067
3067 3068 py_only : bool (default False)
3068 3069 Only try to fetch python code, do not try alternative methods to decode file
3069 3070 if unicode fails.
3070 3071
3071 3072 Returns
3072 3073 -------
3073 3074 A string of code.
3074 3075
3075 3076 ValueError is raised if nothing is found, and TypeError if it evaluates
3076 3077 to an object of another type. In each case, .args[0] is a printable
3077 3078 message.
3078 3079 """
3079 3080 code = self.extract_input_lines(target, raw=raw) # Grab history
3080 3081 if code:
3081 3082 return code
3082 3083 utarget = unquote_filename(target)
3083 3084 try:
3084 3085 if utarget.startswith(('http://', 'https://')):
3085 3086 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3086 3087 except UnicodeDecodeError:
3087 3088 if not py_only :
3088 3089 from urllib import urlopen # Deferred import
3089 3090 response = urlopen(target)
3090 3091 return response.read().decode('latin1')
3091 3092 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3092 3093
3093 3094 potential_target = [target]
3094 3095 try :
3095 3096 potential_target.insert(0,get_py_filename(target))
3096 3097 except IOError:
3097 3098 pass
3098 3099
3099 3100 for tgt in potential_target :
3100 3101 if os.path.isfile(tgt): # Read file
3101 3102 try :
3102 3103 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3103 3104 except UnicodeDecodeError :
3104 3105 if not py_only :
3105 3106 with io_open(tgt,'r', encoding='latin1') as f :
3106 3107 return f.read()
3107 3108 raise ValueError(("'%s' seem to be unreadable.") % target)
3108 3109 elif os.path.isdir(os.path.expanduser(tgt)):
3109 3110 raise ValueError("'%s' is a directory, not a regular file." % target)
3110 3111
3111 3112 try: # User namespace
3112 3113 codeobj = eval(target, self.user_ns)
3113 3114 except Exception:
3114 3115 raise ValueError(("'%s' was not found in history, as a file, url, "
3115 3116 "nor in the user namespace.") % target)
3116 3117 if isinstance(codeobj, string_types):
3117 3118 return codeobj
3118 3119 elif isinstance(codeobj, Macro):
3119 3120 return codeobj.value
3120 3121
3121 3122 raise TypeError("%s is neither a string nor a macro." % target,
3122 3123 codeobj)
3123 3124
3124 3125 #-------------------------------------------------------------------------
3125 3126 # Things related to IPython exiting
3126 3127 #-------------------------------------------------------------------------
3127 3128 def atexit_operations(self):
3128 3129 """This will be executed at the time of exit.
3129 3130
3130 3131 Cleanup operations and saving of persistent data that is done
3131 3132 unconditionally by IPython should be performed here.
3132 3133
3133 3134 For things that may depend on startup flags or platform specifics (such
3134 3135 as having readline or not), register a separate atexit function in the
3135 3136 code that has the appropriate information, rather than trying to
3136 3137 clutter
3137 3138 """
3138 3139 # Close the history session (this stores the end time and line count)
3139 3140 # this must be *before* the tempfile cleanup, in case of temporary
3140 3141 # history db
3141 3142 self.history_manager.end_session()
3142 3143
3143 3144 # Cleanup all tempfiles left around
3144 3145 for tfile in self.tempfiles:
3145 3146 try:
3146 3147 os.unlink(tfile)
3147 3148 except OSError:
3148 3149 pass
3149 3150
3150 3151 # Clear all user namespaces to release all references cleanly.
3151 3152 self.reset(new_session=False)
3152 3153
3153 3154 # Run user hooks
3154 3155 self.hooks.shutdown_hook()
3155 3156
3156 3157 def cleanup(self):
3157 3158 self.restore_sys_module_state()
3158 3159
3159 3160
3160 class InteractiveShellABC(object):
3161 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3161 3162 """An abstract base class for InteractiveShell."""
3162 __metaclass__ = abc.ABCMeta
3163 3163
3164 3164 InteractiveShellABC.register(InteractiveShell)
@@ -1,126 +1,125 b''
1 1 """Abstract base classes for kernel client channels"""
2 2
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (C) 2013 The IPython Development Team
5 5 #
6 6 # Distributed under the terms of the BSD License. The full license is in
7 7 # the file COPYING, distributed as part of this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13
14 # Standard library imports
15 14 import abc
16 15
16 from IPython.utils.py3compat import with_metaclass
17
17 18 #-----------------------------------------------------------------------------
18 19 # Channels
19 20 #-----------------------------------------------------------------------------
20 21
21 22
22 class ChannelABC(object):
23 class ChannelABC(with_metaclass(abc.ABCMeta, object)):
23 24 """A base class for all channel ABCs."""
24 25
25 __metaclass__ = abc.ABCMeta
26
27 26 @abc.abstractmethod
28 27 def start(self):
29 28 pass
30 29
31 30 @abc.abstractmethod
32 31 def stop(self):
33 32 pass
34 33
35 34 @abc.abstractmethod
36 35 def is_alive(self):
37 36 pass
38 37
39 38
40 39 class ShellChannelABC(ChannelABC):
41 40 """ShellChannel ABC.
42 41
43 42 The docstrings for this class can be found in the base implementation:
44 43
45 44 `IPython.kernel.channels.ShellChannel`
46 45 """
47 46
48 47 @abc.abstractproperty
49 48 def allow_stdin(self):
50 49 pass
51 50
52 51 @abc.abstractmethod
53 52 def execute(self, code, silent=False, store_history=True,
54 53 user_variables=None, user_expressions=None, allow_stdin=None):
55 54 pass
56 55
57 56 @abc.abstractmethod
58 57 def complete(self, text, line, cursor_pos, block=None):
59 58 pass
60 59
61 60 @abc.abstractmethod
62 61 def object_info(self, oname, detail_level=0):
63 62 pass
64 63
65 64 @abc.abstractmethod
66 65 def history(self, raw=True, output=False, hist_access_type='range', **kwargs):
67 66 pass
68 67
69 68 @abc.abstractmethod
70 69 def kernel_info(self):
71 70 pass
72 71
73 72 @abc.abstractmethod
74 73 def shutdown(self, restart=False):
75 74 pass
76 75
77 76
78 77 class IOPubChannelABC(ChannelABC):
79 78 """IOPubChannel ABC.
80 79
81 80 The docstrings for this class can be found in the base implementation:
82 81
83 82 `IPython.kernel.channels.IOPubChannel`
84 83 """
85 84
86 85 @abc.abstractmethod
87 86 def flush(self, timeout=1.0):
88 87 pass
89 88
90 89
91 90 class StdInChannelABC(ChannelABC):
92 91 """StdInChannel ABC.
93 92
94 93 The docstrings for this class can be found in the base implementation:
95 94
96 95 `IPython.kernel.channels.StdInChannel`
97 96 """
98 97
99 98 @abc.abstractmethod
100 99 def input(self, string):
101 100 pass
102 101
103 102
104 103 class HBChannelABC(ChannelABC):
105 104 """HBChannel ABC.
106 105
107 106 The docstrings for this class can be found in the base implementation:
108 107
109 108 `IPython.kernel.channels.HBChannel`
110 109 """
111 110
112 111 @abc.abstractproperty
113 112 def time_to_dead(self):
114 113 pass
115 114
116 115 @abc.abstractmethod
117 116 def pause(self):
118 117 pass
119 118
120 119 @abc.abstractmethod
121 120 def unpause(self):
122 121 pass
123 122
124 123 @abc.abstractmethod
125 124 def is_beating(self):
126 125 pass
@@ -1,81 +1,80 b''
1 1 """Abstract base class for kernel clients"""
2 2
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (C) 2013 The IPython Development Team
5 5 #
6 6 # Distributed under the terms of the BSD License. The full license is in
7 7 # the file COPYING, distributed as part of this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13
14 # Standard library imports
15 14 import abc
16 15
16 from IPython.utils.py3compat import with_metaclass
17
17 18 #-----------------------------------------------------------------------------
18 19 # Main kernel client class
19 20 #-----------------------------------------------------------------------------
20 21
21 class KernelClientABC(object):
22 class KernelClientABC(with_metaclass(abc.ABCMeta, object)):
22 23 """KernelManager ABC.
23 24
24 25 The docstrings for this class can be found in the base implementation:
25 26
26 27 `IPython.kernel.client.KernelClient`
27 28 """
28 29
29 __metaclass__ = abc.ABCMeta
30
31 30 @abc.abstractproperty
32 31 def kernel(self):
33 32 pass
34 33
35 34 @abc.abstractproperty
36 35 def shell_channel_class(self):
37 36 pass
38 37
39 38 @abc.abstractproperty
40 39 def iopub_channel_class(self):
41 40 pass
42 41
43 42 @abc.abstractproperty
44 43 def hb_channel_class(self):
45 44 pass
46 45
47 46 @abc.abstractproperty
48 47 def stdin_channel_class(self):
49 48 pass
50 49
51 50 #--------------------------------------------------------------------------
52 51 # Channel management methods
53 52 #--------------------------------------------------------------------------
54 53
55 54 @abc.abstractmethod
56 55 def start_channels(self, shell=True, iopub=True, stdin=True, hb=True):
57 56 pass
58 57
59 58 @abc.abstractmethod
60 59 def stop_channels(self):
61 60 pass
62 61
63 62 @abc.abstractproperty
64 63 def channels_running(self):
65 64 pass
66 65
67 66 @abc.abstractproperty
68 67 def shell_channel(self):
69 68 pass
70 69
71 70 @abc.abstractproperty
72 71 def iopub_channel(self):
73 72 pass
74 73
75 74 @abc.abstractproperty
76 75 def stdin_channel(self):
77 76 pass
78 77
79 78 @abc.abstractproperty
80 79 def hb_channel(self):
81 80 pass
@@ -1,66 +1,65 b''
1 1 """ Defines a dummy socket implementing (part of) the zmq.Socket interface. """
2 2
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (C) 2012 The IPython Development Team
5 5 #
6 6 # Distributed under the terms of the BSD License. The full license is in
7 7 # the file COPYING, distributed as part of this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13
14 14 # Standard library imports.
15 15 import abc
16 16 try:
17 17 from queue import Queue # Py 3
18 18 except ImportError:
19 19 from Queue import Queue # Py 2
20 20
21 21 # System library imports.
22 22 import zmq
23 23
24 24 # Local imports.
25 25 from IPython.utils.traitlets import HasTraits, Instance, Int
26 from IPython.utils.py3compat import with_metaclass
26 27
27 28 #-----------------------------------------------------------------------------
28 29 # Generic socket interface
29 30 #-----------------------------------------------------------------------------
30 31
31 class SocketABC(object):
32 __metaclass__ = abc.ABCMeta
33
32 class SocketABC(with_metaclass(abc.ABCMeta, object)):
34 33 @abc.abstractmethod
35 34 def recv_multipart(self, flags=0, copy=True, track=False):
36 35 raise NotImplementedError
37 36
38 37 @abc.abstractmethod
39 38 def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
40 39 raise NotImplementedError
41 40
42 41 SocketABC.register(zmq.Socket)
43 42
44 43 #-----------------------------------------------------------------------------
45 44 # Dummy socket class
46 45 #-----------------------------------------------------------------------------
47 46
48 47 class DummySocket(HasTraits):
49 48 """ A dummy socket implementing (part of) the zmq.Socket interface. """
50 49
51 50 queue = Instance(Queue, ())
52 51 message_sent = Int(0) # Should be an Event
53 52
54 53 #-------------------------------------------------------------------------
55 54 # Socket interface
56 55 #-------------------------------------------------------------------------
57 56
58 57 def recv_multipart(self, flags=0, copy=True, track=False):
59 58 return self.queue.get_nowait()
60 59
61 60 def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
62 61 msg_parts = map(zmq.Message, msg_parts)
63 62 self.queue.put_nowait(msg_parts)
64 63 self.message_sent += 1
65 64
66 65 SocketABC.register(DummySocket)
@@ -1,225 +1,222 b''
1 1 """Abstract base classes for kernel manager and channels."""
2 2
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (C) 2013 The IPython Development Team
5 5 #
6 6 # Distributed under the terms of the BSD License. The full license is in
7 7 # the file COPYING, distributed as part of this software.
8 8 #-----------------------------------------------------------------------------
9 9
10 10 #-----------------------------------------------------------------------------
11 11 # Imports
12 12 #-----------------------------------------------------------------------------
13 13
14 # Standard library imports.
15 14 import abc
16 15
16 from IPython.utils.py3compat import with_metaclass
17
17 18 #-----------------------------------------------------------------------------
18 19 # Channels
19 20 #-----------------------------------------------------------------------------
20 21
21 22
22 class ChannelABC(object):
23 class ChannelABC(with_metaclass(abc.ABCMeta, object)):
23 24 """A base class for all channel ABCs."""
24 25
25 __metaclass__ = abc.ABCMeta
26
27 26 @abc.abstractmethod
28 27 def start(self):
29 28 pass
30 29
31 30 @abc.abstractmethod
32 31 def stop(self):
33 32 pass
34 33
35 34 @abc.abstractmethod
36 35 def is_alive(self):
37 36 pass
38 37
39 38
40 39 class ShellChannelABC(ChannelABC):
41 40 """ShellChannel ABC.
42 41
43 42 The docstrings for this class can be found in the base implementation:
44 43
45 44 `IPython.kernel.kernelmanager.ShellChannel`
46 45 """
47 46
48 47 @abc.abstractproperty
49 48 def allow_stdin(self):
50 49 pass
51 50
52 51 @abc.abstractmethod
53 52 def execute(self, code, silent=False, store_history=True,
54 53 user_variables=None, user_expressions=None, allow_stdin=None):
55 54 pass
56 55
57 56 @abc.abstractmethod
58 57 def complete(self, text, line, cursor_pos, block=None):
59 58 pass
60 59
61 60 @abc.abstractmethod
62 61 def object_info(self, oname, detail_level=0):
63 62 pass
64 63
65 64 @abc.abstractmethod
66 65 def history(self, raw=True, output=False, hist_access_type='range', **kwargs):
67 66 pass
68 67
69 68 @abc.abstractmethod
70 69 def kernel_info(self):
71 70 pass
72 71
73 72 @abc.abstractmethod
74 73 def shutdown(self, restart=False):
75 74 pass
76 75
77 76
78 77 class IOPubChannelABC(ChannelABC):
79 78 """IOPubChannel ABC.
80 79
81 80 The docstrings for this class can be found in the base implementation:
82 81
83 82 `IPython.kernel.kernelmanager.IOPubChannel`
84 83 """
85 84
86 85 @abc.abstractmethod
87 86 def flush(self, timeout=1.0):
88 87 pass
89 88
90 89
91 90 class StdInChannelABC(ChannelABC):
92 91 """StdInChannel ABC.
93 92
94 93 The docstrings for this class can be found in the base implementation:
95 94
96 95 `IPython.kernel.kernelmanager.StdInChannel`
97 96 """
98 97
99 98 @abc.abstractmethod
100 99 def input(self, string):
101 100 pass
102 101
103 102
104 103 class HBChannelABC(ChannelABC):
105 104 """HBChannel ABC.
106 105
107 106 The docstrings for this class can be found in the base implementation:
108 107
109 108 `IPython.kernel.kernelmanager.HBChannel`
110 109 """
111 110
112 111 @abc.abstractproperty
113 112 def time_to_dead(self):
114 113 pass
115 114
116 115 @abc.abstractmethod
117 116 def pause(self):
118 117 pass
119 118
120 119 @abc.abstractmethod
121 120 def unpause(self):
122 121 pass
123 122
124 123 @abc.abstractmethod
125 124 def is_beating(self):
126 125 pass
127 126
128 127
129 128 #-----------------------------------------------------------------------------
130 129 # Main kernel manager class
131 130 #-----------------------------------------------------------------------------
132 131
133 class KernelManagerABC(object):
132 class KernelManagerABC(with_metaclass(abc.ABCMeta, object)):
134 133 """KernelManager ABC.
135 134
136 135 The docstrings for this class can be found in the base implementation:
137 136
138 137 `IPython.kernel.kernelmanager.KernelManager`
139 138 """
140 139
141 __metaclass__ = abc.ABCMeta
142
143 140 @abc.abstractproperty
144 141 def kernel(self):
145 142 pass
146 143
147 144 @abc.abstractproperty
148 145 def shell_channel_class(self):
149 146 pass
150 147
151 148 @abc.abstractproperty
152 149 def iopub_channel_class(self):
153 150 pass
154 151
155 152 @abc.abstractproperty
156 153 def hb_channel_class(self):
157 154 pass
158 155
159 156 @abc.abstractproperty
160 157 def stdin_channel_class(self):
161 158 pass
162 159
163 160 #--------------------------------------------------------------------------
164 161 # Channel management methods
165 162 #--------------------------------------------------------------------------
166 163
167 164 @abc.abstractmethod
168 165 def start_channels(self, shell=True, iopub=True, stdin=True, hb=True):
169 166 pass
170 167
171 168 @abc.abstractmethod
172 169 def stop_channels(self):
173 170 pass
174 171
175 172 @abc.abstractproperty
176 173 def channels_running(self):
177 174 pass
178 175
179 176 @abc.abstractproperty
180 177 def shell_channel(self):
181 178 pass
182 179
183 180 @abc.abstractproperty
184 181 def iopub_channel(self):
185 182 pass
186 183
187 184 @abc.abstractproperty
188 185 def stdin_channel(self):
189 186 pass
190 187
191 188 @abc.abstractproperty
192 189 def hb_channel(self):
193 190 pass
194 191
195 192 #--------------------------------------------------------------------------
196 193 # Kernel management
197 194 #--------------------------------------------------------------------------
198 195
199 196 @abc.abstractmethod
200 197 def start_kernel(self, **kw):
201 198 pass
202 199
203 200 @abc.abstractmethod
204 201 def shutdown_kernel(self, now=False, restart=False):
205 202 pass
206 203
207 204 @abc.abstractmethod
208 205 def restart_kernel(self, now=False, **kw):
209 206 pass
210 207
211 208 @abc.abstractproperty
212 209 def has_kernel(self):
213 210 pass
214 211
215 212 @abc.abstractmethod
216 213 def interrupt_kernel(self):
217 214 pass
218 215
219 216 @abc.abstractmethod
220 217 def signal_kernel(self, signum):
221 218 pass
222 219
223 220 @abc.abstractmethod
224 221 def is_alive(self):
225 222 pass
@@ -1,2110 +1,2110 b''
1 1 """ An abstract base class for console-type widgets.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Imports
5 5 #-----------------------------------------------------------------------------
6 6
7 7 # Standard library imports
8 8 import os.path
9 9 import re
10 10 import sys
11 11 from textwrap import dedent
12 12 import time
13 13 from unicodedata import category
14 14 import webbrowser
15 15
16 16 # System library imports
17 17 from IPython.external.qt import QtCore, QtGui
18 18
19 19 # Local imports
20 20 from IPython.config.configurable import LoggingConfigurable
21 21 from IPython.core.inputsplitter import ESC_SEQUENCES
22 22 from IPython.qt.rich_text import HtmlExporter
23 23 from IPython.qt.util import MetaQObjectHasTraits, get_font
24 from IPython.utils.py3compat import with_metaclass
24 25 from IPython.utils.text import columnize
25 26 from IPython.utils.traitlets import Bool, Enum, Integer, Unicode
26 27 from .ansi_code_processor import QtAnsiCodeProcessor
27 28 from .completion_widget import CompletionWidget
28 29 from .completion_html import CompletionHtml
29 30 from .completion_plain import CompletionPlain
30 31 from .kill_ring import QtKillRing
31 32
32 33
33 34 #-----------------------------------------------------------------------------
34 35 # Functions
35 36 #-----------------------------------------------------------------------------
36 37
37 38 ESCAPE_CHARS = ''.join(ESC_SEQUENCES)
38 39 ESCAPE_RE = re.compile("^["+ESCAPE_CHARS+"]+")
39 40
40 41 def commonprefix(items):
41 42 """Get common prefix for completions
42 43
43 44 Return the longest common prefix of a list of strings, but with special
44 45 treatment of escape characters that might precede commands in IPython,
45 46 such as %magic functions. Used in tab completion.
46 47
47 48 For a more general function, see os.path.commonprefix
48 49 """
49 50 # the last item will always have the least leading % symbol
50 51 # min / max are first/last in alphabetical order
51 52 first_match = ESCAPE_RE.match(min(items))
52 53 last_match = ESCAPE_RE.match(max(items))
53 54 # common suffix is (common prefix of reversed items) reversed
54 55 if first_match and last_match:
55 56 prefix = os.path.commonprefix((first_match.group(0)[::-1], last_match.group(0)[::-1]))[::-1]
56 57 else:
57 58 prefix = ''
58 59
59 60 items = [s.lstrip(ESCAPE_CHARS) for s in items]
60 61 return prefix+os.path.commonprefix(items)
61 62
62 63 def is_letter_or_number(char):
63 64 """ Returns whether the specified unicode character is a letter or a number.
64 65 """
65 66 cat = category(char)
66 67 return cat.startswith('L') or cat.startswith('N')
67 68
68 69 #-----------------------------------------------------------------------------
69 70 # Classes
70 71 #-----------------------------------------------------------------------------
71 72
72 class ConsoleWidget(LoggingConfigurable, QtGui.QWidget):
73 class ConsoleWidget(with_metaclass(MetaQObjectHasTraits, type('NewBase', (LoggingConfigurable, QtGui.QWidget), {}))):
73 74 """ An abstract base class for console-type widgets. This class has
74 75 functionality for:
75 76
76 77 * Maintaining a prompt and editing region
77 78 * Providing the traditional Unix-style console keyboard shortcuts
78 79 * Performing tab completion
79 80 * Paging text
80 81 * Handling ANSI escape codes
81 82
82 83 ConsoleWidget also provides a number of utility methods that will be
83 84 convenient to implementors of a console-style widget.
84 85 """
85 __metaclass__ = MetaQObjectHasTraits
86 86
87 87 #------ Configuration ------------------------------------------------------
88 88
89 89 ansi_codes = Bool(True, config=True,
90 90 help="Whether to process ANSI escape codes."
91 91 )
92 92 buffer_size = Integer(500, config=True,
93 93 help="""
94 94 The maximum number of lines of text before truncation. Specifying a
95 95 non-positive number disables text truncation (not recommended).
96 96 """
97 97 )
98 98 execute_on_complete_input = Bool(True, config=True,
99 99 help="""Whether to automatically execute on syntactically complete input.
100 100
101 101 If False, Shift-Enter is required to submit each execution.
102 102 Disabling this is mainly useful for non-Python kernels,
103 103 where the completion check would be wrong.
104 104 """
105 105 )
106 106 gui_completion = Enum(['plain', 'droplist', 'ncurses'], config=True,
107 107 default_value = 'ncurses',
108 108 help="""
109 109 The type of completer to use. Valid values are:
110 110
111 111 'plain' : Show the available completion as a text list
112 112 Below the editing area.
113 113 'droplist': Show the completion in a drop down list navigable
114 114 by the arrow keys, and from which you can select
115 115 completion by pressing Return.
116 116 'ncurses' : Show the completion as a text list which is navigable by
117 117 `tab` and arrow keys.
118 118 """
119 119 )
120 120 # NOTE: this value can only be specified during initialization.
121 121 kind = Enum(['plain', 'rich'], default_value='plain', config=True,
122 122 help="""
123 123 The type of underlying text widget to use. Valid values are 'plain',
124 124 which specifies a QPlainTextEdit, and 'rich', which specifies a
125 125 QTextEdit.
126 126 """
127 127 )
128 128 # NOTE: this value can only be specified during initialization.
129 129 paging = Enum(['inside', 'hsplit', 'vsplit', 'custom', 'none'],
130 130 default_value='inside', config=True,
131 131 help="""
132 132 The type of paging to use. Valid values are:
133 133
134 134 'inside' : The widget pages like a traditional terminal.
135 135 'hsplit' : When paging is requested, the widget is split
136 136 horizontally. The top pane contains the console, and the
137 137 bottom pane contains the paged text.
138 138 'vsplit' : Similar to 'hsplit', except that a vertical splitter
139 139 used.
140 140 'custom' : No action is taken by the widget beyond emitting a
141 141 'custom_page_requested(str)' signal.
142 142 'none' : The text is written directly to the console.
143 143 """)
144 144
145 145 font_family = Unicode(config=True,
146 146 help="""The font family to use for the console.
147 147 On OSX this defaults to Monaco, on Windows the default is
148 148 Consolas with fallback of Courier, and on other platforms
149 149 the default is Monospace.
150 150 """)
151 151 def _font_family_default(self):
152 152 if sys.platform == 'win32':
153 153 # Consolas ships with Vista/Win7, fallback to Courier if needed
154 154 return 'Consolas'
155 155 elif sys.platform == 'darwin':
156 156 # OSX always has Monaco, no need for a fallback
157 157 return 'Monaco'
158 158 else:
159 159 # Monospace should always exist, no need for a fallback
160 160 return 'Monospace'
161 161
162 162 font_size = Integer(config=True,
163 163 help="""The font size. If unconfigured, Qt will be entrusted
164 164 with the size of the font.
165 165 """)
166 166
167 167 width = Integer(81, config=True,
168 168 help="""The width of the console at start time in number
169 169 of characters (will double with `hsplit` paging)
170 170 """)
171 171
172 172 height = Integer(25, config=True,
173 173 help="""The height of the console at start time in number
174 174 of characters (will double with `vsplit` paging)
175 175 """)
176 176
177 177 # Whether to override ShortcutEvents for the keybindings defined by this
178 178 # widget (Ctrl+n, Ctrl+a, etc). Enable this if you want this widget to take
179 179 # priority (when it has focus) over, e.g., window-level menu shortcuts.
180 180 override_shortcuts = Bool(False)
181 181
182 182 # ------ Custom Qt Widgets -------------------------------------------------
183 183
184 184 # For other projects to easily override the Qt widgets used by the console
185 185 # (e.g. Spyder)
186 186 custom_control = None
187 187 custom_page_control = None
188 188
189 189 #------ Signals ------------------------------------------------------------
190 190
191 191 # Signals that indicate ConsoleWidget state.
192 192 copy_available = QtCore.Signal(bool)
193 193 redo_available = QtCore.Signal(bool)
194 194 undo_available = QtCore.Signal(bool)
195 195
196 196 # Signal emitted when paging is needed and the paging style has been
197 197 # specified as 'custom'.
198 198 custom_page_requested = QtCore.Signal(object)
199 199
200 200 # Signal emitted when the font is changed.
201 201 font_changed = QtCore.Signal(QtGui.QFont)
202 202
203 203 #------ Protected class variables ------------------------------------------
204 204
205 205 # control handles
206 206 _control = None
207 207 _page_control = None
208 208 _splitter = None
209 209
210 210 # When the control key is down, these keys are mapped.
211 211 _ctrl_down_remap = { QtCore.Qt.Key_B : QtCore.Qt.Key_Left,
212 212 QtCore.Qt.Key_F : QtCore.Qt.Key_Right,
213 213 QtCore.Qt.Key_A : QtCore.Qt.Key_Home,
214 214 QtCore.Qt.Key_P : QtCore.Qt.Key_Up,
215 215 QtCore.Qt.Key_N : QtCore.Qt.Key_Down,
216 216 QtCore.Qt.Key_H : QtCore.Qt.Key_Backspace, }
217 217 if not sys.platform == 'darwin':
218 218 # On OS X, Ctrl-E already does the right thing, whereas End moves the
219 219 # cursor to the bottom of the buffer.
220 220 _ctrl_down_remap[QtCore.Qt.Key_E] = QtCore.Qt.Key_End
221 221
222 222 # The shortcuts defined by this widget. We need to keep track of these to
223 223 # support 'override_shortcuts' above.
224 224 _shortcuts = set(_ctrl_down_remap.keys() +
225 225 [ QtCore.Qt.Key_C, QtCore.Qt.Key_G, QtCore.Qt.Key_O,
226 226 QtCore.Qt.Key_V ])
227 227
228 228 _temp_buffer_filled = False
229 229
230 230 #---------------------------------------------------------------------------
231 231 # 'QObject' interface
232 232 #---------------------------------------------------------------------------
233 233
234 234 def __init__(self, parent=None, **kw):
235 235 """ Create a ConsoleWidget.
236 236
237 237 Parameters:
238 238 -----------
239 239 parent : QWidget, optional [default None]
240 240 The parent for this widget.
241 241 """
242 242 QtGui.QWidget.__init__(self, parent)
243 243 LoggingConfigurable.__init__(self, **kw)
244 244
245 245 # While scrolling the pager on Mac OS X, it tears badly. The
246 246 # NativeGesture is platform and perhaps build-specific hence
247 247 # we take adequate precautions here.
248 248 self._pager_scroll_events = [QtCore.QEvent.Wheel]
249 249 if hasattr(QtCore.QEvent, 'NativeGesture'):
250 250 self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)
251 251
252 252 # Create the layout and underlying text widget.
253 253 layout = QtGui.QStackedLayout(self)
254 254 layout.setContentsMargins(0, 0, 0, 0)
255 255 self._control = self._create_control()
256 256 if self.paging in ('hsplit', 'vsplit'):
257 257 self._splitter = QtGui.QSplitter()
258 258 if self.paging == 'hsplit':
259 259 self._splitter.setOrientation(QtCore.Qt.Horizontal)
260 260 else:
261 261 self._splitter.setOrientation(QtCore.Qt.Vertical)
262 262 self._splitter.addWidget(self._control)
263 263 layout.addWidget(self._splitter)
264 264 else:
265 265 layout.addWidget(self._control)
266 266
267 267 # Create the paging widget, if necessary.
268 268 if self.paging in ('inside', 'hsplit', 'vsplit'):
269 269 self._page_control = self._create_page_control()
270 270 if self._splitter:
271 271 self._page_control.hide()
272 272 self._splitter.addWidget(self._page_control)
273 273 else:
274 274 layout.addWidget(self._page_control)
275 275
276 276 # Initialize protected variables. Some variables contain useful state
277 277 # information for subclasses; they should be considered read-only.
278 278 self._append_before_prompt_pos = 0
279 279 self._ansi_processor = QtAnsiCodeProcessor()
280 280 if self.gui_completion == 'ncurses':
281 281 self._completion_widget = CompletionHtml(self)
282 282 elif self.gui_completion == 'droplist':
283 283 self._completion_widget = CompletionWidget(self)
284 284 elif self.gui_completion == 'plain':
285 285 self._completion_widget = CompletionPlain(self)
286 286
287 287 self._continuation_prompt = '> '
288 288 self._continuation_prompt_html = None
289 289 self._executing = False
290 290 self._filter_resize = False
291 291 self._html_exporter = HtmlExporter(self._control)
292 292 self._input_buffer_executing = ''
293 293 self._input_buffer_pending = ''
294 294 self._kill_ring = QtKillRing(self._control)
295 295 self._prompt = ''
296 296 self._prompt_html = None
297 297 self._prompt_pos = 0
298 298 self._prompt_sep = ''
299 299 self._reading = False
300 300 self._reading_callback = None
301 301 self._tab_width = 8
302 302
303 303 # List of strings pending to be appended as plain text in the widget.
304 304 # The text is not immediately inserted when available to not
305 305 # choke the Qt event loop with paint events for the widget in
306 306 # case of lots of output from kernel.
307 307 self._pending_insert_text = []
308 308
309 309 # Timer to flush the pending stream messages. The interval is adjusted
310 310 # later based on actual time taken for flushing a screen (buffer_size)
311 311 # of output text.
312 312 self._pending_text_flush_interval = QtCore.QTimer(self._control)
313 313 self._pending_text_flush_interval.setInterval(100)
314 314 self._pending_text_flush_interval.setSingleShot(True)
315 315 self._pending_text_flush_interval.timeout.connect(
316 316 self._flush_pending_stream)
317 317
318 318 # Set a monospaced font.
319 319 self.reset_font()
320 320
321 321 # Configure actions.
322 322 action = QtGui.QAction('Print', None)
323 323 action.setEnabled(True)
324 324 printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)
325 325 if printkey.matches("Ctrl+P") and sys.platform != 'darwin':
326 326 # Only override the default if there is a collision.
327 327 # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
328 328 printkey = "Ctrl+Shift+P"
329 329 action.setShortcut(printkey)
330 330 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
331 331 action.triggered.connect(self.print_)
332 332 self.addAction(action)
333 333 self.print_action = action
334 334
335 335 action = QtGui.QAction('Save as HTML/XML', None)
336 336 action.setShortcut(QtGui.QKeySequence.Save)
337 337 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
338 338 action.triggered.connect(self.export_html)
339 339 self.addAction(action)
340 340 self.export_action = action
341 341
342 342 action = QtGui.QAction('Select All', None)
343 343 action.setEnabled(True)
344 344 selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)
345 345 if selectall.matches("Ctrl+A") and sys.platform != 'darwin':
346 346 # Only override the default if there is a collision.
347 347 # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX.
348 348 selectall = "Ctrl+Shift+A"
349 349 action.setShortcut(selectall)
350 350 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
351 351 action.triggered.connect(self.select_all)
352 352 self.addAction(action)
353 353 self.select_all_action = action
354 354
355 355 self.increase_font_size = QtGui.QAction("Bigger Font",
356 356 self,
357 357 shortcut=QtGui.QKeySequence.ZoomIn,
358 358 shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
359 359 statusTip="Increase the font size by one point",
360 360 triggered=self._increase_font_size)
361 361 self.addAction(self.increase_font_size)
362 362
363 363 self.decrease_font_size = QtGui.QAction("Smaller Font",
364 364 self,
365 365 shortcut=QtGui.QKeySequence.ZoomOut,
366 366 shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
367 367 statusTip="Decrease the font size by one point",
368 368 triggered=self._decrease_font_size)
369 369 self.addAction(self.decrease_font_size)
370 370
371 371 self.reset_font_size = QtGui.QAction("Normal Font",
372 372 self,
373 373 shortcut="Ctrl+0",
374 374 shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,
375 375 statusTip="Restore the Normal font size",
376 376 triggered=self.reset_font)
377 377 self.addAction(self.reset_font_size)
378 378
379 379 # Accept drag and drop events here. Drops were already turned off
380 380 # in self._control when that widget was created.
381 381 self.setAcceptDrops(True)
382 382
383 383 #---------------------------------------------------------------------------
384 384 # Drag and drop support
385 385 #---------------------------------------------------------------------------
386 386
387 387 def dragEnterEvent(self, e):
388 388 if e.mimeData().hasUrls():
389 389 # The link action should indicate to that the drop will insert
390 390 # the file anme.
391 391 e.setDropAction(QtCore.Qt.LinkAction)
392 392 e.accept()
393 393 elif e.mimeData().hasText():
394 394 # By changing the action to copy we don't need to worry about
395 395 # the user accidentally moving text around in the widget.
396 396 e.setDropAction(QtCore.Qt.CopyAction)
397 397 e.accept()
398 398
399 399 def dragMoveEvent(self, e):
400 400 if e.mimeData().hasUrls():
401 401 pass
402 402 elif e.mimeData().hasText():
403 403 cursor = self._control.cursorForPosition(e.pos())
404 404 if self._in_buffer(cursor.position()):
405 405 e.setDropAction(QtCore.Qt.CopyAction)
406 406 self._control.setTextCursor(cursor)
407 407 else:
408 408 e.setDropAction(QtCore.Qt.IgnoreAction)
409 409 e.accept()
410 410
411 411 def dropEvent(self, e):
412 412 if e.mimeData().hasUrls():
413 413 self._keep_cursor_in_buffer()
414 414 cursor = self._control.textCursor()
415 415 filenames = [url.toLocalFile() for url in e.mimeData().urls()]
416 416 text = ', '.join("'" + f.replace("'", "'\"'\"'") + "'"
417 417 for f in filenames)
418 418 self._insert_plain_text_into_buffer(cursor, text)
419 419 elif e.mimeData().hasText():
420 420 cursor = self._control.cursorForPosition(e.pos())
421 421 if self._in_buffer(cursor.position()):
422 422 text = e.mimeData().text()
423 423 self._insert_plain_text_into_buffer(cursor, text)
424 424
425 425 def eventFilter(self, obj, event):
426 426 """ Reimplemented to ensure a console-like behavior in the underlying
427 427 text widgets.
428 428 """
429 429 etype = event.type()
430 430 if etype == QtCore.QEvent.KeyPress:
431 431
432 432 # Re-map keys for all filtered widgets.
433 433 key = event.key()
434 434 if self._control_key_down(event.modifiers()) and \
435 435 key in self._ctrl_down_remap:
436 436 new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
437 437 self._ctrl_down_remap[key],
438 438 QtCore.Qt.NoModifier)
439 439 QtGui.qApp.sendEvent(obj, new_event)
440 440 return True
441 441
442 442 elif obj == self._control:
443 443 return self._event_filter_console_keypress(event)
444 444
445 445 elif obj == self._page_control:
446 446 return self._event_filter_page_keypress(event)
447 447
448 448 # Make middle-click paste safe.
449 449 elif etype == QtCore.QEvent.MouseButtonRelease and \
450 450 event.button() == QtCore.Qt.MidButton and \
451 451 obj == self._control.viewport():
452 452 cursor = self._control.cursorForPosition(event.pos())
453 453 self._control.setTextCursor(cursor)
454 454 self.paste(QtGui.QClipboard.Selection)
455 455 return True
456 456
457 457 # Manually adjust the scrollbars *after* a resize event is dispatched.
458 458 elif etype == QtCore.QEvent.Resize and not self._filter_resize:
459 459 self._filter_resize = True
460 460 QtGui.qApp.sendEvent(obj, event)
461 461 self._adjust_scrollbars()
462 462 self._filter_resize = False
463 463 return True
464 464
465 465 # Override shortcuts for all filtered widgets.
466 466 elif etype == QtCore.QEvent.ShortcutOverride and \
467 467 self.override_shortcuts and \
468 468 self._control_key_down(event.modifiers()) and \
469 469 event.key() in self._shortcuts:
470 470 event.accept()
471 471
472 472 # Handle scrolling of the vsplit pager. This hack attempts to solve
473 473 # problems with tearing of the help text inside the pager window. This
474 474 # happens only on Mac OS X with both PySide and PyQt. This fix isn't
475 475 # perfect but makes the pager more usable.
476 476 elif etype in self._pager_scroll_events and \
477 477 obj == self._page_control:
478 478 self._page_control.repaint()
479 479 return True
480 480
481 481 elif etype == QtCore.QEvent.MouseMove:
482 482 anchor = self._control.anchorAt(event.pos())
483 483 QtGui.QToolTip.showText(event.globalPos(), anchor)
484 484
485 485 return super(ConsoleWidget, self).eventFilter(obj, event)
486 486
487 487 #---------------------------------------------------------------------------
488 488 # 'QWidget' interface
489 489 #---------------------------------------------------------------------------
490 490
491 491 def sizeHint(self):
492 492 """ Reimplemented to suggest a size that is 80 characters wide and
493 493 25 lines high.
494 494 """
495 495 font_metrics = QtGui.QFontMetrics(self.font)
496 496 margin = (self._control.frameWidth() +
497 497 self._control.document().documentMargin()) * 2
498 498 style = self.style()
499 499 splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)
500 500
501 501 # Note 1: Despite my best efforts to take the various margins into
502 502 # account, the width is still coming out a bit too small, so we include
503 503 # a fudge factor of one character here.
504 504 # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
505 505 # to a Qt bug on certain Mac OS systems where it returns 0.
506 506 width = font_metrics.width(' ') * self.width + margin
507 507 width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
508 508 if self.paging == 'hsplit':
509 509 width = width * 2 + splitwidth
510 510
511 511 height = font_metrics.height() * self.height + margin
512 512 if self.paging == 'vsplit':
513 513 height = height * 2 + splitwidth
514 514
515 515 return QtCore.QSize(width, height)
516 516
517 517 #---------------------------------------------------------------------------
518 518 # 'ConsoleWidget' public interface
519 519 #---------------------------------------------------------------------------
520 520
521 521 def can_copy(self):
522 522 """ Returns whether text can be copied to the clipboard.
523 523 """
524 524 return self._control.textCursor().hasSelection()
525 525
526 526 def can_cut(self):
527 527 """ Returns whether text can be cut to the clipboard.
528 528 """
529 529 cursor = self._control.textCursor()
530 530 return (cursor.hasSelection() and
531 531 self._in_buffer(cursor.anchor()) and
532 532 self._in_buffer(cursor.position()))
533 533
534 534 def can_paste(self):
535 535 """ Returns whether text can be pasted from the clipboard.
536 536 """
537 537 if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
538 538 return bool(QtGui.QApplication.clipboard().text())
539 539 return False
540 540
541 541 def clear(self, keep_input=True):
542 542 """ Clear the console.
543 543
544 544 Parameters:
545 545 -----------
546 546 keep_input : bool, optional (default True)
547 547 If set, restores the old input buffer if a new prompt is written.
548 548 """
549 549 if self._executing:
550 550 self._control.clear()
551 551 else:
552 552 if keep_input:
553 553 input_buffer = self.input_buffer
554 554 self._control.clear()
555 555 self._show_prompt()
556 556 if keep_input:
557 557 self.input_buffer = input_buffer
558 558
559 559 def copy(self):
560 560 """ Copy the currently selected text to the clipboard.
561 561 """
562 562 self.layout().currentWidget().copy()
563 563
564 564 def copy_anchor(self, anchor):
565 565 """ Copy anchor text to the clipboard
566 566 """
567 567 QtGui.QApplication.clipboard().setText(anchor)
568 568
569 569 def cut(self):
570 570 """ Copy the currently selected text to the clipboard and delete it
571 571 if it's inside the input buffer.
572 572 """
573 573 self.copy()
574 574 if self.can_cut():
575 575 self._control.textCursor().removeSelectedText()
576 576
577 577 def execute(self, source=None, hidden=False, interactive=False):
578 578 """ Executes source or the input buffer, possibly prompting for more
579 579 input.
580 580
581 581 Parameters:
582 582 -----------
583 583 source : str, optional
584 584
585 585 The source to execute. If not specified, the input buffer will be
586 586 used. If specified and 'hidden' is False, the input buffer will be
587 587 replaced with the source before execution.
588 588
589 589 hidden : bool, optional (default False)
590 590
591 591 If set, no output will be shown and the prompt will not be modified.
592 592 In other words, it will be completely invisible to the user that
593 593 an execution has occurred.
594 594
595 595 interactive : bool, optional (default False)
596 596
597 597 Whether the console is to treat the source as having been manually
598 598 entered by the user. The effect of this parameter depends on the
599 599 subclass implementation.
600 600
601 601 Raises:
602 602 -------
603 603 RuntimeError
604 604 If incomplete input is given and 'hidden' is True. In this case,
605 605 it is not possible to prompt for more input.
606 606
607 607 Returns:
608 608 --------
609 609 A boolean indicating whether the source was executed.
610 610 """
611 611 # WARNING: The order in which things happen here is very particular, in
612 612 # large part because our syntax highlighting is fragile. If you change
613 613 # something, test carefully!
614 614
615 615 # Decide what to execute.
616 616 if source is None:
617 617 source = self.input_buffer
618 618 if not hidden:
619 619 # A newline is appended later, but it should be considered part
620 620 # of the input buffer.
621 621 source += '\n'
622 622 elif not hidden:
623 623 self.input_buffer = source
624 624
625 625 # Execute the source or show a continuation prompt if it is incomplete.
626 626 if self.execute_on_complete_input:
627 627 complete = self._is_complete(source, interactive)
628 628 else:
629 629 complete = not interactive
630 630 if hidden:
631 631 if complete or not self.execute_on_complete_input:
632 632 self._execute(source, hidden)
633 633 else:
634 634 error = 'Incomplete noninteractive input: "%s"'
635 635 raise RuntimeError(error % source)
636 636 else:
637 637 if complete:
638 638 self._append_plain_text('\n')
639 639 self._input_buffer_executing = self.input_buffer
640 640 self._executing = True
641 641 self._prompt_finished()
642 642
643 643 # The maximum block count is only in effect during execution.
644 644 # This ensures that _prompt_pos does not become invalid due to
645 645 # text truncation.
646 646 self._control.document().setMaximumBlockCount(self.buffer_size)
647 647
648 648 # Setting a positive maximum block count will automatically
649 649 # disable the undo/redo history, but just to be safe:
650 650 self._control.setUndoRedoEnabled(False)
651 651
652 652 # Perform actual execution.
653 653 self._execute(source, hidden)
654 654
655 655 else:
656 656 # Do this inside an edit block so continuation prompts are
657 657 # removed seamlessly via undo/redo.
658 658 cursor = self._get_end_cursor()
659 659 cursor.beginEditBlock()
660 660 cursor.insertText('\n')
661 661 self._insert_continuation_prompt(cursor)
662 662 cursor.endEditBlock()
663 663
664 664 # Do not do this inside the edit block. It works as expected
665 665 # when using a QPlainTextEdit control, but does not have an
666 666 # effect when using a QTextEdit. I believe this is a Qt bug.
667 667 self._control.moveCursor(QtGui.QTextCursor.End)
668 668
669 669 return complete
670 670
671 671 def export_html(self):
672 672 """ Shows a dialog to export HTML/XML in various formats.
673 673 """
674 674 self._html_exporter.export()
675 675
676 676 def _get_input_buffer(self, force=False):
677 677 """ The text that the user has entered entered at the current prompt.
678 678
679 679 If the console is currently executing, the text that is executing will
680 680 always be returned.
681 681 """
682 682 # If we're executing, the input buffer may not even exist anymore due to
683 683 # the limit imposed by 'buffer_size'. Therefore, we store it.
684 684 if self._executing and not force:
685 685 return self._input_buffer_executing
686 686
687 687 cursor = self._get_end_cursor()
688 688 cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
689 689 input_buffer = cursor.selection().toPlainText()
690 690
691 691 # Strip out continuation prompts.
692 692 return input_buffer.replace('\n' + self._continuation_prompt, '\n')
693 693
694 694 def _set_input_buffer(self, string):
695 695 """ Sets the text in the input buffer.
696 696
697 697 If the console is currently executing, this call has no *immediate*
698 698 effect. When the execution is finished, the input buffer will be updated
699 699 appropriately.
700 700 """
701 701 # If we're executing, store the text for later.
702 702 if self._executing:
703 703 self._input_buffer_pending = string
704 704 return
705 705
706 706 # Remove old text.
707 707 cursor = self._get_end_cursor()
708 708 cursor.beginEditBlock()
709 709 cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)
710 710 cursor.removeSelectedText()
711 711
712 712 # Insert new text with continuation prompts.
713 713 self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)
714 714 cursor.endEditBlock()
715 715 self._control.moveCursor(QtGui.QTextCursor.End)
716 716
717 717 input_buffer = property(_get_input_buffer, _set_input_buffer)
718 718
719 719 def _get_font(self):
720 720 """ The base font being used by the ConsoleWidget.
721 721 """
722 722 return self._control.document().defaultFont()
723 723
724 724 def _set_font(self, font):
725 725 """ Sets the base font for the ConsoleWidget to the specified QFont.
726 726 """
727 727 font_metrics = QtGui.QFontMetrics(font)
728 728 self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
729 729
730 730 self._completion_widget.setFont(font)
731 731 self._control.document().setDefaultFont(font)
732 732 if self._page_control:
733 733 self._page_control.document().setDefaultFont(font)
734 734
735 735 self.font_changed.emit(font)
736 736
737 737 font = property(_get_font, _set_font)
738 738
739 739 def open_anchor(self, anchor):
740 740 """ Open selected anchor in the default webbrowser
741 741 """
742 742 webbrowser.open( anchor )
743 743
744 744 def paste(self, mode=QtGui.QClipboard.Clipboard):
745 745 """ Paste the contents of the clipboard into the input region.
746 746
747 747 Parameters:
748 748 -----------
749 749 mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
750 750
751 751 Controls which part of the system clipboard is used. This can be
752 752 used to access the selection clipboard in X11 and the Find buffer
753 753 in Mac OS. By default, the regular clipboard is used.
754 754 """
755 755 if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
756 756 # Make sure the paste is safe.
757 757 self._keep_cursor_in_buffer()
758 758 cursor = self._control.textCursor()
759 759
760 760 # Remove any trailing newline, which confuses the GUI and forces the
761 761 # user to backspace.
762 762 text = QtGui.QApplication.clipboard().text(mode).rstrip()
763 763 self._insert_plain_text_into_buffer(cursor, dedent(text))
764 764
765 765 def print_(self, printer = None):
766 766 """ Print the contents of the ConsoleWidget to the specified QPrinter.
767 767 """
768 768 if (not printer):
769 769 printer = QtGui.QPrinter()
770 770 if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
771 771 return
772 772 self._control.print_(printer)
773 773
774 774 def prompt_to_top(self):
775 775 """ Moves the prompt to the top of the viewport.
776 776 """
777 777 if not self._executing:
778 778 prompt_cursor = self._get_prompt_cursor()
779 779 if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
780 780 self._set_cursor(prompt_cursor)
781 781 self._set_top_cursor(prompt_cursor)
782 782
783 783 def redo(self):
784 784 """ Redo the last operation. If there is no operation to redo, nothing
785 785 happens.
786 786 """
787 787 self._control.redo()
788 788
789 789 def reset_font(self):
790 790 """ Sets the font to the default fixed-width font for this platform.
791 791 """
792 792 if sys.platform == 'win32':
793 793 # Consolas ships with Vista/Win7, fallback to Courier if needed
794 794 fallback = 'Courier'
795 795 elif sys.platform == 'darwin':
796 796 # OSX always has Monaco
797 797 fallback = 'Monaco'
798 798 else:
799 799 # Monospace should always exist
800 800 fallback = 'Monospace'
801 801 font = get_font(self.font_family, fallback)
802 802 if self.font_size:
803 803 font.setPointSize(self.font_size)
804 804 else:
805 805 font.setPointSize(QtGui.qApp.font().pointSize())
806 806 font.setStyleHint(QtGui.QFont.TypeWriter)
807 807 self._set_font(font)
808 808
809 809 def change_font_size(self, delta):
810 810 """Change the font size by the specified amount (in points).
811 811 """
812 812 font = self.font
813 813 size = max(font.pointSize() + delta, 1) # minimum 1 point
814 814 font.setPointSize(size)
815 815 self._set_font(font)
816 816
817 817 def _increase_font_size(self):
818 818 self.change_font_size(1)
819 819
820 820 def _decrease_font_size(self):
821 821 self.change_font_size(-1)
822 822
823 823 def select_all(self):
824 824 """ Selects all the text in the buffer.
825 825 """
826 826 self._control.selectAll()
827 827
828 828 def _get_tab_width(self):
829 829 """ The width (in terms of space characters) for tab characters.
830 830 """
831 831 return self._tab_width
832 832
833 833 def _set_tab_width(self, tab_width):
834 834 """ Sets the width (in terms of space characters) for tab characters.
835 835 """
836 836 font_metrics = QtGui.QFontMetrics(self.font)
837 837 self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
838 838
839 839 self._tab_width = tab_width
840 840
841 841 tab_width = property(_get_tab_width, _set_tab_width)
842 842
843 843 def undo(self):
844 844 """ Undo the last operation. If there is no operation to undo, nothing
845 845 happens.
846 846 """
847 847 self._control.undo()
848 848
849 849 #---------------------------------------------------------------------------
850 850 # 'ConsoleWidget' abstract interface
851 851 #---------------------------------------------------------------------------
852 852
853 853 def _is_complete(self, source, interactive):
854 854 """ Returns whether 'source' can be executed. When triggered by an
855 855 Enter/Return key press, 'interactive' is True; otherwise, it is
856 856 False.
857 857 """
858 858 raise NotImplementedError
859 859
860 860 def _execute(self, source, hidden):
861 861 """ Execute 'source'. If 'hidden', do not show any output.
862 862 """
863 863 raise NotImplementedError
864 864
865 865 def _prompt_started_hook(self):
866 866 """ Called immediately after a new prompt is displayed.
867 867 """
868 868 pass
869 869
870 870 def _prompt_finished_hook(self):
871 871 """ Called immediately after a prompt is finished, i.e. when some input
872 872 will be processed and a new prompt displayed.
873 873 """
874 874 pass
875 875
876 876 def _up_pressed(self, shift_modifier):
877 877 """ Called when the up key is pressed. Returns whether to continue
878 878 processing the event.
879 879 """
880 880 return True
881 881
882 882 def _down_pressed(self, shift_modifier):
883 883 """ Called when the down key is pressed. Returns whether to continue
884 884 processing the event.
885 885 """
886 886 return True
887 887
888 888 def _tab_pressed(self):
889 889 """ Called when the tab key is pressed. Returns whether to continue
890 890 processing the event.
891 891 """
892 892 return False
893 893
894 894 #--------------------------------------------------------------------------
895 895 # 'ConsoleWidget' protected interface
896 896 #--------------------------------------------------------------------------
897 897
898 898 def _append_custom(self, insert, input, before_prompt=False, *args, **kwargs):
899 899 """ A low-level method for appending content to the end of the buffer.
900 900
901 901 If 'before_prompt' is enabled, the content will be inserted before the
902 902 current prompt, if there is one.
903 903 """
904 904 # Determine where to insert the content.
905 905 cursor = self._control.textCursor()
906 906 if before_prompt and (self._reading or not self._executing):
907 907 self._flush_pending_stream()
908 908 cursor.setPosition(self._append_before_prompt_pos)
909 909 else:
910 910 if insert != self._insert_plain_text:
911 911 self._flush_pending_stream()
912 912 cursor.movePosition(QtGui.QTextCursor.End)
913 913 start_pos = cursor.position()
914 914
915 915 # Perform the insertion.
916 916 result = insert(cursor, input, *args, **kwargs)
917 917
918 918 # Adjust the prompt position if we have inserted before it. This is safe
919 919 # because buffer truncation is disabled when not executing.
920 920 if before_prompt and not self._executing:
921 921 diff = cursor.position() - start_pos
922 922 self._append_before_prompt_pos += diff
923 923 self._prompt_pos += diff
924 924
925 925 return result
926 926
927 927 def _append_block(self, block_format=None, before_prompt=False):
928 928 """ Appends an new QTextBlock to the end of the console buffer.
929 929 """
930 930 self._append_custom(self._insert_block, block_format, before_prompt)
931 931
932 932 def _append_html(self, html, before_prompt=False):
933 933 """ Appends HTML at the end of the console buffer.
934 934 """
935 935 self._append_custom(self._insert_html, html, before_prompt)
936 936
937 937 def _append_html_fetching_plain_text(self, html, before_prompt=False):
938 938 """ Appends HTML, then returns the plain text version of it.
939 939 """
940 940 return self._append_custom(self._insert_html_fetching_plain_text,
941 941 html, before_prompt)
942 942
943 943 def _append_plain_text(self, text, before_prompt=False):
944 944 """ Appends plain text, processing ANSI codes if enabled.
945 945 """
946 946 self._append_custom(self._insert_plain_text, text, before_prompt)
947 947
948 948 def _cancel_completion(self):
949 949 """ If text completion is progress, cancel it.
950 950 """
951 951 self._completion_widget.cancel_completion()
952 952
953 953 def _clear_temporary_buffer(self):
954 954 """ Clears the "temporary text" buffer, i.e. all the text following
955 955 the prompt region.
956 956 """
957 957 # Select and remove all text below the input buffer.
958 958 cursor = self._get_prompt_cursor()
959 959 prompt = self._continuation_prompt.lstrip()
960 960 if(self._temp_buffer_filled):
961 961 self._temp_buffer_filled = False
962 962 while cursor.movePosition(QtGui.QTextCursor.NextBlock):
963 963 temp_cursor = QtGui.QTextCursor(cursor)
964 964 temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
965 965 text = temp_cursor.selection().toPlainText().lstrip()
966 966 if not text.startswith(prompt):
967 967 break
968 968 else:
969 969 # We've reached the end of the input buffer and no text follows.
970 970 return
971 971 cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
972 972 cursor.movePosition(QtGui.QTextCursor.End,
973 973 QtGui.QTextCursor.KeepAnchor)
974 974 cursor.removeSelectedText()
975 975
976 976 # After doing this, we have no choice but to clear the undo/redo
977 977 # history. Otherwise, the text is not "temporary" at all, because it
978 978 # can be recalled with undo/redo. Unfortunately, Qt does not expose
979 979 # fine-grained control to the undo/redo system.
980 980 if self._control.isUndoRedoEnabled():
981 981 self._control.setUndoRedoEnabled(False)
982 982 self._control.setUndoRedoEnabled(True)
983 983
984 984 def _complete_with_items(self, cursor, items):
985 985 """ Performs completion with 'items' at the specified cursor location.
986 986 """
987 987 self._cancel_completion()
988 988
989 989 if len(items) == 1:
990 990 cursor.setPosition(self._control.textCursor().position(),
991 991 QtGui.QTextCursor.KeepAnchor)
992 992 cursor.insertText(items[0])
993 993
994 994 elif len(items) > 1:
995 995 current_pos = self._control.textCursor().position()
996 996 prefix = commonprefix(items)
997 997 if prefix:
998 998 cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
999 999 cursor.insertText(prefix)
1000 1000 current_pos = cursor.position()
1001 1001
1002 1002 cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
1003 1003 self._completion_widget.show_items(cursor, items)
1004 1004
1005 1005
1006 1006 def _fill_temporary_buffer(self, cursor, text, html=False):
1007 1007 """fill the area below the active editting zone with text"""
1008 1008
1009 1009 current_pos = self._control.textCursor().position()
1010 1010
1011 1011 cursor.beginEditBlock()
1012 1012 self._append_plain_text('\n')
1013 1013 self._page(text, html=html)
1014 1014 cursor.endEditBlock()
1015 1015
1016 1016 cursor.setPosition(current_pos)
1017 1017 self._control.moveCursor(QtGui.QTextCursor.End)
1018 1018 self._control.setTextCursor(cursor)
1019 1019
1020 1020 self._temp_buffer_filled = True
1021 1021
1022 1022
1023 1023 def _context_menu_make(self, pos):
1024 1024 """ Creates a context menu for the given QPoint (in widget coordinates).
1025 1025 """
1026 1026 menu = QtGui.QMenu(self)
1027 1027
1028 1028 self.cut_action = menu.addAction('Cut', self.cut)
1029 1029 self.cut_action.setEnabled(self.can_cut())
1030 1030 self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
1031 1031
1032 1032 self.copy_action = menu.addAction('Copy', self.copy)
1033 1033 self.copy_action.setEnabled(self.can_copy())
1034 1034 self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
1035 1035
1036 1036 self.paste_action = menu.addAction('Paste', self.paste)
1037 1037 self.paste_action.setEnabled(self.can_paste())
1038 1038 self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
1039 1039
1040 1040 anchor = self._control.anchorAt(pos)
1041 1041 if anchor:
1042 1042 menu.addSeparator()
1043 1043 self.copy_link_action = menu.addAction(
1044 1044 'Copy Link Address', lambda: self.copy_anchor(anchor=anchor))
1045 1045 self.open_link_action = menu.addAction(
1046 1046 'Open Link', lambda: self.open_anchor(anchor=anchor))
1047 1047
1048 1048 menu.addSeparator()
1049 1049 menu.addAction(self.select_all_action)
1050 1050
1051 1051 menu.addSeparator()
1052 1052 menu.addAction(self.export_action)
1053 1053 menu.addAction(self.print_action)
1054 1054
1055 1055 return menu
1056 1056
1057 1057 def _control_key_down(self, modifiers, include_command=False):
1058 1058 """ Given a KeyboardModifiers flags object, return whether the Control
1059 1059 key is down.
1060 1060
1061 1061 Parameters:
1062 1062 -----------
1063 1063 include_command : bool, optional (default True)
1064 1064 Whether to treat the Command key as a (mutually exclusive) synonym
1065 1065 for Control when in Mac OS.
1066 1066 """
1067 1067 # Note that on Mac OS, ControlModifier corresponds to the Command key
1068 1068 # while MetaModifier corresponds to the Control key.
1069 1069 if sys.platform == 'darwin':
1070 1070 down = include_command and (modifiers & QtCore.Qt.ControlModifier)
1071 1071 return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
1072 1072 else:
1073 1073 return bool(modifiers & QtCore.Qt.ControlModifier)
1074 1074
1075 1075 def _create_control(self):
1076 1076 """ Creates and connects the underlying text widget.
1077 1077 """
1078 1078 # Create the underlying control.
1079 1079 if self.custom_control:
1080 1080 control = self.custom_control()
1081 1081 elif self.kind == 'plain':
1082 1082 control = QtGui.QPlainTextEdit()
1083 1083 elif self.kind == 'rich':
1084 1084 control = QtGui.QTextEdit()
1085 1085 control.setAcceptRichText(False)
1086 1086 control.setMouseTracking(True)
1087 1087
1088 1088 # Prevent the widget from handling drops, as we already provide
1089 1089 # the logic in this class.
1090 1090 control.setAcceptDrops(False)
1091 1091
1092 1092 # Install event filters. The filter on the viewport is needed for
1093 1093 # mouse events.
1094 1094 control.installEventFilter(self)
1095 1095 control.viewport().installEventFilter(self)
1096 1096
1097 1097 # Connect signals.
1098 1098 control.customContextMenuRequested.connect(
1099 1099 self._custom_context_menu_requested)
1100 1100 control.copyAvailable.connect(self.copy_available)
1101 1101 control.redoAvailable.connect(self.redo_available)
1102 1102 control.undoAvailable.connect(self.undo_available)
1103 1103
1104 1104 # Hijack the document size change signal to prevent Qt from adjusting
1105 1105 # the viewport's scrollbar. We are relying on an implementation detail
1106 1106 # of Q(Plain)TextEdit here, which is potentially dangerous, but without
1107 1107 # this functionality we cannot create a nice terminal interface.
1108 1108 layout = control.document().documentLayout()
1109 1109 layout.documentSizeChanged.disconnect()
1110 1110 layout.documentSizeChanged.connect(self._adjust_scrollbars)
1111 1111
1112 1112 # Configure the control.
1113 1113 control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
1114 1114 control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
1115 1115 control.setReadOnly(True)
1116 1116 control.setUndoRedoEnabled(False)
1117 1117 control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
1118 1118 return control
1119 1119
1120 1120 def _create_page_control(self):
1121 1121 """ Creates and connects the underlying paging widget.
1122 1122 """
1123 1123 if self.custom_page_control:
1124 1124 control = self.custom_page_control()
1125 1125 elif self.kind == 'plain':
1126 1126 control = QtGui.QPlainTextEdit()
1127 1127 elif self.kind == 'rich':
1128 1128 control = QtGui.QTextEdit()
1129 1129 control.installEventFilter(self)
1130 1130 viewport = control.viewport()
1131 1131 viewport.installEventFilter(self)
1132 1132 control.setReadOnly(True)
1133 1133 control.setUndoRedoEnabled(False)
1134 1134 control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
1135 1135 return control
1136 1136
1137 1137 def _event_filter_console_keypress(self, event):
1138 1138 """ Filter key events for the underlying text widget to create a
1139 1139 console-like interface.
1140 1140 """
1141 1141 intercepted = False
1142 1142 cursor = self._control.textCursor()
1143 1143 position = cursor.position()
1144 1144 key = event.key()
1145 1145 ctrl_down = self._control_key_down(event.modifiers())
1146 1146 alt_down = event.modifiers() & QtCore.Qt.AltModifier
1147 1147 shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
1148 1148
1149 1149 #------ Special sequences ----------------------------------------------
1150 1150
1151 1151 if event.matches(QtGui.QKeySequence.Copy):
1152 1152 self.copy()
1153 1153 intercepted = True
1154 1154
1155 1155 elif event.matches(QtGui.QKeySequence.Cut):
1156 1156 self.cut()
1157 1157 intercepted = True
1158 1158
1159 1159 elif event.matches(QtGui.QKeySequence.Paste):
1160 1160 self.paste()
1161 1161 intercepted = True
1162 1162
1163 1163 #------ Special modifier logic -----------------------------------------
1164 1164
1165 1165 elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
1166 1166 intercepted = True
1167 1167
1168 1168 # Special handling when tab completing in text mode.
1169 1169 self._cancel_completion()
1170 1170
1171 1171 if self._in_buffer(position):
1172 1172 # Special handling when a reading a line of raw input.
1173 1173 if self._reading:
1174 1174 self._append_plain_text('\n')
1175 1175 self._reading = False
1176 1176 if self._reading_callback:
1177 1177 self._reading_callback()
1178 1178
1179 1179 # If the input buffer is a single line or there is only
1180 1180 # whitespace after the cursor, execute. Otherwise, split the
1181 1181 # line with a continuation prompt.
1182 1182 elif not self._executing:
1183 1183 cursor.movePosition(QtGui.QTextCursor.End,
1184 1184 QtGui.QTextCursor.KeepAnchor)
1185 1185 at_end = len(cursor.selectedText().strip()) == 0
1186 1186 single_line = (self._get_end_cursor().blockNumber() ==
1187 1187 self._get_prompt_cursor().blockNumber())
1188 1188 if (at_end or shift_down or single_line) and not ctrl_down:
1189 1189 self.execute(interactive = not shift_down)
1190 1190 else:
1191 1191 # Do this inside an edit block for clean undo/redo.
1192 1192 cursor.beginEditBlock()
1193 1193 cursor.setPosition(position)
1194 1194 cursor.insertText('\n')
1195 1195 self._insert_continuation_prompt(cursor)
1196 1196 cursor.endEditBlock()
1197 1197
1198 1198 # Ensure that the whole input buffer is visible.
1199 1199 # FIXME: This will not be usable if the input buffer is
1200 1200 # taller than the console widget.
1201 1201 self._control.moveCursor(QtGui.QTextCursor.End)
1202 1202 self._control.setTextCursor(cursor)
1203 1203
1204 1204 #------ Control/Cmd modifier -------------------------------------------
1205 1205
1206 1206 elif ctrl_down:
1207 1207 if key == QtCore.Qt.Key_G:
1208 1208 self._keyboard_quit()
1209 1209 intercepted = True
1210 1210
1211 1211 elif key == QtCore.Qt.Key_K:
1212 1212 if self._in_buffer(position):
1213 1213 cursor.clearSelection()
1214 1214 cursor.movePosition(QtGui.QTextCursor.EndOfLine,
1215 1215 QtGui.QTextCursor.KeepAnchor)
1216 1216 if not cursor.hasSelection():
1217 1217 # Line deletion (remove continuation prompt)
1218 1218 cursor.movePosition(QtGui.QTextCursor.NextBlock,
1219 1219 QtGui.QTextCursor.KeepAnchor)
1220 1220 cursor.movePosition(QtGui.QTextCursor.Right,
1221 1221 QtGui.QTextCursor.KeepAnchor,
1222 1222 len(self._continuation_prompt))
1223 1223 self._kill_ring.kill_cursor(cursor)
1224 1224 self._set_cursor(cursor)
1225 1225 intercepted = True
1226 1226
1227 1227 elif key == QtCore.Qt.Key_L:
1228 1228 self.prompt_to_top()
1229 1229 intercepted = True
1230 1230
1231 1231 elif key == QtCore.Qt.Key_O:
1232 1232 if self._page_control and self._page_control.isVisible():
1233 1233 self._page_control.setFocus()
1234 1234 intercepted = True
1235 1235
1236 1236 elif key == QtCore.Qt.Key_U:
1237 1237 if self._in_buffer(position):
1238 1238 cursor.clearSelection()
1239 1239 start_line = cursor.blockNumber()
1240 1240 if start_line == self._get_prompt_cursor().blockNumber():
1241 1241 offset = len(self._prompt)
1242 1242 else:
1243 1243 offset = len(self._continuation_prompt)
1244 1244 cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
1245 1245 QtGui.QTextCursor.KeepAnchor)
1246 1246 cursor.movePosition(QtGui.QTextCursor.Right,
1247 1247 QtGui.QTextCursor.KeepAnchor, offset)
1248 1248 self._kill_ring.kill_cursor(cursor)
1249 1249 self._set_cursor(cursor)
1250 1250 intercepted = True
1251 1251
1252 1252 elif key == QtCore.Qt.Key_Y:
1253 1253 self._keep_cursor_in_buffer()
1254 1254 self._kill_ring.yank()
1255 1255 intercepted = True
1256 1256
1257 1257 elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
1258 1258 if key == QtCore.Qt.Key_Backspace:
1259 1259 cursor = self._get_word_start_cursor(position)
1260 1260 else: # key == QtCore.Qt.Key_Delete
1261 1261 cursor = self._get_word_end_cursor(position)
1262 1262 cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
1263 1263 self._kill_ring.kill_cursor(cursor)
1264 1264 intercepted = True
1265 1265
1266 1266 elif key == QtCore.Qt.Key_D:
1267 1267 if len(self.input_buffer) == 0:
1268 1268 self.exit_requested.emit(self)
1269 1269 else:
1270 1270 new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
1271 1271 QtCore.Qt.Key_Delete,
1272 1272 QtCore.Qt.NoModifier)
1273 1273 QtGui.qApp.sendEvent(self._control, new_event)
1274 1274 intercepted = True
1275 1275
1276 1276 #------ Alt modifier ---------------------------------------------------
1277 1277
1278 1278 elif alt_down:
1279 1279 if key == QtCore.Qt.Key_B:
1280 1280 self._set_cursor(self._get_word_start_cursor(position))
1281 1281 intercepted = True
1282 1282
1283 1283 elif key == QtCore.Qt.Key_F:
1284 1284 self._set_cursor(self._get_word_end_cursor(position))
1285 1285 intercepted = True
1286 1286
1287 1287 elif key == QtCore.Qt.Key_Y:
1288 1288 self._kill_ring.rotate()
1289 1289 intercepted = True
1290 1290
1291 1291 elif key == QtCore.Qt.Key_Backspace:
1292 1292 cursor = self._get_word_start_cursor(position)
1293 1293 cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
1294 1294 self._kill_ring.kill_cursor(cursor)
1295 1295 intercepted = True
1296 1296
1297 1297 elif key == QtCore.Qt.Key_D:
1298 1298 cursor = self._get_word_end_cursor(position)
1299 1299 cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
1300 1300 self._kill_ring.kill_cursor(cursor)
1301 1301 intercepted = True
1302 1302
1303 1303 elif key == QtCore.Qt.Key_Delete:
1304 1304 intercepted = True
1305 1305
1306 1306 elif key == QtCore.Qt.Key_Greater:
1307 1307 self._control.moveCursor(QtGui.QTextCursor.End)
1308 1308 intercepted = True
1309 1309
1310 1310 elif key == QtCore.Qt.Key_Less:
1311 1311 self._control.setTextCursor(self._get_prompt_cursor())
1312 1312 intercepted = True
1313 1313
1314 1314 #------ No modifiers ---------------------------------------------------
1315 1315
1316 1316 else:
1317 1317 if shift_down:
1318 1318 anchormode = QtGui.QTextCursor.KeepAnchor
1319 1319 else:
1320 1320 anchormode = QtGui.QTextCursor.MoveAnchor
1321 1321
1322 1322 if key == QtCore.Qt.Key_Escape:
1323 1323 self._keyboard_quit()
1324 1324 intercepted = True
1325 1325
1326 1326 elif key == QtCore.Qt.Key_Up:
1327 1327 if self._reading or not self._up_pressed(shift_down):
1328 1328 intercepted = True
1329 1329 else:
1330 1330 prompt_line = self._get_prompt_cursor().blockNumber()
1331 1331 intercepted = cursor.blockNumber() <= prompt_line
1332 1332
1333 1333 elif key == QtCore.Qt.Key_Down:
1334 1334 if self._reading or not self._down_pressed(shift_down):
1335 1335 intercepted = True
1336 1336 else:
1337 1337 end_line = self._get_end_cursor().blockNumber()
1338 1338 intercepted = cursor.blockNumber() == end_line
1339 1339
1340 1340 elif key == QtCore.Qt.Key_Tab:
1341 1341 if not self._reading:
1342 1342 if self._tab_pressed():
1343 1343 # real tab-key, insert four spaces
1344 1344 cursor.insertText(' '*4)
1345 1345 intercepted = True
1346 1346
1347 1347 elif key == QtCore.Qt.Key_Left:
1348 1348
1349 1349 # Move to the previous line
1350 1350 line, col = cursor.blockNumber(), cursor.columnNumber()
1351 1351 if line > self._get_prompt_cursor().blockNumber() and \
1352 1352 col == len(self._continuation_prompt):
1353 1353 self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
1354 1354 mode=anchormode)
1355 1355 self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
1356 1356 mode=anchormode)
1357 1357 intercepted = True
1358 1358
1359 1359 # Regular left movement
1360 1360 else:
1361 1361 intercepted = not self._in_buffer(position - 1)
1362 1362
1363 1363 elif key == QtCore.Qt.Key_Right:
1364 1364 original_block_number = cursor.blockNumber()
1365 1365 cursor.movePosition(QtGui.QTextCursor.Right,
1366 1366 mode=anchormode)
1367 1367 if cursor.blockNumber() != original_block_number:
1368 1368 cursor.movePosition(QtGui.QTextCursor.Right,
1369 1369 n=len(self._continuation_prompt),
1370 1370 mode=anchormode)
1371 1371 self._set_cursor(cursor)
1372 1372 intercepted = True
1373 1373
1374 1374 elif key == QtCore.Qt.Key_Home:
1375 1375 start_line = cursor.blockNumber()
1376 1376 if start_line == self._get_prompt_cursor().blockNumber():
1377 1377 start_pos = self._prompt_pos
1378 1378 else:
1379 1379 cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
1380 1380 QtGui.QTextCursor.KeepAnchor)
1381 1381 start_pos = cursor.position()
1382 1382 start_pos += len(self._continuation_prompt)
1383 1383 cursor.setPosition(position)
1384 1384 if shift_down and self._in_buffer(position):
1385 1385 cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
1386 1386 else:
1387 1387 cursor.setPosition(start_pos)
1388 1388 self._set_cursor(cursor)
1389 1389 intercepted = True
1390 1390
1391 1391 elif key == QtCore.Qt.Key_Backspace:
1392 1392
1393 1393 # Line deletion (remove continuation prompt)
1394 1394 line, col = cursor.blockNumber(), cursor.columnNumber()
1395 1395 if not self._reading and \
1396 1396 col == len(self._continuation_prompt) and \
1397 1397 line > self._get_prompt_cursor().blockNumber():
1398 1398 cursor.beginEditBlock()
1399 1399 cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
1400 1400 QtGui.QTextCursor.KeepAnchor)
1401 1401 cursor.removeSelectedText()
1402 1402 cursor.deletePreviousChar()
1403 1403 cursor.endEditBlock()
1404 1404 intercepted = True
1405 1405
1406 1406 # Regular backwards deletion
1407 1407 else:
1408 1408 anchor = cursor.anchor()
1409 1409 if anchor == position:
1410 1410 intercepted = not self._in_buffer(position - 1)
1411 1411 else:
1412 1412 intercepted = not self._in_buffer(min(anchor, position))
1413 1413
1414 1414 elif key == QtCore.Qt.Key_Delete:
1415 1415
1416 1416 # Line deletion (remove continuation prompt)
1417 1417 if not self._reading and self._in_buffer(position) and \
1418 1418 cursor.atBlockEnd() and not cursor.hasSelection():
1419 1419 cursor.movePosition(QtGui.QTextCursor.NextBlock,
1420 1420 QtGui.QTextCursor.KeepAnchor)
1421 1421 cursor.movePosition(QtGui.QTextCursor.Right,
1422 1422 QtGui.QTextCursor.KeepAnchor,
1423 1423 len(self._continuation_prompt))
1424 1424 cursor.removeSelectedText()
1425 1425 intercepted = True
1426 1426
1427 1427 # Regular forwards deletion:
1428 1428 else:
1429 1429 anchor = cursor.anchor()
1430 1430 intercepted = (not self._in_buffer(anchor) or
1431 1431 not self._in_buffer(position))
1432 1432
1433 1433 # Don't move the cursor if Control/Cmd is pressed to allow copy-paste
1434 1434 # using the keyboard in any part of the buffer. Also, permit scrolling
1435 1435 # with Page Up/Down keys. Finally, if we're executing, don't move the
1436 1436 # cursor (if even this made sense, we can't guarantee that the prompt
1437 1437 # position is still valid due to text truncation).
1438 1438 if not (self._control_key_down(event.modifiers(), include_command=True)
1439 1439 or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
1440 1440 or (self._executing and not self._reading)):
1441 1441 self._keep_cursor_in_buffer()
1442 1442
1443 1443 return intercepted
1444 1444
1445 1445 def _event_filter_page_keypress(self, event):
1446 1446 """ Filter key events for the paging widget to create console-like
1447 1447 interface.
1448 1448 """
1449 1449 key = event.key()
1450 1450 ctrl_down = self._control_key_down(event.modifiers())
1451 1451 alt_down = event.modifiers() & QtCore.Qt.AltModifier
1452 1452
1453 1453 if ctrl_down:
1454 1454 if key == QtCore.Qt.Key_O:
1455 1455 self._control.setFocus()
1456 1456 intercept = True
1457 1457
1458 1458 elif alt_down:
1459 1459 if key == QtCore.Qt.Key_Greater:
1460 1460 self._page_control.moveCursor(QtGui.QTextCursor.End)
1461 1461 intercepted = True
1462 1462
1463 1463 elif key == QtCore.Qt.Key_Less:
1464 1464 self._page_control.moveCursor(QtGui.QTextCursor.Start)
1465 1465 intercepted = True
1466 1466
1467 1467 elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
1468 1468 if self._splitter:
1469 1469 self._page_control.hide()
1470 1470 self._control.setFocus()
1471 1471 else:
1472 1472 self.layout().setCurrentWidget(self._control)
1473 1473 return True
1474 1474
1475 1475 elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
1476 1476 QtCore.Qt.Key_Tab):
1477 1477 new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
1478 1478 QtCore.Qt.Key_PageDown,
1479 1479 QtCore.Qt.NoModifier)
1480 1480 QtGui.qApp.sendEvent(self._page_control, new_event)
1481 1481 return True
1482 1482
1483 1483 elif key == QtCore.Qt.Key_Backspace:
1484 1484 new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
1485 1485 QtCore.Qt.Key_PageUp,
1486 1486 QtCore.Qt.NoModifier)
1487 1487 QtGui.qApp.sendEvent(self._page_control, new_event)
1488 1488 return True
1489 1489
1490 1490 return False
1491 1491
1492 1492 def _flush_pending_stream(self):
1493 1493 """ Flush out pending text into the widget. """
1494 1494 text = self._pending_insert_text
1495 1495 self._pending_insert_text = []
1496 1496 buffer_size = self._control.document().maximumBlockCount()
1497 1497 if buffer_size > 0:
1498 1498 text = self._get_last_lines_from_list(text, buffer_size)
1499 1499 text = ''.join(text)
1500 1500 t = time.time()
1501 1501 self._insert_plain_text(self._get_end_cursor(), text, flush=True)
1502 1502 # Set the flush interval to equal the maximum time to update text.
1503 1503 self._pending_text_flush_interval.setInterval(max(100,
1504 1504 (time.time()-t)*1000))
1505 1505
1506 1506 def _format_as_columns(self, items, separator=' '):
1507 1507 """ Transform a list of strings into a single string with columns.
1508 1508
1509 1509 Parameters
1510 1510 ----------
1511 1511 items : sequence of strings
1512 1512 The strings to process.
1513 1513
1514 1514 separator : str, optional [default is two spaces]
1515 1515 The string that separates columns.
1516 1516
1517 1517 Returns
1518 1518 -------
1519 1519 The formatted string.
1520 1520 """
1521 1521 # Calculate the number of characters available.
1522 1522 width = self._control.viewport().width()
1523 1523 char_width = QtGui.QFontMetrics(self.font).width(' ')
1524 1524 displaywidth = max(10, (width / char_width) - 1)
1525 1525
1526 1526 return columnize(items, separator, displaywidth)
1527 1527
1528 1528 def _get_block_plain_text(self, block):
1529 1529 """ Given a QTextBlock, return its unformatted text.
1530 1530 """
1531 1531 cursor = QtGui.QTextCursor(block)
1532 1532 cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
1533 1533 cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
1534 1534 QtGui.QTextCursor.KeepAnchor)
1535 1535 return cursor.selection().toPlainText()
1536 1536
1537 1537 def _get_cursor(self):
1538 1538 """ Convenience method that returns a cursor for the current position.
1539 1539 """
1540 1540 return self._control.textCursor()
1541 1541
1542 1542 def _get_end_cursor(self):
1543 1543 """ Convenience method that returns a cursor for the last character.
1544 1544 """
1545 1545 cursor = self._control.textCursor()
1546 1546 cursor.movePosition(QtGui.QTextCursor.End)
1547 1547 return cursor
1548 1548
1549 1549 def _get_input_buffer_cursor_column(self):
1550 1550 """ Returns the column of the cursor in the input buffer, excluding the
1551 1551 contribution by the prompt, or -1 if there is no such column.
1552 1552 """
1553 1553 prompt = self._get_input_buffer_cursor_prompt()
1554 1554 if prompt is None:
1555 1555 return -1
1556 1556 else:
1557 1557 cursor = self._control.textCursor()
1558 1558 return cursor.columnNumber() - len(prompt)
1559 1559
1560 1560 def _get_input_buffer_cursor_line(self):
1561 1561 """ Returns the text of the line of the input buffer that contains the
1562 1562 cursor, or None if there is no such line.
1563 1563 """
1564 1564 prompt = self._get_input_buffer_cursor_prompt()
1565 1565 if prompt is None:
1566 1566 return None
1567 1567 else:
1568 1568 cursor = self._control.textCursor()
1569 1569 text = self._get_block_plain_text(cursor.block())
1570 1570 return text[len(prompt):]
1571 1571
1572 1572 def _get_input_buffer_cursor_prompt(self):
1573 1573 """ Returns the (plain text) prompt for line of the input buffer that
1574 1574 contains the cursor, or None if there is no such line.
1575 1575 """
1576 1576 if self._executing:
1577 1577 return None
1578 1578 cursor = self._control.textCursor()
1579 1579 if cursor.position() >= self._prompt_pos:
1580 1580 if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
1581 1581 return self._prompt
1582 1582 else:
1583 1583 return self._continuation_prompt
1584 1584 else:
1585 1585 return None
1586 1586
1587 1587 def _get_last_lines(self, text, num_lines, return_count=False):
1588 1588 """ Return last specified number of lines of text (like `tail -n`).
1589 1589 If return_count is True, returns a tuple of clipped text and the
1590 1590 number of lines in the clipped text.
1591 1591 """
1592 1592 pos = len(text)
1593 1593 if pos < num_lines:
1594 1594 if return_count:
1595 1595 return text, text.count('\n') if return_count else text
1596 1596 else:
1597 1597 return text
1598 1598 i = 0
1599 1599 while i < num_lines:
1600 1600 pos = text.rfind('\n', None, pos)
1601 1601 if pos == -1:
1602 1602 pos = None
1603 1603 break
1604 1604 i += 1
1605 1605 if return_count:
1606 1606 return text[pos:], i
1607 1607 else:
1608 1608 return text[pos:]
1609 1609
1610 1610 def _get_last_lines_from_list(self, text_list, num_lines):
1611 1611 """ Return the list of text clipped to last specified lines.
1612 1612 """
1613 1613 ret = []
1614 1614 lines_pending = num_lines
1615 1615 for text in reversed(text_list):
1616 1616 text, lines_added = self._get_last_lines(text, lines_pending,
1617 1617 return_count=True)
1618 1618 ret.append(text)
1619 1619 lines_pending -= lines_added
1620 1620 if lines_pending <= 0:
1621 1621 break
1622 1622 return ret[::-1]
1623 1623
1624 1624 def _get_prompt_cursor(self):
1625 1625 """ Convenience method that returns a cursor for the prompt position.
1626 1626 """
1627 1627 cursor = self._control.textCursor()
1628 1628 cursor.setPosition(self._prompt_pos)
1629 1629 return cursor
1630 1630
1631 1631 def _get_selection_cursor(self, start, end):
1632 1632 """ Convenience method that returns a cursor with text selected between
1633 1633 the positions 'start' and 'end'.
1634 1634 """
1635 1635 cursor = self._control.textCursor()
1636 1636 cursor.setPosition(start)
1637 1637 cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
1638 1638 return cursor
1639 1639
1640 1640 def _get_word_start_cursor(self, position):
1641 1641 """ Find the start of the word to the left the given position. If a
1642 1642 sequence of non-word characters precedes the first word, skip over
1643 1643 them. (This emulates the behavior of bash, emacs, etc.)
1644 1644 """
1645 1645 document = self._control.document()
1646 1646 position -= 1
1647 1647 while position >= self._prompt_pos and \
1648 1648 not is_letter_or_number(document.characterAt(position)):
1649 1649 position -= 1
1650 1650 while position >= self._prompt_pos and \
1651 1651 is_letter_or_number(document.characterAt(position)):
1652 1652 position -= 1
1653 1653 cursor = self._control.textCursor()
1654 1654 cursor.setPosition(position + 1)
1655 1655 return cursor
1656 1656
1657 1657 def _get_word_end_cursor(self, position):
1658 1658 """ Find the end of the word to the right the given position. If a
1659 1659 sequence of non-word characters precedes the first word, skip over
1660 1660 them. (This emulates the behavior of bash, emacs, etc.)
1661 1661 """
1662 1662 document = self._control.document()
1663 1663 end = self._get_end_cursor().position()
1664 1664 while position < end and \
1665 1665 not is_letter_or_number(document.characterAt(position)):
1666 1666 position += 1
1667 1667 while position < end and \
1668 1668 is_letter_or_number(document.characterAt(position)):
1669 1669 position += 1
1670 1670 cursor = self._control.textCursor()
1671 1671 cursor.setPosition(position)
1672 1672 return cursor
1673 1673
1674 1674 def _insert_continuation_prompt(self, cursor):
1675 1675 """ Inserts new continuation prompt using the specified cursor.
1676 1676 """
1677 1677 if self._continuation_prompt_html is None:
1678 1678 self._insert_plain_text(cursor, self._continuation_prompt)
1679 1679 else:
1680 1680 self._continuation_prompt = self._insert_html_fetching_plain_text(
1681 1681 cursor, self._continuation_prompt_html)
1682 1682
1683 1683 def _insert_block(self, cursor, block_format=None):
1684 1684 """ Inserts an empty QTextBlock using the specified cursor.
1685 1685 """
1686 1686 if block_format is None:
1687 1687 block_format = QtGui.QTextBlockFormat()
1688 1688 cursor.insertBlock(block_format)
1689 1689
1690 1690 def _insert_html(self, cursor, html):
1691 1691 """ Inserts HTML using the specified cursor in such a way that future
1692 1692 formatting is unaffected.
1693 1693 """
1694 1694 cursor.beginEditBlock()
1695 1695 cursor.insertHtml(html)
1696 1696
1697 1697 # After inserting HTML, the text document "remembers" it's in "html
1698 1698 # mode", which means that subsequent calls adding plain text will result
1699 1699 # in unwanted formatting, lost tab characters, etc. The following code
1700 1700 # hacks around this behavior, which I consider to be a bug in Qt, by
1701 1701 # (crudely) resetting the document's style state.
1702 1702 cursor.movePosition(QtGui.QTextCursor.Left,
1703 1703 QtGui.QTextCursor.KeepAnchor)
1704 1704 if cursor.selection().toPlainText() == ' ':
1705 1705 cursor.removeSelectedText()
1706 1706 else:
1707 1707 cursor.movePosition(QtGui.QTextCursor.Right)
1708 1708 cursor.insertText(' ', QtGui.QTextCharFormat())
1709 1709 cursor.endEditBlock()
1710 1710
1711 1711 def _insert_html_fetching_plain_text(self, cursor, html):
1712 1712 """ Inserts HTML using the specified cursor, then returns its plain text
1713 1713 version.
1714 1714 """
1715 1715 cursor.beginEditBlock()
1716 1716 cursor.removeSelectedText()
1717 1717
1718 1718 start = cursor.position()
1719 1719 self._insert_html(cursor, html)
1720 1720 end = cursor.position()
1721 1721 cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
1722 1722 text = cursor.selection().toPlainText()
1723 1723
1724 1724 cursor.setPosition(end)
1725 1725 cursor.endEditBlock()
1726 1726 return text
1727 1727
1728 1728 def _insert_plain_text(self, cursor, text, flush=False):
1729 1729 """ Inserts plain text using the specified cursor, processing ANSI codes
1730 1730 if enabled.
1731 1731 """
1732 1732 # maximumBlockCount() can be different from self.buffer_size in
1733 1733 # case input prompt is active.
1734 1734 buffer_size = self._control.document().maximumBlockCount()
1735 1735
1736 1736 if self._executing and not flush and \
1737 1737 self._pending_text_flush_interval.isActive():
1738 1738 self._pending_insert_text.append(text)
1739 1739 if buffer_size > 0:
1740 1740 self._pending_insert_text = self._get_last_lines_from_list(
1741 1741 self._pending_insert_text, buffer_size)
1742 1742 return
1743 1743
1744 1744 if self._executing and not self._pending_text_flush_interval.isActive():
1745 1745 self._pending_text_flush_interval.start()
1746 1746
1747 1747 # Clip the text to last `buffer_size` lines.
1748 1748 if buffer_size > 0:
1749 1749 text = self._get_last_lines(text, buffer_size)
1750 1750
1751 1751 cursor.beginEditBlock()
1752 1752 if self.ansi_codes:
1753 1753 for substring in self._ansi_processor.split_string(text):
1754 1754 for act in self._ansi_processor.actions:
1755 1755
1756 1756 # Unlike real terminal emulators, we don't distinguish
1757 1757 # between the screen and the scrollback buffer. A screen
1758 1758 # erase request clears everything.
1759 1759 if act.action == 'erase' and act.area == 'screen':
1760 1760 cursor.select(QtGui.QTextCursor.Document)
1761 1761 cursor.removeSelectedText()
1762 1762
1763 1763 # Simulate a form feed by scrolling just past the last line.
1764 1764 elif act.action == 'scroll' and act.unit == 'page':
1765 1765 cursor.insertText('\n')
1766 1766 cursor.endEditBlock()
1767 1767 self._set_top_cursor(cursor)
1768 1768 cursor.joinPreviousEditBlock()
1769 1769 cursor.deletePreviousChar()
1770 1770
1771 1771 elif act.action == 'carriage-return':
1772 1772 cursor.movePosition(
1773 1773 cursor.StartOfLine, cursor.KeepAnchor)
1774 1774
1775 1775 elif act.action == 'beep':
1776 1776 QtGui.qApp.beep()
1777 1777
1778 1778 elif act.action == 'backspace':
1779 1779 if not cursor.atBlockStart():
1780 1780 cursor.movePosition(
1781 1781 cursor.PreviousCharacter, cursor.KeepAnchor)
1782 1782
1783 1783 elif act.action == 'newline':
1784 1784 cursor.movePosition(cursor.EndOfLine)
1785 1785
1786 1786 format = self._ansi_processor.get_format()
1787 1787
1788 1788 selection = cursor.selectedText()
1789 1789 if len(selection) == 0:
1790 1790 cursor.insertText(substring, format)
1791 1791 elif substring is not None:
1792 1792 # BS and CR are treated as a change in print
1793 1793 # position, rather than a backwards character
1794 1794 # deletion for output equivalence with (I)Python
1795 1795 # terminal.
1796 1796 if len(substring) >= len(selection):
1797 1797 cursor.insertText(substring, format)
1798 1798 else:
1799 1799 old_text = selection[len(substring):]
1800 1800 cursor.insertText(substring + old_text, format)
1801 1801 cursor.movePosition(cursor.PreviousCharacter,
1802 1802 cursor.KeepAnchor, len(old_text))
1803 1803 else:
1804 1804 cursor.insertText(text)
1805 1805 cursor.endEditBlock()
1806 1806
1807 1807 def _insert_plain_text_into_buffer(self, cursor, text):
1808 1808 """ Inserts text into the input buffer using the specified cursor (which
1809 1809 must be in the input buffer), ensuring that continuation prompts are
1810 1810 inserted as necessary.
1811 1811 """
1812 1812 lines = text.splitlines(True)
1813 1813 if lines:
1814 1814 cursor.beginEditBlock()
1815 1815 cursor.insertText(lines[0])
1816 1816 for line in lines[1:]:
1817 1817 if self._continuation_prompt_html is None:
1818 1818 cursor.insertText(self._continuation_prompt)
1819 1819 else:
1820 1820 self._continuation_prompt = \
1821 1821 self._insert_html_fetching_plain_text(
1822 1822 cursor, self._continuation_prompt_html)
1823 1823 cursor.insertText(line)
1824 1824 cursor.endEditBlock()
1825 1825
1826 1826 def _in_buffer(self, position=None):
1827 1827 """ Returns whether the current cursor (or, if specified, a position) is
1828 1828 inside the editing region.
1829 1829 """
1830 1830 cursor = self._control.textCursor()
1831 1831 if position is None:
1832 1832 position = cursor.position()
1833 1833 else:
1834 1834 cursor.setPosition(position)
1835 1835 line = cursor.blockNumber()
1836 1836 prompt_line = self._get_prompt_cursor().blockNumber()
1837 1837 if line == prompt_line:
1838 1838 return position >= self._prompt_pos
1839 1839 elif line > prompt_line:
1840 1840 cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
1841 1841 prompt_pos = cursor.position() + len(self._continuation_prompt)
1842 1842 return position >= prompt_pos
1843 1843 return False
1844 1844
1845 1845 def _keep_cursor_in_buffer(self):
1846 1846 """ Ensures that the cursor is inside the editing region. Returns
1847 1847 whether the cursor was moved.
1848 1848 """
1849 1849 moved = not self._in_buffer()
1850 1850 if moved:
1851 1851 cursor = self._control.textCursor()
1852 1852 cursor.movePosition(QtGui.QTextCursor.End)
1853 1853 self._control.setTextCursor(cursor)
1854 1854 return moved
1855 1855
1856 1856 def _keyboard_quit(self):
1857 1857 """ Cancels the current editing task ala Ctrl-G in Emacs.
1858 1858 """
1859 1859 if self._temp_buffer_filled :
1860 1860 self._cancel_completion()
1861 1861 self._clear_temporary_buffer()
1862 1862 else:
1863 1863 self.input_buffer = ''
1864 1864
1865 1865 def _page(self, text, html=False):
1866 1866 """ Displays text using the pager if it exceeds the height of the
1867 1867 viewport.
1868 1868
1869 1869 Parameters:
1870 1870 -----------
1871 1871 html : bool, optional (default False)
1872 1872 If set, the text will be interpreted as HTML instead of plain text.
1873 1873 """
1874 1874 line_height = QtGui.QFontMetrics(self.font).height()
1875 1875 minlines = self._control.viewport().height() / line_height
1876 1876 if self.paging != 'none' and \
1877 1877 re.match("(?:[^\n]*\n){%i}" % minlines, text):
1878 1878 if self.paging == 'custom':
1879 1879 self.custom_page_requested.emit(text)
1880 1880 else:
1881 1881 self._page_control.clear()
1882 1882 cursor = self._page_control.textCursor()
1883 1883 if html:
1884 1884 self._insert_html(cursor, text)
1885 1885 else:
1886 1886 self._insert_plain_text(cursor, text)
1887 1887 self._page_control.moveCursor(QtGui.QTextCursor.Start)
1888 1888
1889 1889 self._page_control.viewport().resize(self._control.size())
1890 1890 if self._splitter:
1891 1891 self._page_control.show()
1892 1892 self._page_control.setFocus()
1893 1893 else:
1894 1894 self.layout().setCurrentWidget(self._page_control)
1895 1895 elif html:
1896 1896 self._append_html(text)
1897 1897 else:
1898 1898 self._append_plain_text(text)
1899 1899
1900 1900 def _set_paging(self, paging):
1901 1901 """
1902 1902 Change the pager to `paging` style.
1903 1903
1904 1904 XXX: currently, this is limited to switching between 'hsplit' and
1905 1905 'vsplit'.
1906 1906
1907 1907 Parameters:
1908 1908 -----------
1909 1909 paging : string
1910 1910 Either "hsplit", "vsplit", or "inside"
1911 1911 """
1912 1912 if self._splitter is None:
1913 1913 raise NotImplementedError("""can only switch if --paging=hsplit or
1914 1914 --paging=vsplit is used.""")
1915 1915 if paging == 'hsplit':
1916 1916 self._splitter.setOrientation(QtCore.Qt.Horizontal)
1917 1917 elif paging == 'vsplit':
1918 1918 self._splitter.setOrientation(QtCore.Qt.Vertical)
1919 1919 elif paging == 'inside':
1920 1920 raise NotImplementedError("""switching to 'inside' paging not
1921 1921 supported yet.""")
1922 1922 else:
1923 1923 raise ValueError("unknown paging method '%s'" % paging)
1924 1924 self.paging = paging
1925 1925
1926 1926 def _prompt_finished(self):
1927 1927 """ Called immediately after a prompt is finished, i.e. when some input
1928 1928 will be processed and a new prompt displayed.
1929 1929 """
1930 1930 self._control.setReadOnly(True)
1931 1931 self._prompt_finished_hook()
1932 1932
1933 1933 def _prompt_started(self):
1934 1934 """ Called immediately after a new prompt is displayed.
1935 1935 """
1936 1936 # Temporarily disable the maximum block count to permit undo/redo and
1937 1937 # to ensure that the prompt position does not change due to truncation.
1938 1938 self._control.document().setMaximumBlockCount(0)
1939 1939 self._control.setUndoRedoEnabled(True)
1940 1940
1941 1941 # Work around bug in QPlainTextEdit: input method is not re-enabled
1942 1942 # when read-only is disabled.
1943 1943 self._control.setReadOnly(False)
1944 1944 self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
1945 1945
1946 1946 if not self._reading:
1947 1947 self._executing = False
1948 1948 self._prompt_started_hook()
1949 1949
1950 1950 # If the input buffer has changed while executing, load it.
1951 1951 if self._input_buffer_pending:
1952 1952 self.input_buffer = self._input_buffer_pending
1953 1953 self._input_buffer_pending = ''
1954 1954
1955 1955 self._control.moveCursor(QtGui.QTextCursor.End)
1956 1956
1957 1957 def _readline(self, prompt='', callback=None):
1958 1958 """ Reads one line of input from the user.
1959 1959
1960 1960 Parameters
1961 1961 ----------
1962 1962 prompt : str, optional
1963 1963 The prompt to print before reading the line.
1964 1964
1965 1965 callback : callable, optional
1966 1966 A callback to execute with the read line. If not specified, input is
1967 1967 read *synchronously* and this method does not return until it has
1968 1968 been read.
1969 1969
1970 1970 Returns
1971 1971 -------
1972 1972 If a callback is specified, returns nothing. Otherwise, returns the
1973 1973 input string with the trailing newline stripped.
1974 1974 """
1975 1975 if self._reading:
1976 1976 raise RuntimeError('Cannot read a line. Widget is already reading.')
1977 1977
1978 1978 if not callback and not self.isVisible():
1979 1979 # If the user cannot see the widget, this function cannot return.
1980 1980 raise RuntimeError('Cannot synchronously read a line if the widget '
1981 1981 'is not visible!')
1982 1982
1983 1983 self._reading = True
1984 1984 self._show_prompt(prompt, newline=False)
1985 1985
1986 1986 if callback is None:
1987 1987 self._reading_callback = None
1988 1988 while self._reading:
1989 1989 QtCore.QCoreApplication.processEvents()
1990 1990 return self._get_input_buffer(force=True).rstrip('\n')
1991 1991
1992 1992 else:
1993 1993 self._reading_callback = lambda: \
1994 1994 callback(self._get_input_buffer(force=True).rstrip('\n'))
1995 1995
1996 1996 def _set_continuation_prompt(self, prompt, html=False):
1997 1997 """ Sets the continuation prompt.
1998 1998
1999 1999 Parameters
2000 2000 ----------
2001 2001 prompt : str
2002 2002 The prompt to show when more input is needed.
2003 2003
2004 2004 html : bool, optional (default False)
2005 2005 If set, the prompt will be inserted as formatted HTML. Otherwise,
2006 2006 the prompt will be treated as plain text, though ANSI color codes
2007 2007 will be handled.
2008 2008 """
2009 2009 if html:
2010 2010 self._continuation_prompt_html = prompt
2011 2011 else:
2012 2012 self._continuation_prompt = prompt
2013 2013 self._continuation_prompt_html = None
2014 2014
2015 2015 def _set_cursor(self, cursor):
2016 2016 """ Convenience method to set the current cursor.
2017 2017 """
2018 2018 self._control.setTextCursor(cursor)
2019 2019
2020 2020 def _set_top_cursor(self, cursor):
2021 2021 """ Scrolls the viewport so that the specified cursor is at the top.
2022 2022 """
2023 2023 scrollbar = self._control.verticalScrollBar()
2024 2024 scrollbar.setValue(scrollbar.maximum())
2025 2025 original_cursor = self._control.textCursor()
2026 2026 self._control.setTextCursor(cursor)
2027 2027 self._control.ensureCursorVisible()
2028 2028 self._control.setTextCursor(original_cursor)
2029 2029
2030 2030 def _show_prompt(self, prompt=None, html=False, newline=True):
2031 2031 """ Writes a new prompt at the end of the buffer.
2032 2032
2033 2033 Parameters
2034 2034 ----------
2035 2035 prompt : str, optional
2036 2036 The prompt to show. If not specified, the previous prompt is used.
2037 2037
2038 2038 html : bool, optional (default False)
2039 2039 Only relevant when a prompt is specified. If set, the prompt will
2040 2040 be inserted as formatted HTML. Otherwise, the prompt will be treated
2041 2041 as plain text, though ANSI color codes will be handled.
2042 2042
2043 2043 newline : bool, optional (default True)
2044 2044 If set, a new line will be written before showing the prompt if
2045 2045 there is not already a newline at the end of the buffer.
2046 2046 """
2047 2047 # Save the current end position to support _append*(before_prompt=True).
2048 2048 cursor = self._get_end_cursor()
2049 2049 self._append_before_prompt_pos = cursor.position()
2050 2050
2051 2051 # Insert a preliminary newline, if necessary.
2052 2052 if newline and cursor.position() > 0:
2053 2053 cursor.movePosition(QtGui.QTextCursor.Left,
2054 2054 QtGui.QTextCursor.KeepAnchor)
2055 2055 if cursor.selection().toPlainText() != '\n':
2056 2056 self._append_block()
2057 2057
2058 2058 # Write the prompt.
2059 2059 self._append_plain_text(self._prompt_sep)
2060 2060 if prompt is None:
2061 2061 if self._prompt_html is None:
2062 2062 self._append_plain_text(self._prompt)
2063 2063 else:
2064 2064 self._append_html(self._prompt_html)
2065 2065 else:
2066 2066 if html:
2067 2067 self._prompt = self._append_html_fetching_plain_text(prompt)
2068 2068 self._prompt_html = prompt
2069 2069 else:
2070 2070 self._append_plain_text(prompt)
2071 2071 self._prompt = prompt
2072 2072 self._prompt_html = None
2073 2073
2074 2074 self._flush_pending_stream()
2075 2075 self._prompt_pos = self._get_end_cursor().position()
2076 2076 self._prompt_started()
2077 2077
2078 2078 #------ Signal handlers ----------------------------------------------------
2079 2079
2080 2080 def _adjust_scrollbars(self):
2081 2081 """ Expands the vertical scrollbar beyond the range set by Qt.
2082 2082 """
2083 2083 # This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
2084 2084 # and qtextedit.cpp.
2085 2085 document = self._control.document()
2086 2086 scrollbar = self._control.verticalScrollBar()
2087 2087 viewport_height = self._control.viewport().height()
2088 2088 if isinstance(self._control, QtGui.QPlainTextEdit):
2089 2089 maximum = max(0, document.lineCount() - 1)
2090 2090 step = viewport_height / self._control.fontMetrics().lineSpacing()
2091 2091 else:
2092 2092 # QTextEdit does not do line-based layout and blocks will not in
2093 2093 # general have the same height. Therefore it does not make sense to
2094 2094 # attempt to scroll in line height increments.
2095 2095 maximum = document.size().height()
2096 2096 step = viewport_height
2097 2097 diff = maximum - scrollbar.maximum()
2098 2098 scrollbar.setRange(0, maximum)
2099 2099 scrollbar.setPageStep(step)
2100 2100
2101 2101 # Compensate for undesirable scrolling that occurs automatically due to
2102 2102 # maximumBlockCount() text truncation.
2103 2103 if diff < 0 and document.blockCount() == document.maximumBlockCount():
2104 2104 scrollbar.setValue(scrollbar.value() + diff)
2105 2105
2106 2106 def _custom_context_menu_requested(self, pos):
2107 2107 """ Shows a context menu at the given QPoint (in widget coordinates).
2108 2108 """
2109 2109 menu = self._context_menu_make(pos)
2110 2110 menu.exec_(self._control.mapToGlobal(pos))
@@ -1,220 +1,215 b''
1 1 """ Defines a KernelManager that provides signals and slots.
2 2 """
3 3
4 4 # System library imports.
5 5 from IPython.external.qt import QtCore
6 6
7 7 # IPython imports.
8 8 from IPython.utils.traitlets import HasTraits, Type
9 9 from .util import MetaQObjectHasTraits, SuperQObject
10 10
11 11
12 12 class ChannelQObject(SuperQObject):
13 13
14 14 # Emitted when the channel is started.
15 15 started = QtCore.Signal()
16 16
17 17 # Emitted when the channel is stopped.
18 18 stopped = QtCore.Signal()
19 19
20 20 #---------------------------------------------------------------------------
21 21 # Channel interface
22 22 #---------------------------------------------------------------------------
23 23
24 24 def start(self):
25 25 """ Reimplemented to emit signal.
26 26 """
27 27 super(ChannelQObject, self).start()
28 28 self.started.emit()
29 29
30 30 def stop(self):
31 31 """ Reimplemented to emit signal.
32 32 """
33 33 super(ChannelQObject, self).stop()
34 34 self.stopped.emit()
35 35
36 36 #---------------------------------------------------------------------------
37 37 # InProcessChannel interface
38 38 #---------------------------------------------------------------------------
39 39
40 40 def call_handlers_later(self, *args, **kwds):
41 41 """ Call the message handlers later.
42 42 """
43 43 do_later = lambda: self.call_handlers(*args, **kwds)
44 44 QtCore.QTimer.singleShot(0, do_later)
45 45
46 46 def process_events(self):
47 47 """ Process any pending GUI events.
48 48 """
49 49 QtCore.QCoreApplication.instance().processEvents()
50 50
51 51
52 52 class QtShellChannelMixin(ChannelQObject):
53 53
54 54 # Emitted when any message is received.
55 55 message_received = QtCore.Signal(object)
56 56
57 57 # Emitted when a reply has been received for the corresponding request type.
58 58 execute_reply = QtCore.Signal(object)
59 59 complete_reply = QtCore.Signal(object)
60 60 object_info_reply = QtCore.Signal(object)
61 61 history_reply = QtCore.Signal(object)
62 62
63 63 #---------------------------------------------------------------------------
64 64 # 'ShellChannel' interface
65 65 #---------------------------------------------------------------------------
66 66
67 67 def call_handlers(self, msg):
68 68 """ Reimplemented to emit signals instead of making callbacks.
69 69 """
70 70 # Emit the generic signal.
71 71 self.message_received.emit(msg)
72 72
73 73 # Emit signals for specialized message types.
74 74 msg_type = msg['header']['msg_type']
75 75 signal = getattr(self, msg_type, None)
76 76 if signal:
77 77 signal.emit(msg)
78 78
79 79
80 80 class QtIOPubChannelMixin(ChannelQObject):
81 81
82 82 # Emitted when any message is received.
83 83 message_received = QtCore.Signal(object)
84 84
85 85 # Emitted when a message of type 'stream' is received.
86 86 stream_received = QtCore.Signal(object)
87 87
88 88 # Emitted when a message of type 'pyin' is received.
89 89 pyin_received = QtCore.Signal(object)
90 90
91 91 # Emitted when a message of type 'pyout' is received.
92 92 pyout_received = QtCore.Signal(object)
93 93
94 94 # Emitted when a message of type 'pyerr' is received.
95 95 pyerr_received = QtCore.Signal(object)
96 96
97 97 # Emitted when a message of type 'display_data' is received
98 98 display_data_received = QtCore.Signal(object)
99 99
100 100 # Emitted when a crash report message is received from the kernel's
101 101 # last-resort sys.excepthook.
102 102 crash_received = QtCore.Signal(object)
103 103
104 104 # Emitted when a shutdown is noticed.
105 105 shutdown_reply_received = QtCore.Signal(object)
106 106
107 107 #---------------------------------------------------------------------------
108 108 # 'IOPubChannel' interface
109 109 #---------------------------------------------------------------------------
110 110
111 111 def call_handlers(self, msg):
112 112 """ Reimplemented to emit signals instead of making callbacks.
113 113 """
114 114 # Emit the generic signal.
115 115 self.message_received.emit(msg)
116 116 # Emit signals for specialized message types.
117 117 msg_type = msg['header']['msg_type']
118 118 signal = getattr(self, msg_type + '_received', None)
119 119 if signal:
120 120 signal.emit(msg)
121 121 elif msg_type in ('stdout', 'stderr'):
122 122 self.stream_received.emit(msg)
123 123
124 124 def flush(self):
125 125 """ Reimplemented to ensure that signals are dispatched immediately.
126 126 """
127 127 super(QtIOPubChannelMixin, self).flush()
128 128 QtCore.QCoreApplication.instance().processEvents()
129 129
130 130
131 131 class QtStdInChannelMixin(ChannelQObject):
132 132
133 133 # Emitted when any message is received.
134 134 message_received = QtCore.Signal(object)
135 135
136 136 # Emitted when an input request is received.
137 137 input_requested = QtCore.Signal(object)
138 138
139 139 #---------------------------------------------------------------------------
140 140 # 'StdInChannel' interface
141 141 #---------------------------------------------------------------------------
142 142
143 143 def call_handlers(self, msg):
144 144 """ Reimplemented to emit signals instead of making callbacks.
145 145 """
146 146 # Emit the generic signal.
147 147 self.message_received.emit(msg)
148 148
149 149 # Emit signals for specialized message types.
150 150 msg_type = msg['header']['msg_type']
151 151 if msg_type == 'input_request':
152 152 self.input_requested.emit(msg)
153 153
154 154
155 155 class QtHBChannelMixin(ChannelQObject):
156 156
157 157 # Emitted when the kernel has died.
158 158 kernel_died = QtCore.Signal(object)
159 159
160 160 #---------------------------------------------------------------------------
161 161 # 'HBChannel' interface
162 162 #---------------------------------------------------------------------------
163 163
164 164 def call_handlers(self, since_last_heartbeat):
165 165 """ Reimplemented to emit signals instead of making callbacks.
166 166 """
167 167 # Emit the generic signal.
168 168 self.kernel_died.emit(since_last_heartbeat)
169 169
170 170
171 class QtKernelRestarterMixin(HasTraits, SuperQObject):
171 class QtKernelRestarterMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
172 172
173 __metaclass__ = MetaQObjectHasTraits
174 173 _timer = None
175 174
176 175
177 class QtKernelManagerMixin(HasTraits, SuperQObject):
176 class QtKernelManagerMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
178 177 """ A KernelClient that provides signals and slots.
179 178 """
180 179
181 __metaclass__ = MetaQObjectHasTraits
182
183 180 kernel_restarted = QtCore.Signal()
184 181
185 182
186 class QtKernelClientMixin(HasTraits, SuperQObject):
183 class QtKernelClientMixin(MetaQObjectHasTraits('NewBase', (HasTraits, SuperQObject), {})):
187 184 """ A KernelClient that provides signals and slots.
188 185 """
189 186
190 __metaclass__ = MetaQObjectHasTraits
191
192 187 # Emitted when the kernel client has started listening.
193 188 started_channels = QtCore.Signal()
194 189
195 190 # Emitted when the kernel client has stopped listening.
196 191 stopped_channels = QtCore.Signal()
197 192
198 193 # Use Qt-specific channel classes that emit signals.
199 194 iopub_channel_class = Type(QtIOPubChannelMixin)
200 195 shell_channel_class = Type(QtShellChannelMixin)
201 196 stdin_channel_class = Type(QtStdInChannelMixin)
202 197 hb_channel_class = Type(QtHBChannelMixin)
203 198
204 199 #---------------------------------------------------------------------------
205 200 # 'KernelClient' interface
206 201 #---------------------------------------------------------------------------
207 202
208 203 #------ Channel management -------------------------------------------------
209 204
210 205 def start_channels(self, *args, **kw):
211 206 """ Reimplemented to emit signal.
212 207 """
213 208 super(QtKernelClientMixin, self).start_channels(*args, **kw)
214 209 self.started_channels.emit()
215 210
216 211 def stop_channels(self):
217 212 """ Reimplemented to emit signal.
218 213 """
219 214 super(QtKernelClientMixin, self).stop_channels()
220 215 self.stopped_channels.emit()
@@ -1,210 +1,235 b''
1 1 # coding: utf-8
2 2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 3 import functools
4 4 import sys
5 5 import re
6 6 import types
7 7
8 8 from .encoding import DEFAULT_ENCODING
9 9
10 10 orig_open = open
11 11
12 12 def no_code(x, encoding=None):
13 13 return x
14 14
15 15 def decode(s, encoding=None):
16 16 encoding = encoding or DEFAULT_ENCODING
17 17 return s.decode(encoding, "replace")
18 18
19 19 def encode(u, encoding=None):
20 20 encoding = encoding or DEFAULT_ENCODING
21 21 return u.encode(encoding, "replace")
22 22
23 23
24 24 def cast_unicode(s, encoding=None):
25 25 if isinstance(s, bytes):
26 26 return decode(s, encoding)
27 27 return s
28 28
29 29 def cast_bytes(s, encoding=None):
30 30 if not isinstance(s, bytes):
31 31 return encode(s, encoding)
32 32 return s
33 33
34 34 def _modify_str_or_docstring(str_change_func):
35 35 @functools.wraps(str_change_func)
36 36 def wrapper(func_or_str):
37 37 if isinstance(func_or_str, string_types):
38 38 func = None
39 39 doc = func_or_str
40 40 else:
41 41 func = func_or_str
42 42 doc = func.__doc__
43 43
44 44 doc = str_change_func(doc)
45 45
46 46 if func:
47 47 func.__doc__ = doc
48 48 return func
49 49 return doc
50 50 return wrapper
51 51
52 52 def safe_unicode(e):
53 53 """unicode(e) with various fallbacks. Used for exceptions, which may not be
54 54 safe to call unicode() on.
55 55 """
56 56 try:
57 57 return unicode_type(e)
58 58 except UnicodeError:
59 59 pass
60 60
61 61 try:
62 62 return str_to_unicode(str(e))
63 63 except UnicodeError:
64 64 pass
65 65
66 66 try:
67 67 return str_to_unicode(repr(e))
68 68 except UnicodeError:
69 69 pass
70 70
71 71 return u'Unrecoverably corrupt evalue'
72 72
73 73 if sys.version_info[0] >= 3:
74 74 PY3 = True
75 75
76 76 input = input
77 77 builtin_mod_name = "builtins"
78 78 import builtins as builtin_mod
79 79
80 80 str_to_unicode = no_code
81 81 unicode_to_str = no_code
82 82 str_to_bytes = encode
83 83 bytes_to_str = decode
84 84 cast_bytes_py2 = no_code
85 85
86 86 string_types = (str,)
87 87 unicode_type = str
88 88
89 89 def isidentifier(s, dotted=False):
90 90 if dotted:
91 91 return all(isidentifier(a) for a in s.split("."))
92 92 return s.isidentifier()
93 93
94 94 open = orig_open
95 95 xrange = range
96 96
97 97 MethodType = types.MethodType
98 98
99 99 def execfile(fname, glob, loc=None):
100 100 loc = loc if (loc is not None) else glob
101 101 with open(fname, 'rb') as f:
102 102 exec(compile(f.read(), fname, 'exec'), glob, loc)
103 103
104 104 # Refactor print statements in doctests.
105 105 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
106 106 def _print_statement_sub(match):
107 107 expr = match.groups('expr')
108 108 return "print(%s)" % expr
109 109
110 110 @_modify_str_or_docstring
111 111 def doctest_refactor_print(doc):
112 112 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
113 113 unfortunately doesn't pick up on our doctests.
114 114
115 115 Can accept a string or a function, so it can be used as a decorator."""
116 116 return _print_statement_re.sub(_print_statement_sub, doc)
117 117
118 118 # Abstract u'abc' syntax:
119 119 @_modify_str_or_docstring
120 120 def u_format(s):
121 121 """"{u}'abc'" --> "'abc'" (Python 3)
122 122
123 123 Accepts a string or a function, so it can be used as a decorator."""
124 124 return s.format(u='')
125 125
126 126 else:
127 127 PY3 = False
128 128
129 129 input = raw_input
130 130 builtin_mod_name = "__builtin__"
131 131 import __builtin__ as builtin_mod
132 132
133 133 str_to_unicode = decode
134 134 unicode_to_str = encode
135 135 str_to_bytes = no_code
136 136 bytes_to_str = no_code
137 137 cast_bytes_py2 = cast_bytes
138 138
139 139 string_types = (str, unicode)
140 140 unicode_type = unicode
141 141
142 142 import re
143 143 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
144 144 def isidentifier(s, dotted=False):
145 145 if dotted:
146 146 return all(isidentifier(a) for a in s.split("."))
147 147 return bool(_name_re.match(s))
148 148
149 149 class open(object):
150 150 """Wrapper providing key part of Python 3 open() interface."""
151 151 def __init__(self, fname, mode="r", encoding="utf-8"):
152 152 self.f = orig_open(fname, mode)
153 153 self.enc = encoding
154 154
155 155 def write(self, s):
156 156 return self.f.write(s.encode(self.enc))
157 157
158 158 def read(self, size=-1):
159 159 return self.f.read(size).decode(self.enc)
160 160
161 161 def close(self):
162 162 return self.f.close()
163 163
164 164 def __enter__(self):
165 165 return self
166 166
167 167 def __exit__(self, etype, value, traceback):
168 168 self.f.close()
169 169
170 170 xrange = xrange
171 171
172 172 def MethodType(func, instance):
173 173 return types.MethodType(func, instance, type(instance))
174 174
175 175 # don't override system execfile on 2.x:
176 176 execfile = execfile
177 177
178 178 def doctest_refactor_print(func_or_str):
179 179 return func_or_str
180 180
181 181
182 182 # Abstract u'abc' syntax:
183 183 @_modify_str_or_docstring
184 184 def u_format(s):
185 185 """"{u}'abc'" --> "u'abc'" (Python 2)
186 186
187 187 Accepts a string or a function, so it can be used as a decorator."""
188 188 return s.format(u='u')
189 189
190 190 if sys.platform == 'win32':
191 191 def execfile(fname, glob=None, loc=None):
192 192 loc = loc if (loc is not None) else glob
193 193 # The rstrip() is necessary b/c trailing whitespace in files will
194 194 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
195 195 # but we still support 2.6). See issue 1027.
196 196 scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
197 197 # compile converts unicode filename to str assuming
198 198 # ascii. Let's do the conversion before calling compile
199 199 if isinstance(fname, unicode):
200 200 filename = unicode_to_str(fname)
201 201 else:
202 202 filename = fname
203 203 exec(compile(scripttext, filename, 'exec'), glob, loc)
204 204 else:
205 205 def execfile(fname, *where):
206 206 if isinstance(fname, unicode):
207 207 filename = fname.encode(sys.getfilesystemencoding())
208 208 else:
209 209 filename = fname
210 210 builtin_mod.execfile(filename, *where)
211
212 # Parts below taken from six:
213 # Copyright (c) 2010-2013 Benjamin Peterson
214 #
215 # Permission is hereby granted, free of charge, to any person obtaining a copy
216 # of this software and associated documentation files (the "Software"), to deal
217 # in the Software without restriction, including without limitation the rights
218 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
219 # copies of the Software, and to permit persons to whom the Software is
220 # furnished to do so, subject to the following conditions:
221 #
222 # The above copyright notice and this permission notice shall be included in all
223 # copies or substantial portions of the Software.
224 #
225 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
226 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
227 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
228 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
229 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
230 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
231 # SOFTWARE.
232
233 def with_metaclass(meta, *bases):
234 """Create a base class with a metaclass."""
235 return meta("NewBase", bases, {})
@@ -1,1439 +1,1437 b''
1 1 # encoding: utf-8
2 2 """
3 3 A lightweight Traits like module.
4 4
5 5 This is designed to provide a lightweight, simple, pure Python version of
6 6 many of the capabilities of enthought.traits. This includes:
7 7
8 8 * Validation
9 9 * Type specification with defaults
10 10 * Static and dynamic notification
11 11 * Basic predefined types
12 12 * An API that is similar to enthought.traits
13 13
14 14 We don't support:
15 15
16 16 * Delegation
17 17 * Automatic GUI generation
18 18 * A full set of trait types. Most importantly, we don't provide container
19 19 traits (list, dict, tuple) that can trigger notifications if their
20 20 contents change.
21 21 * API compatibility with enthought.traits
22 22
23 23 There are also some important difference in our design:
24 24
25 25 * enthought.traits does not validate default values. We do.
26 26
27 27 We choose to create this module because we need these capabilities, but
28 28 we need them to be pure Python so they work in all Python implementations,
29 29 including Jython and IronPython.
30 30
31 31 Inheritance diagram:
32 32
33 33 .. inheritance-diagram:: IPython.utils.traitlets
34 34 :parts: 3
35 35
36 36 Authors:
37 37
38 38 * Brian Granger
39 39 * Enthought, Inc. Some of the code in this file comes from enthought.traits
40 40 and is licensed under the BSD license. Also, many of the ideas also come
41 41 from enthought.traits even though our implementation is very different.
42 42 """
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # Copyright (C) 2008-2011 The IPython Development Team
46 46 #
47 47 # Distributed under the terms of the BSD License. The full license is in
48 48 # the file COPYING, distributed as part of this software.
49 49 #-----------------------------------------------------------------------------
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Imports
53 53 #-----------------------------------------------------------------------------
54 54
55 55
56 56 import inspect
57 57 import re
58 58 import sys
59 59 import types
60 60 from types import FunctionType
61 61 try:
62 62 from types import ClassType, InstanceType
63 63 ClassTypes = (ClassType, type)
64 64 except:
65 65 ClassTypes = (type,)
66 66
67 67 from .importstring import import_item
68 68 from IPython.utils import py3compat
69 69
70 70 SequenceTypes = (list, tuple, set, frozenset)
71 71
72 72 #-----------------------------------------------------------------------------
73 73 # Basic classes
74 74 #-----------------------------------------------------------------------------
75 75
76 76
77 77 class NoDefaultSpecified ( object ): pass
78 78 NoDefaultSpecified = NoDefaultSpecified()
79 79
80 80
81 81 class Undefined ( object ): pass
82 82 Undefined = Undefined()
83 83
84 84 class TraitError(Exception):
85 85 pass
86 86
87 87 #-----------------------------------------------------------------------------
88 88 # Utilities
89 89 #-----------------------------------------------------------------------------
90 90
91 91
92 92 def class_of ( object ):
93 93 """ Returns a string containing the class name of an object with the
94 94 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
95 95 'a PlotValue').
96 96 """
97 97 if isinstance( object, py3compat.string_types ):
98 98 return add_article( object )
99 99
100 100 return add_article( object.__class__.__name__ )
101 101
102 102
103 103 def add_article ( name ):
104 104 """ Returns a string containing the correct indefinite article ('a' or 'an')
105 105 prefixed to the specified string.
106 106 """
107 107 if name[:1].lower() in 'aeiou':
108 108 return 'an ' + name
109 109
110 110 return 'a ' + name
111 111
112 112
113 113 def repr_type(obj):
114 114 """ Return a string representation of a value and its type for readable
115 115 error messages.
116 116 """
117 117 the_type = type(obj)
118 118 if (not py3compat.PY3) and the_type is InstanceType:
119 119 # Old-style class.
120 120 the_type = obj.__class__
121 121 msg = '%r %r' % (obj, the_type)
122 122 return msg
123 123
124 124
125 125 def is_trait(t):
126 126 """ Returns whether the given value is an instance or subclass of TraitType.
127 127 """
128 128 return (isinstance(t, TraitType) or
129 129 (isinstance(t, type) and issubclass(t, TraitType)))
130 130
131 131
132 132 def parse_notifier_name(name):
133 133 """Convert the name argument to a list of names.
134 134
135 135 Examples
136 136 --------
137 137
138 138 >>> parse_notifier_name('a')
139 139 ['a']
140 140 >>> parse_notifier_name(['a','b'])
141 141 ['a', 'b']
142 142 >>> parse_notifier_name(None)
143 143 ['anytrait']
144 144 """
145 145 if isinstance(name, str):
146 146 return [name]
147 147 elif name is None:
148 148 return ['anytrait']
149 149 elif isinstance(name, (list, tuple)):
150 150 for n in name:
151 151 assert isinstance(n, str), "names must be strings"
152 152 return name
153 153
154 154
155 155 class _SimpleTest:
156 156 def __init__ ( self, value ): self.value = value
157 157 def __call__ ( self, test ):
158 158 return test == self.value
159 159 def __repr__(self):
160 160 return "<SimpleTest(%r)" % self.value
161 161 def __str__(self):
162 162 return self.__repr__()
163 163
164 164
165 165 def getmembers(object, predicate=None):
166 166 """A safe version of inspect.getmembers that handles missing attributes.
167 167
168 168 This is useful when there are descriptor based attributes that for
169 169 some reason raise AttributeError even though they exist. This happens
170 170 in zope.inteface with the __provides__ attribute.
171 171 """
172 172 results = []
173 173 for key in dir(object):
174 174 try:
175 175 value = getattr(object, key)
176 176 except AttributeError:
177 177 pass
178 178 else:
179 179 if not predicate or predicate(value):
180 180 results.append((key, value))
181 181 results.sort()
182 182 return results
183 183
184 184
185 185 #-----------------------------------------------------------------------------
186 186 # Base TraitType for all traits
187 187 #-----------------------------------------------------------------------------
188 188
189 189
190 190 class TraitType(object):
191 191 """A base class for all trait descriptors.
192 192
193 193 Notes
194 194 -----
195 195 Our implementation of traits is based on Python's descriptor
196 196 prototol. This class is the base class for all such descriptors. The
197 197 only magic we use is a custom metaclass for the main :class:`HasTraits`
198 198 class that does the following:
199 199
200 200 1. Sets the :attr:`name` attribute of every :class:`TraitType`
201 201 instance in the class dict to the name of the attribute.
202 202 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
203 203 instance in the class dict to the *class* that declared the trait.
204 204 This is used by the :class:`This` trait to allow subclasses to
205 205 accept superclasses for :class:`This` values.
206 206 """
207 207
208 208
209 209 metadata = {}
210 210 default_value = Undefined
211 211 info_text = 'any value'
212 212
213 213 def __init__(self, default_value=NoDefaultSpecified, **metadata):
214 214 """Create a TraitType.
215 215 """
216 216 if default_value is not NoDefaultSpecified:
217 217 self.default_value = default_value
218 218
219 219 if len(metadata) > 0:
220 220 if len(self.metadata) > 0:
221 221 self._metadata = self.metadata.copy()
222 222 self._metadata.update(metadata)
223 223 else:
224 224 self._metadata = metadata
225 225 else:
226 226 self._metadata = self.metadata
227 227
228 228 self.init()
229 229
230 230 def init(self):
231 231 pass
232 232
233 233 def get_default_value(self):
234 234 """Create a new instance of the default value."""
235 235 return self.default_value
236 236
237 237 def instance_init(self, obj):
238 238 """This is called by :meth:`HasTraits.__new__` to finish init'ing.
239 239
240 240 Some stages of initialization must be delayed until the parent
241 241 :class:`HasTraits` instance has been created. This method is
242 242 called in :meth:`HasTraits.__new__` after the instance has been
243 243 created.
244 244
245 245 This method trigger the creation and validation of default values
246 246 and also things like the resolution of str given class names in
247 247 :class:`Type` and :class`Instance`.
248 248
249 249 Parameters
250 250 ----------
251 251 obj : :class:`HasTraits` instance
252 252 The parent :class:`HasTraits` instance that has just been
253 253 created.
254 254 """
255 255 self.set_default_value(obj)
256 256
257 257 def set_default_value(self, obj):
258 258 """Set the default value on a per instance basis.
259 259
260 260 This method is called by :meth:`instance_init` to create and
261 261 validate the default value. The creation and validation of
262 262 default values must be delayed until the parent :class:`HasTraits`
263 263 class has been instantiated.
264 264 """
265 265 # Check for a deferred initializer defined in the same class as the
266 266 # trait declaration or above.
267 267 mro = type(obj).mro()
268 268 meth_name = '_%s_default' % self.name
269 269 for cls in mro[:mro.index(self.this_class)+1]:
270 270 if meth_name in cls.__dict__:
271 271 break
272 272 else:
273 273 # We didn't find one. Do static initialization.
274 274 dv = self.get_default_value()
275 275 newdv = self._validate(obj, dv)
276 276 obj._trait_values[self.name] = newdv
277 277 return
278 278 # Complete the dynamic initialization.
279 279 obj._trait_dyn_inits[self.name] = cls.__dict__[meth_name]
280 280
281 281 def __get__(self, obj, cls=None):
282 282 """Get the value of the trait by self.name for the instance.
283 283
284 284 Default values are instantiated when :meth:`HasTraits.__new__`
285 285 is called. Thus by the time this method gets called either the
286 286 default value or a user defined value (they called :meth:`__set__`)
287 287 is in the :class:`HasTraits` instance.
288 288 """
289 289 if obj is None:
290 290 return self
291 291 else:
292 292 try:
293 293 value = obj._trait_values[self.name]
294 294 except KeyError:
295 295 # Check for a dynamic initializer.
296 296 if self.name in obj._trait_dyn_inits:
297 297 value = obj._trait_dyn_inits[self.name](obj)
298 298 # FIXME: Do we really validate here?
299 299 value = self._validate(obj, value)
300 300 obj._trait_values[self.name] = value
301 301 return value
302 302 else:
303 303 raise TraitError('Unexpected error in TraitType: '
304 304 'both default value and dynamic initializer are '
305 305 'absent.')
306 306 except Exception:
307 307 # HasTraits should call set_default_value to populate
308 308 # this. So this should never be reached.
309 309 raise TraitError('Unexpected error in TraitType: '
310 310 'default value not set properly')
311 311 else:
312 312 return value
313 313
314 314 def __set__(self, obj, value):
315 315 new_value = self._validate(obj, value)
316 316 old_value = self.__get__(obj)
317 317 obj._trait_values[self.name] = new_value
318 318 if old_value != new_value:
319 319 obj._notify_trait(self.name, old_value, new_value)
320 320
321 321 def _validate(self, obj, value):
322 322 if hasattr(self, 'validate'):
323 323 return self.validate(obj, value)
324 324 elif hasattr(self, 'is_valid_for'):
325 325 valid = self.is_valid_for(value)
326 326 if valid:
327 327 return value
328 328 else:
329 329 raise TraitError('invalid value for type: %r' % value)
330 330 elif hasattr(self, 'value_for'):
331 331 return self.value_for(value)
332 332 else:
333 333 return value
334 334
335 335 def info(self):
336 336 return self.info_text
337 337
338 338 def error(self, obj, value):
339 339 if obj is not None:
340 340 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
341 341 % (self.name, class_of(obj),
342 342 self.info(), repr_type(value))
343 343 else:
344 344 e = "The '%s' trait must be %s, but a value of %r was specified." \
345 345 % (self.name, self.info(), repr_type(value))
346 346 raise TraitError(e)
347 347
348 348 def get_metadata(self, key):
349 349 return getattr(self, '_metadata', {}).get(key, None)
350 350
351 351 def set_metadata(self, key, value):
352 352 getattr(self, '_metadata', {})[key] = value
353 353
354 354
355 355 #-----------------------------------------------------------------------------
356 356 # The HasTraits implementation
357 357 #-----------------------------------------------------------------------------
358 358
359 359
360 360 class MetaHasTraits(type):
361 361 """A metaclass for HasTraits.
362 362
363 363 This metaclass makes sure that any TraitType class attributes are
364 364 instantiated and sets their name attribute.
365 365 """
366 366
367 367 def __new__(mcls, name, bases, classdict):
368 368 """Create the HasTraits class.
369 369
370 370 This instantiates all TraitTypes in the class dict and sets their
371 371 :attr:`name` attribute.
372 372 """
373 373 # print "MetaHasTraitlets (mcls, name): ", mcls, name
374 374 # print "MetaHasTraitlets (bases): ", bases
375 375 # print "MetaHasTraitlets (classdict): ", classdict
376 376 for k,v in classdict.iteritems():
377 377 if isinstance(v, TraitType):
378 378 v.name = k
379 379 elif inspect.isclass(v):
380 380 if issubclass(v, TraitType):
381 381 vinst = v()
382 382 vinst.name = k
383 383 classdict[k] = vinst
384 384 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
385 385
386 386 def __init__(cls, name, bases, classdict):
387 387 """Finish initializing the HasTraits class.
388 388
389 389 This sets the :attr:`this_class` attribute of each TraitType in the
390 390 class dict to the newly created class ``cls``.
391 391 """
392 392 for k, v in classdict.iteritems():
393 393 if isinstance(v, TraitType):
394 394 v.this_class = cls
395 395 super(MetaHasTraits, cls).__init__(name, bases, classdict)
396 396
397 class HasTraits(object):
398
399 __metaclass__ = MetaHasTraits
397 class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)):
400 398
401 399 def __new__(cls, *args, **kw):
402 400 # This is needed because in Python 2.6 object.__new__ only accepts
403 401 # the cls argument.
404 402 new_meth = super(HasTraits, cls).__new__
405 403 if new_meth is object.__new__:
406 404 inst = new_meth(cls)
407 405 else:
408 406 inst = new_meth(cls, **kw)
409 407 inst._trait_values = {}
410 408 inst._trait_notifiers = {}
411 409 inst._trait_dyn_inits = {}
412 410 # Here we tell all the TraitType instances to set their default
413 411 # values on the instance.
414 412 for key in dir(cls):
415 413 # Some descriptors raise AttributeError like zope.interface's
416 414 # __provides__ attributes even though they exist. This causes
417 415 # AttributeErrors even though they are listed in dir(cls).
418 416 try:
419 417 value = getattr(cls, key)
420 418 except AttributeError:
421 419 pass
422 420 else:
423 421 if isinstance(value, TraitType):
424 422 value.instance_init(inst)
425 423
426 424 return inst
427 425
428 426 def __init__(self, *args, **kw):
429 427 # Allow trait values to be set using keyword arguments.
430 428 # We need to use setattr for this to trigger validation and
431 429 # notifications.
432 430 for key, value in kw.iteritems():
433 431 setattr(self, key, value)
434 432
435 433 def _notify_trait(self, name, old_value, new_value):
436 434
437 435 # First dynamic ones
438 436 callables = []
439 437 callables.extend(self._trait_notifiers.get(name,[]))
440 438 callables.extend(self._trait_notifiers.get('anytrait',[]))
441 439
442 440 # Now static ones
443 441 try:
444 442 cb = getattr(self, '_%s_changed' % name)
445 443 except:
446 444 pass
447 445 else:
448 446 callables.append(cb)
449 447
450 448 # Call them all now
451 449 for c in callables:
452 450 # Traits catches and logs errors here. I allow them to raise
453 451 if callable(c):
454 452 argspec = inspect.getargspec(c)
455 453 nargs = len(argspec[0])
456 454 # Bound methods have an additional 'self' argument
457 455 # I don't know how to treat unbound methods, but they
458 456 # can't really be used for callbacks.
459 457 if isinstance(c, types.MethodType):
460 458 offset = -1
461 459 else:
462 460 offset = 0
463 461 if nargs + offset == 0:
464 462 c()
465 463 elif nargs + offset == 1:
466 464 c(name)
467 465 elif nargs + offset == 2:
468 466 c(name, new_value)
469 467 elif nargs + offset == 3:
470 468 c(name, old_value, new_value)
471 469 else:
472 470 raise TraitError('a trait changed callback '
473 471 'must have 0-3 arguments.')
474 472 else:
475 473 raise TraitError('a trait changed callback '
476 474 'must be callable.')
477 475
478 476
479 477 def _add_notifiers(self, handler, name):
480 478 if name not in self._trait_notifiers:
481 479 nlist = []
482 480 self._trait_notifiers[name] = nlist
483 481 else:
484 482 nlist = self._trait_notifiers[name]
485 483 if handler not in nlist:
486 484 nlist.append(handler)
487 485
488 486 def _remove_notifiers(self, handler, name):
489 487 if name in self._trait_notifiers:
490 488 nlist = self._trait_notifiers[name]
491 489 try:
492 490 index = nlist.index(handler)
493 491 except ValueError:
494 492 pass
495 493 else:
496 494 del nlist[index]
497 495
498 496 def on_trait_change(self, handler, name=None, remove=False):
499 497 """Setup a handler to be called when a trait changes.
500 498
501 499 This is used to setup dynamic notifications of trait changes.
502 500
503 501 Static handlers can be created by creating methods on a HasTraits
504 502 subclass with the naming convention '_[traitname]_changed'. Thus,
505 503 to create static handler for the trait 'a', create the method
506 504 _a_changed(self, name, old, new) (fewer arguments can be used, see
507 505 below).
508 506
509 507 Parameters
510 508 ----------
511 509 handler : callable
512 510 A callable that is called when a trait changes. Its
513 511 signature can be handler(), handler(name), handler(name, new)
514 512 or handler(name, old, new).
515 513 name : list, str, None
516 514 If None, the handler will apply to all traits. If a list
517 515 of str, handler will apply to all names in the list. If a
518 516 str, the handler will apply just to that name.
519 517 remove : bool
520 518 If False (the default), then install the handler. If True
521 519 then unintall it.
522 520 """
523 521 if remove:
524 522 names = parse_notifier_name(name)
525 523 for n in names:
526 524 self._remove_notifiers(handler, n)
527 525 else:
528 526 names = parse_notifier_name(name)
529 527 for n in names:
530 528 self._add_notifiers(handler, n)
531 529
532 530 @classmethod
533 531 def class_trait_names(cls, **metadata):
534 532 """Get a list of all the names of this classes traits.
535 533
536 534 This method is just like the :meth:`trait_names` method, but is unbound.
537 535 """
538 536 return cls.class_traits(**metadata).keys()
539 537
540 538 @classmethod
541 539 def class_traits(cls, **metadata):
542 540 """Get a list of all the traits of this class.
543 541
544 542 This method is just like the :meth:`traits` method, but is unbound.
545 543
546 544 The TraitTypes returned don't know anything about the values
547 545 that the various HasTrait's instances are holding.
548 546
549 547 This follows the same algorithm as traits does and does not allow
550 548 for any simple way of specifying merely that a metadata name
551 549 exists, but has any value. This is because get_metadata returns
552 550 None if a metadata key doesn't exist.
553 551 """
554 552 traits = dict([memb for memb in getmembers(cls) if \
555 553 isinstance(memb[1], TraitType)])
556 554
557 555 if len(metadata) == 0:
558 556 return traits
559 557
560 558 for meta_name, meta_eval in metadata.items():
561 559 if type(meta_eval) is not FunctionType:
562 560 metadata[meta_name] = _SimpleTest(meta_eval)
563 561
564 562 result = {}
565 563 for name, trait in traits.items():
566 564 for meta_name, meta_eval in metadata.items():
567 565 if not meta_eval(trait.get_metadata(meta_name)):
568 566 break
569 567 else:
570 568 result[name] = trait
571 569
572 570 return result
573 571
574 572 def trait_names(self, **metadata):
575 573 """Get a list of all the names of this classes traits."""
576 574 return self.traits(**metadata).keys()
577 575
578 576 def traits(self, **metadata):
579 577 """Get a list of all the traits of this class.
580 578
581 579 The TraitTypes returned don't know anything about the values
582 580 that the various HasTrait's instances are holding.
583 581
584 582 This follows the same algorithm as traits does and does not allow
585 583 for any simple way of specifying merely that a metadata name
586 584 exists, but has any value. This is because get_metadata returns
587 585 None if a metadata key doesn't exist.
588 586 """
589 587 traits = dict([memb for memb in getmembers(self.__class__) if \
590 588 isinstance(memb[1], TraitType)])
591 589
592 590 if len(metadata) == 0:
593 591 return traits
594 592
595 593 for meta_name, meta_eval in metadata.items():
596 594 if type(meta_eval) is not FunctionType:
597 595 metadata[meta_name] = _SimpleTest(meta_eval)
598 596
599 597 result = {}
600 598 for name, trait in traits.items():
601 599 for meta_name, meta_eval in metadata.items():
602 600 if not meta_eval(trait.get_metadata(meta_name)):
603 601 break
604 602 else:
605 603 result[name] = trait
606 604
607 605 return result
608 606
609 607 def trait_metadata(self, traitname, key):
610 608 """Get metadata values for trait by key."""
611 609 try:
612 610 trait = getattr(self.__class__, traitname)
613 611 except AttributeError:
614 612 raise TraitError("Class %s does not have a trait named %s" %
615 613 (self.__class__.__name__, traitname))
616 614 else:
617 615 return trait.get_metadata(key)
618 616
619 617 #-----------------------------------------------------------------------------
620 618 # Actual TraitTypes implementations/subclasses
621 619 #-----------------------------------------------------------------------------
622 620
623 621 #-----------------------------------------------------------------------------
624 622 # TraitTypes subclasses for handling classes and instances of classes
625 623 #-----------------------------------------------------------------------------
626 624
627 625
628 626 class ClassBasedTraitType(TraitType):
629 627 """A trait with error reporting for Type, Instance and This."""
630 628
631 629 def error(self, obj, value):
632 630 kind = type(value)
633 631 if (not py3compat.PY3) and kind is InstanceType:
634 632 msg = 'class %s' % value.__class__.__name__
635 633 else:
636 634 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
637 635
638 636 if obj is not None:
639 637 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
640 638 % (self.name, class_of(obj),
641 639 self.info(), msg)
642 640 else:
643 641 e = "The '%s' trait must be %s, but a value of %r was specified." \
644 642 % (self.name, self.info(), msg)
645 643
646 644 raise TraitError(e)
647 645
648 646
649 647 class Type(ClassBasedTraitType):
650 648 """A trait whose value must be a subclass of a specified class."""
651 649
652 650 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
653 651 """Construct a Type trait
654 652
655 653 A Type trait specifies that its values must be subclasses of
656 654 a particular class.
657 655
658 656 If only ``default_value`` is given, it is used for the ``klass`` as
659 657 well.
660 658
661 659 Parameters
662 660 ----------
663 661 default_value : class, str or None
664 662 The default value must be a subclass of klass. If an str,
665 663 the str must be a fully specified class name, like 'foo.bar.Bah'.
666 664 The string is resolved into real class, when the parent
667 665 :class:`HasTraits` class is instantiated.
668 666 klass : class, str, None
669 667 Values of this trait must be a subclass of klass. The klass
670 668 may be specified in a string like: 'foo.bar.MyClass'.
671 669 The string is resolved into real class, when the parent
672 670 :class:`HasTraits` class is instantiated.
673 671 allow_none : boolean
674 672 Indicates whether None is allowed as an assignable value. Even if
675 673 ``False``, the default value may be ``None``.
676 674 """
677 675 if default_value is None:
678 676 if klass is None:
679 677 klass = object
680 678 elif klass is None:
681 679 klass = default_value
682 680
683 681 if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
684 682 raise TraitError("A Type trait must specify a class.")
685 683
686 684 self.klass = klass
687 685 self._allow_none = allow_none
688 686
689 687 super(Type, self).__init__(default_value, **metadata)
690 688
691 689 def validate(self, obj, value):
692 690 """Validates that the value is a valid object instance."""
693 691 try:
694 692 if issubclass(value, self.klass):
695 693 return value
696 694 except:
697 695 if (value is None) and (self._allow_none):
698 696 return value
699 697
700 698 self.error(obj, value)
701 699
702 700 def info(self):
703 701 """ Returns a description of the trait."""
704 702 if isinstance(self.klass, py3compat.string_types):
705 703 klass = self.klass
706 704 else:
707 705 klass = self.klass.__name__
708 706 result = 'a subclass of ' + klass
709 707 if self._allow_none:
710 708 return result + ' or None'
711 709 return result
712 710
713 711 def instance_init(self, obj):
714 712 self._resolve_classes()
715 713 super(Type, self).instance_init(obj)
716 714
717 715 def _resolve_classes(self):
718 716 if isinstance(self.klass, py3compat.string_types):
719 717 self.klass = import_item(self.klass)
720 718 if isinstance(self.default_value, py3compat.string_types):
721 719 self.default_value = import_item(self.default_value)
722 720
723 721 def get_default_value(self):
724 722 return self.default_value
725 723
726 724
727 725 class DefaultValueGenerator(object):
728 726 """A class for generating new default value instances."""
729 727
730 728 def __init__(self, *args, **kw):
731 729 self.args = args
732 730 self.kw = kw
733 731
734 732 def generate(self, klass):
735 733 return klass(*self.args, **self.kw)
736 734
737 735
738 736 class Instance(ClassBasedTraitType):
739 737 """A trait whose value must be an instance of a specified class.
740 738
741 739 The value can also be an instance of a subclass of the specified class.
742 740 """
743 741
744 742 def __init__(self, klass=None, args=None, kw=None,
745 743 allow_none=True, **metadata ):
746 744 """Construct an Instance trait.
747 745
748 746 This trait allows values that are instances of a particular
749 747 class or its sublclasses. Our implementation is quite different
750 748 from that of enthough.traits as we don't allow instances to be used
751 749 for klass and we handle the ``args`` and ``kw`` arguments differently.
752 750
753 751 Parameters
754 752 ----------
755 753 klass : class, str
756 754 The class that forms the basis for the trait. Class names
757 755 can also be specified as strings, like 'foo.bar.Bar'.
758 756 args : tuple
759 757 Positional arguments for generating the default value.
760 758 kw : dict
761 759 Keyword arguments for generating the default value.
762 760 allow_none : bool
763 761 Indicates whether None is allowed as a value.
764 762
765 763 Default Value
766 764 -------------
767 765 If both ``args`` and ``kw`` are None, then the default value is None.
768 766 If ``args`` is a tuple and ``kw`` is a dict, then the default is
769 767 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
770 768 not (but not both), None is replace by ``()`` or ``{}``.
771 769 """
772 770
773 771 self._allow_none = allow_none
774 772
775 773 if (klass is None) or (not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types))):
776 774 raise TraitError('The klass argument must be a class'
777 775 ' you gave: %r' % klass)
778 776 self.klass = klass
779 777
780 778 # self.klass is a class, so handle default_value
781 779 if args is None and kw is None:
782 780 default_value = None
783 781 else:
784 782 if args is None:
785 783 # kw is not None
786 784 args = ()
787 785 elif kw is None:
788 786 # args is not None
789 787 kw = {}
790 788
791 789 if not isinstance(kw, dict):
792 790 raise TraitError("The 'kw' argument must be a dict or None.")
793 791 if not isinstance(args, tuple):
794 792 raise TraitError("The 'args' argument must be a tuple or None.")
795 793
796 794 default_value = DefaultValueGenerator(*args, **kw)
797 795
798 796 super(Instance, self).__init__(default_value, **metadata)
799 797
800 798 def validate(self, obj, value):
801 799 if value is None:
802 800 if self._allow_none:
803 801 return value
804 802 self.error(obj, value)
805 803
806 804 if isinstance(value, self.klass):
807 805 return value
808 806 else:
809 807 self.error(obj, value)
810 808
811 809 def info(self):
812 810 if isinstance(self.klass, py3compat.string_types):
813 811 klass = self.klass
814 812 else:
815 813 klass = self.klass.__name__
816 814 result = class_of(klass)
817 815 if self._allow_none:
818 816 return result + ' or None'
819 817
820 818 return result
821 819
822 820 def instance_init(self, obj):
823 821 self._resolve_classes()
824 822 super(Instance, self).instance_init(obj)
825 823
826 824 def _resolve_classes(self):
827 825 if isinstance(self.klass, py3compat.string_types):
828 826 self.klass = import_item(self.klass)
829 827
830 828 def get_default_value(self):
831 829 """Instantiate a default value instance.
832 830
833 831 This is called when the containing HasTraits classes'
834 832 :meth:`__new__` method is called to ensure that a unique instance
835 833 is created for each HasTraits instance.
836 834 """
837 835 dv = self.default_value
838 836 if isinstance(dv, DefaultValueGenerator):
839 837 return dv.generate(self.klass)
840 838 else:
841 839 return dv
842 840
843 841
844 842 class This(ClassBasedTraitType):
845 843 """A trait for instances of the class containing this trait.
846 844
847 845 Because how how and when class bodies are executed, the ``This``
848 846 trait can only have a default value of None. This, and because we
849 847 always validate default values, ``allow_none`` is *always* true.
850 848 """
851 849
852 850 info_text = 'an instance of the same type as the receiver or None'
853 851
854 852 def __init__(self, **metadata):
855 853 super(This, self).__init__(None, **metadata)
856 854
857 855 def validate(self, obj, value):
858 856 # What if value is a superclass of obj.__class__? This is
859 857 # complicated if it was the superclass that defined the This
860 858 # trait.
861 859 if isinstance(value, self.this_class) or (value is None):
862 860 return value
863 861 else:
864 862 self.error(obj, value)
865 863
866 864
867 865 #-----------------------------------------------------------------------------
868 866 # Basic TraitTypes implementations/subclasses
869 867 #-----------------------------------------------------------------------------
870 868
871 869
872 870 class Any(TraitType):
873 871 default_value = None
874 872 info_text = 'any value'
875 873
876 874
877 875 class Int(TraitType):
878 876 """An int trait."""
879 877
880 878 default_value = 0
881 879 info_text = 'an int'
882 880
883 881 def validate(self, obj, value):
884 882 if isinstance(value, int):
885 883 return value
886 884 self.error(obj, value)
887 885
888 886 class CInt(Int):
889 887 """A casting version of the int trait."""
890 888
891 889 def validate(self, obj, value):
892 890 try:
893 891 return int(value)
894 892 except:
895 893 self.error(obj, value)
896 894
897 895 if py3compat.PY3:
898 896 Long, CLong = Int, CInt
899 897 Integer = Int
900 898 else:
901 899 class Long(TraitType):
902 900 """A long integer trait."""
903 901
904 902 default_value = 0
905 903 info_text = 'a long'
906 904
907 905 def validate(self, obj, value):
908 906 if isinstance(value, long):
909 907 return value
910 908 if isinstance(value, int):
911 909 return long(value)
912 910 self.error(obj, value)
913 911
914 912
915 913 class CLong(Long):
916 914 """A casting version of the long integer trait."""
917 915
918 916 def validate(self, obj, value):
919 917 try:
920 918 return long(value)
921 919 except:
922 920 self.error(obj, value)
923 921
924 922 class Integer(TraitType):
925 923 """An integer trait.
926 924
927 925 Longs that are unnecessary (<= sys.maxint) are cast to ints."""
928 926
929 927 default_value = 0
930 928 info_text = 'an integer'
931 929
932 930 def validate(self, obj, value):
933 931 if isinstance(value, int):
934 932 return value
935 933 if isinstance(value, long):
936 934 # downcast longs that fit in int:
937 935 # note that int(n > sys.maxint) returns a long, so
938 936 # we don't need a condition on this cast
939 937 return int(value)
940 938 if sys.platform == "cli":
941 939 from System import Int64
942 940 if isinstance(value, Int64):
943 941 return int(value)
944 942 self.error(obj, value)
945 943
946 944
947 945 class Float(TraitType):
948 946 """A float trait."""
949 947
950 948 default_value = 0.0
951 949 info_text = 'a float'
952 950
953 951 def validate(self, obj, value):
954 952 if isinstance(value, float):
955 953 return value
956 954 if isinstance(value, int):
957 955 return float(value)
958 956 self.error(obj, value)
959 957
960 958
961 959 class CFloat(Float):
962 960 """A casting version of the float trait."""
963 961
964 962 def validate(self, obj, value):
965 963 try:
966 964 return float(value)
967 965 except:
968 966 self.error(obj, value)
969 967
970 968 class Complex(TraitType):
971 969 """A trait for complex numbers."""
972 970
973 971 default_value = 0.0 + 0.0j
974 972 info_text = 'a complex number'
975 973
976 974 def validate(self, obj, value):
977 975 if isinstance(value, complex):
978 976 return value
979 977 if isinstance(value, (float, int)):
980 978 return complex(value)
981 979 self.error(obj, value)
982 980
983 981
984 982 class CComplex(Complex):
985 983 """A casting version of the complex number trait."""
986 984
987 985 def validate (self, obj, value):
988 986 try:
989 987 return complex(value)
990 988 except:
991 989 self.error(obj, value)
992 990
993 991 # We should always be explicit about whether we're using bytes or unicode, both
994 992 # for Python 3 conversion and for reliable unicode behaviour on Python 2. So
995 993 # we don't have a Str type.
996 994 class Bytes(TraitType):
997 995 """A trait for byte strings."""
998 996
999 997 default_value = b''
1000 998 info_text = 'a string'
1001 999
1002 1000 def validate(self, obj, value):
1003 1001 if isinstance(value, bytes):
1004 1002 return value
1005 1003 self.error(obj, value)
1006 1004
1007 1005
1008 1006 class CBytes(Bytes):
1009 1007 """A casting version of the byte string trait."""
1010 1008
1011 1009 def validate(self, obj, value):
1012 1010 try:
1013 1011 return bytes(value)
1014 1012 except:
1015 1013 self.error(obj, value)
1016 1014
1017 1015
1018 1016 class Unicode(TraitType):
1019 1017 """A trait for unicode strings."""
1020 1018
1021 1019 default_value = u''
1022 1020 info_text = 'a unicode string'
1023 1021
1024 1022 def validate(self, obj, value):
1025 1023 if isinstance(value, py3compat.unicode_type):
1026 1024 return value
1027 1025 if isinstance(value, bytes):
1028 1026 return py3compat.unicode_type(value)
1029 1027 self.error(obj, value)
1030 1028
1031 1029
1032 1030 class CUnicode(Unicode):
1033 1031 """A casting version of the unicode trait."""
1034 1032
1035 1033 def validate(self, obj, value):
1036 1034 try:
1037 1035 return py3compat.unicode_type(value)
1038 1036 except:
1039 1037 self.error(obj, value)
1040 1038
1041 1039
1042 1040 class ObjectName(TraitType):
1043 1041 """A string holding a valid object name in this version of Python.
1044 1042
1045 1043 This does not check that the name exists in any scope."""
1046 1044 info_text = "a valid object identifier in Python"
1047 1045
1048 1046 if py3compat.PY3:
1049 1047 # Python 3:
1050 1048 coerce_str = staticmethod(lambda _,s: s)
1051 1049
1052 1050 else:
1053 1051 # Python 2:
1054 1052 def coerce_str(self, obj, value):
1055 1053 "In Python 2, coerce ascii-only unicode to str"
1056 1054 if isinstance(value, unicode):
1057 1055 try:
1058 1056 return str(value)
1059 1057 except UnicodeEncodeError:
1060 1058 self.error(obj, value)
1061 1059 return value
1062 1060
1063 1061 def validate(self, obj, value):
1064 1062 value = self.coerce_str(obj, value)
1065 1063
1066 1064 if isinstance(value, str) and py3compat.isidentifier(value):
1067 1065 return value
1068 1066 self.error(obj, value)
1069 1067
1070 1068 class DottedObjectName(ObjectName):
1071 1069 """A string holding a valid dotted object name in Python, such as A.b3._c"""
1072 1070 def validate(self, obj, value):
1073 1071 value = self.coerce_str(obj, value)
1074 1072
1075 1073 if isinstance(value, str) and py3compat.isidentifier(value, dotted=True):
1076 1074 return value
1077 1075 self.error(obj, value)
1078 1076
1079 1077
1080 1078 class Bool(TraitType):
1081 1079 """A boolean (True, False) trait."""
1082 1080
1083 1081 default_value = False
1084 1082 info_text = 'a boolean'
1085 1083
1086 1084 def validate(self, obj, value):
1087 1085 if isinstance(value, bool):
1088 1086 return value
1089 1087 self.error(obj, value)
1090 1088
1091 1089
1092 1090 class CBool(Bool):
1093 1091 """A casting version of the boolean trait."""
1094 1092
1095 1093 def validate(self, obj, value):
1096 1094 try:
1097 1095 return bool(value)
1098 1096 except:
1099 1097 self.error(obj, value)
1100 1098
1101 1099
1102 1100 class Enum(TraitType):
1103 1101 """An enum that whose value must be in a given sequence."""
1104 1102
1105 1103 def __init__(self, values, default_value=None, allow_none=True, **metadata):
1106 1104 self.values = values
1107 1105 self._allow_none = allow_none
1108 1106 super(Enum, self).__init__(default_value, **metadata)
1109 1107
1110 1108 def validate(self, obj, value):
1111 1109 if value is None:
1112 1110 if self._allow_none:
1113 1111 return value
1114 1112
1115 1113 if value in self.values:
1116 1114 return value
1117 1115 self.error(obj, value)
1118 1116
1119 1117 def info(self):
1120 1118 """ Returns a description of the trait."""
1121 1119 result = 'any of ' + repr(self.values)
1122 1120 if self._allow_none:
1123 1121 return result + ' or None'
1124 1122 return result
1125 1123
1126 1124 class CaselessStrEnum(Enum):
1127 1125 """An enum of strings that are caseless in validate."""
1128 1126
1129 1127 def validate(self, obj, value):
1130 1128 if value is None:
1131 1129 if self._allow_none:
1132 1130 return value
1133 1131
1134 1132 if not isinstance(value, py3compat.string_types):
1135 1133 self.error(obj, value)
1136 1134
1137 1135 for v in self.values:
1138 1136 if v.lower() == value.lower():
1139 1137 return v
1140 1138 self.error(obj, value)
1141 1139
1142 1140 class Container(Instance):
1143 1141 """An instance of a container (list, set, etc.)
1144 1142
1145 1143 To be subclassed by overriding klass.
1146 1144 """
1147 1145 klass = None
1148 1146 _valid_defaults = SequenceTypes
1149 1147 _trait = None
1150 1148
1151 1149 def __init__(self, trait=None, default_value=None, allow_none=True,
1152 1150 **metadata):
1153 1151 """Create a container trait type from a list, set, or tuple.
1154 1152
1155 1153 The default value is created by doing ``List(default_value)``,
1156 1154 which creates a copy of the ``default_value``.
1157 1155
1158 1156 ``trait`` can be specified, which restricts the type of elements
1159 1157 in the container to that TraitType.
1160 1158
1161 1159 If only one arg is given and it is not a Trait, it is taken as
1162 1160 ``default_value``:
1163 1161
1164 1162 ``c = List([1,2,3])``
1165 1163
1166 1164 Parameters
1167 1165 ----------
1168 1166
1169 1167 trait : TraitType [ optional ]
1170 1168 the type for restricting the contents of the Container. If unspecified,
1171 1169 types are not checked.
1172 1170
1173 1171 default_value : SequenceType [ optional ]
1174 1172 The default value for the Trait. Must be list/tuple/set, and
1175 1173 will be cast to the container type.
1176 1174
1177 1175 allow_none : Bool [ default True ]
1178 1176 Whether to allow the value to be None
1179 1177
1180 1178 **metadata : any
1181 1179 further keys for extensions to the Trait (e.g. config)
1182 1180
1183 1181 """
1184 1182 # allow List([values]):
1185 1183 if default_value is None and not is_trait(trait):
1186 1184 default_value = trait
1187 1185 trait = None
1188 1186
1189 1187 if default_value is None:
1190 1188 args = ()
1191 1189 elif isinstance(default_value, self._valid_defaults):
1192 1190 args = (default_value,)
1193 1191 else:
1194 1192 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
1195 1193
1196 1194 if is_trait(trait):
1197 1195 self._trait = trait() if isinstance(trait, type) else trait
1198 1196 self._trait.name = 'element'
1199 1197 elif trait is not None:
1200 1198 raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait))
1201 1199
1202 1200 super(Container,self).__init__(klass=self.klass, args=args,
1203 1201 allow_none=allow_none, **metadata)
1204 1202
1205 1203 def element_error(self, obj, element, validator):
1206 1204 e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
1207 1205 % (self.name, class_of(obj), validator.info(), repr_type(element))
1208 1206 raise TraitError(e)
1209 1207
1210 1208 def validate(self, obj, value):
1211 1209 value = super(Container, self).validate(obj, value)
1212 1210 if value is None:
1213 1211 return value
1214 1212
1215 1213 value = self.validate_elements(obj, value)
1216 1214
1217 1215 return value
1218 1216
1219 1217 def validate_elements(self, obj, value):
1220 1218 validated = []
1221 1219 if self._trait is None or isinstance(self._trait, Any):
1222 1220 return value
1223 1221 for v in value:
1224 1222 try:
1225 1223 v = self._trait.validate(obj, v)
1226 1224 except TraitError:
1227 1225 self.element_error(obj, v, self._trait)
1228 1226 else:
1229 1227 validated.append(v)
1230 1228 return self.klass(validated)
1231 1229
1232 1230
1233 1231 class List(Container):
1234 1232 """An instance of a Python list."""
1235 1233 klass = list
1236 1234
1237 1235 def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize,
1238 1236 allow_none=True, **metadata):
1239 1237 """Create a List trait type from a list, set, or tuple.
1240 1238
1241 1239 The default value is created by doing ``List(default_value)``,
1242 1240 which creates a copy of the ``default_value``.
1243 1241
1244 1242 ``trait`` can be specified, which restricts the type of elements
1245 1243 in the container to that TraitType.
1246 1244
1247 1245 If only one arg is given and it is not a Trait, it is taken as
1248 1246 ``default_value``:
1249 1247
1250 1248 ``c = List([1,2,3])``
1251 1249
1252 1250 Parameters
1253 1251 ----------
1254 1252
1255 1253 trait : TraitType [ optional ]
1256 1254 the type for restricting the contents of the Container. If unspecified,
1257 1255 types are not checked.
1258 1256
1259 1257 default_value : SequenceType [ optional ]
1260 1258 The default value for the Trait. Must be list/tuple/set, and
1261 1259 will be cast to the container type.
1262 1260
1263 1261 minlen : Int [ default 0 ]
1264 1262 The minimum length of the input list
1265 1263
1266 1264 maxlen : Int [ default sys.maxsize ]
1267 1265 The maximum length of the input list
1268 1266
1269 1267 allow_none : Bool [ default True ]
1270 1268 Whether to allow the value to be None
1271 1269
1272 1270 **metadata : any
1273 1271 further keys for extensions to the Trait (e.g. config)
1274 1272
1275 1273 """
1276 1274 self._minlen = minlen
1277 1275 self._maxlen = maxlen
1278 1276 super(List, self).__init__(trait=trait, default_value=default_value,
1279 1277 allow_none=allow_none, **metadata)
1280 1278
1281 1279 def length_error(self, obj, value):
1282 1280 e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
1283 1281 % (self.name, class_of(obj), self._minlen, self._maxlen, value)
1284 1282 raise TraitError(e)
1285 1283
1286 1284 def validate_elements(self, obj, value):
1287 1285 length = len(value)
1288 1286 if length < self._minlen or length > self._maxlen:
1289 1287 self.length_error(obj, value)
1290 1288
1291 1289 return super(List, self).validate_elements(obj, value)
1292 1290
1293 1291
1294 1292 class Set(Container):
1295 1293 """An instance of a Python set."""
1296 1294 klass = set
1297 1295
1298 1296 class Tuple(Container):
1299 1297 """An instance of a Python tuple."""
1300 1298 klass = tuple
1301 1299
1302 1300 def __init__(self, *traits, **metadata):
1303 1301 """Tuple(*traits, default_value=None, allow_none=True, **medatata)
1304 1302
1305 1303 Create a tuple from a list, set, or tuple.
1306 1304
1307 1305 Create a fixed-type tuple with Traits:
1308 1306
1309 1307 ``t = Tuple(Int, Str, CStr)``
1310 1308
1311 1309 would be length 3, with Int,Str,CStr for each element.
1312 1310
1313 1311 If only one arg is given and it is not a Trait, it is taken as
1314 1312 default_value:
1315 1313
1316 1314 ``t = Tuple((1,2,3))``
1317 1315
1318 1316 Otherwise, ``default_value`` *must* be specified by keyword.
1319 1317
1320 1318 Parameters
1321 1319 ----------
1322 1320
1323 1321 *traits : TraitTypes [ optional ]
1324 1322 the tsype for restricting the contents of the Tuple. If unspecified,
1325 1323 types are not checked. If specified, then each positional argument
1326 1324 corresponds to an element of the tuple. Tuples defined with traits
1327 1325 are of fixed length.
1328 1326
1329 1327 default_value : SequenceType [ optional ]
1330 1328 The default value for the Tuple. Must be list/tuple/set, and
1331 1329 will be cast to a tuple. If `traits` are specified, the
1332 1330 `default_value` must conform to the shape and type they specify.
1333 1331
1334 1332 allow_none : Bool [ default True ]
1335 1333 Whether to allow the value to be None
1336 1334
1337 1335 **metadata : any
1338 1336 further keys for extensions to the Trait (e.g. config)
1339 1337
1340 1338 """
1341 1339 default_value = metadata.pop('default_value', None)
1342 1340 allow_none = metadata.pop('allow_none', True)
1343 1341
1344 1342 # allow Tuple((values,)):
1345 1343 if len(traits) == 1 and default_value is None and not is_trait(traits[0]):
1346 1344 default_value = traits[0]
1347 1345 traits = ()
1348 1346
1349 1347 if default_value is None:
1350 1348 args = ()
1351 1349 elif isinstance(default_value, self._valid_defaults):
1352 1350 args = (default_value,)
1353 1351 else:
1354 1352 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
1355 1353
1356 1354 self._traits = []
1357 1355 for trait in traits:
1358 1356 t = trait() if isinstance(trait, type) else trait
1359 1357 t.name = 'element'
1360 1358 self._traits.append(t)
1361 1359
1362 1360 if self._traits and default_value is None:
1363 1361 # don't allow default to be an empty container if length is specified
1364 1362 args = None
1365 1363 super(Container,self).__init__(klass=self.klass, args=args,
1366 1364 allow_none=allow_none, **metadata)
1367 1365
1368 1366 def validate_elements(self, obj, value):
1369 1367 if not self._traits:
1370 1368 # nothing to validate
1371 1369 return value
1372 1370 if len(value) != len(self._traits):
1373 1371 e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
1374 1372 % (self.name, class_of(obj), len(self._traits), repr_type(value))
1375 1373 raise TraitError(e)
1376 1374
1377 1375 validated = []
1378 1376 for t,v in zip(self._traits, value):
1379 1377 try:
1380 1378 v = t.validate(obj, v)
1381 1379 except TraitError:
1382 1380 self.element_error(obj, v, t)
1383 1381 else:
1384 1382 validated.append(v)
1385 1383 return tuple(validated)
1386 1384
1387 1385
1388 1386 class Dict(Instance):
1389 1387 """An instance of a Python dict."""
1390 1388
1391 1389 def __init__(self, default_value=None, allow_none=True, **metadata):
1392 1390 """Create a dict trait type from a dict.
1393 1391
1394 1392 The default value is created by doing ``dict(default_value)``,
1395 1393 which creates a copy of the ``default_value``.
1396 1394 """
1397 1395 if default_value is None:
1398 1396 args = ((),)
1399 1397 elif isinstance(default_value, dict):
1400 1398 args = (default_value,)
1401 1399 elif isinstance(default_value, SequenceTypes):
1402 1400 args = (default_value,)
1403 1401 else:
1404 1402 raise TypeError('default value of Dict was %s' % default_value)
1405 1403
1406 1404 super(Dict,self).__init__(klass=dict, args=args,
1407 1405 allow_none=allow_none, **metadata)
1408 1406
1409 1407 class TCPAddress(TraitType):
1410 1408 """A trait for an (ip, port) tuple.
1411 1409
1412 1410 This allows for both IPv4 IP addresses as well as hostnames.
1413 1411 """
1414 1412
1415 1413 default_value = ('127.0.0.1', 0)
1416 1414 info_text = 'an (ip, port) tuple'
1417 1415
1418 1416 def validate(self, obj, value):
1419 1417 if isinstance(value, tuple):
1420 1418 if len(value) == 2:
1421 1419 if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int):
1422 1420 port = value[1]
1423 1421 if port >= 0 and port <= 65535:
1424 1422 return value
1425 1423 self.error(obj, value)
1426 1424
1427 1425 class CRegExp(TraitType):
1428 1426 """A casting compiled regular expression trait.
1429 1427
1430 1428 Accepts both strings and compiled regular expressions. The resulting
1431 1429 attribute will be a compiled regular expression."""
1432 1430
1433 1431 info_text = 'a regular expression'
1434 1432
1435 1433 def validate(self, obj, value):
1436 1434 try:
1437 1435 return re.compile(value)
1438 1436 except:
1439 1437 self.error(obj, value)
General Comments 0
You need to be logged in to leave comments. Login now