##// END OF EJS Templates
Merge pull request #12832 from meeseeksmachine/auto-backport-of-pr-12824-on-7.x...
Matthias Bussonnier -
r26346:97d6baa8 merge
parent child Browse files
Show More
@@ -1,2101 +1,2111 b''
1 1 """Completion for IPython.
2 2
3 3 This module started as fork of the rlcompleter module in the Python standard
4 4 library. The original enhancements made to rlcompleter have been sent
5 5 upstream and were accepted as of Python 2.3,
6 6
7 7 This module now support a wide variety of completion mechanism both available
8 8 for normal classic Python code, as well as completer for IPython specific
9 9 Syntax like magics.
10 10
11 11 Latex and Unicode completion
12 12 ============================
13 13
14 14 IPython and compatible frontends not only can complete your code, but can help
15 15 you to input a wide range of characters. In particular we allow you to insert
16 16 a unicode character using the tab completion mechanism.
17 17
18 18 Forward latex/unicode completion
19 19 --------------------------------
20 20
21 21 Forward completion allows you to easily type a unicode character using its latex
22 22 name, or unicode long description. To do so type a backslash follow by the
23 23 relevant name and press tab:
24 24
25 25
26 26 Using latex completion:
27 27
28 28 .. code::
29 29
30 30 \\alpha<tab>
31 31 Ξ±
32 32
33 33 or using unicode completion:
34 34
35 35
36 36 .. code::
37 37
38 38 \\greek small letter alpha<tab>
39 39 Ξ±
40 40
41 41
42 42 Only valid Python identifiers will complete. Combining characters (like arrow or
43 43 dots) are also available, unlike latex they need to be put after the their
44 44 counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`.
45 45
46 46 Some browsers are known to display combining characters incorrectly.
47 47
48 48 Backward latex completion
49 49 -------------------------
50 50
51 51 It is sometime challenging to know how to type a character, if you are using
52 52 IPython, or any compatible frontend you can prepend backslash to the character
53 53 and press `<tab>` to expand it to its latex form.
54 54
55 55 .. code::
56 56
57 57 \\Ξ±<tab>
58 58 \\alpha
59 59
60 60
61 61 Both forward and backward completions can be deactivated by setting the
62 62 ``Completer.backslash_combining_completions`` option to ``False``.
63 63
64 64
65 65 Experimental
66 66 ============
67 67
68 68 Starting with IPython 6.0, this module can make use of the Jedi library to
69 69 generate completions both using static analysis of the code, and dynamically
70 70 inspecting multiple namespaces. Jedi is an autocompletion and static analysis
71 71 for Python. The APIs attached to this new mechanism is unstable and will
72 72 raise unless use in an :any:`provisionalcompleter` context manager.
73 73
74 74 You will find that the following are experimental:
75 75
76 76 - :any:`provisionalcompleter`
77 77 - :any:`IPCompleter.completions`
78 78 - :any:`Completion`
79 79 - :any:`rectify_completions`
80 80
81 81 .. note::
82 82
83 83 better name for :any:`rectify_completions` ?
84 84
85 85 We welcome any feedback on these new API, and we also encourage you to try this
86 86 module in debug mode (start IPython with ``--Completer.debug=True``) in order
87 87 to have extra logging information if :any:`jedi` is crashing, or if current
88 88 IPython completer pending deprecations are returning results not yet handled
89 89 by :any:`jedi`
90 90
91 91 Using Jedi for tab completion allow snippets like the following to work without
92 92 having to execute any code:
93 93
94 94 >>> myvar = ['hello', 42]
95 95 ... myvar[1].bi<tab>
96 96
97 97 Tab completion will be able to infer that ``myvar[1]`` is a real number without
98 98 executing any code unlike the previously available ``IPCompleter.greedy``
99 99 option.
100 100
101 101 Be sure to update :any:`jedi` to the latest stable version or to try the
102 102 current development version to get better completions.
103 103 """
104 104
105 105
106 106 # Copyright (c) IPython Development Team.
107 107 # Distributed under the terms of the Modified BSD License.
108 108 #
109 109 # Some of this code originated from rlcompleter in the Python standard library
110 110 # Copyright (C) 2001 Python Software Foundation, www.python.org
111 111
112 112
113 113 import builtins as builtin_mod
114 114 import glob
115 115 import inspect
116 116 import itertools
117 117 import keyword
118 118 import os
119 119 import re
120 120 import string
121 121 import sys
122 122 import time
123 123 import unicodedata
124 124 import warnings
125 125 from contextlib import contextmanager
126 126 from importlib import import_module
127 127 from types import SimpleNamespace
128 128 from typing import Iterable, Iterator, List, Tuple
129 129
130 130 from IPython.core.error import TryNext
131 131 from IPython.core.inputtransformer2 import ESC_MAGIC
132 132 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
133 133 from IPython.core.oinspect import InspectColors
134 134 from IPython.utils import generics
135 135 from IPython.utils.dir2 import dir2, get_real_method
136 136 from IPython.utils.process import arg_split
137 137 from traitlets import Bool, Enum, Int, observe
138 138 from traitlets.config.configurable import Configurable
139 139
140 140 import __main__
141 141
142 142 # skip module docstests
143 143 skip_doctest = True
144 144
145 145 try:
146 146 import jedi
147 147 jedi.settings.case_insensitive_completion = False
148 148 import jedi.api.helpers
149 149 import jedi.api.classes
150 150 JEDI_INSTALLED = True
151 151 except ImportError:
152 152 JEDI_INSTALLED = False
153 153 #-----------------------------------------------------------------------------
154 154 # Globals
155 155 #-----------------------------------------------------------------------------
156 156
157 157 # Public API
158 158 __all__ = ['Completer','IPCompleter']
159 159
160 160 if sys.platform == 'win32':
161 161 PROTECTABLES = ' '
162 162 else:
163 163 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
164 164
165 165 # Protect against returning an enormous number of completions which the frontend
166 166 # may have trouble processing.
167 167 MATCHES_LIMIT = 500
168 168
169 169 _deprecation_readline_sentinel = object()
170 170
171 171
172 172 class ProvisionalCompleterWarning(FutureWarning):
173 173 """
174 174 Exception raise by an experimental feature in this module.
175 175
176 176 Wrap code in :any:`provisionalcompleter` context manager if you
177 177 are certain you want to use an unstable feature.
178 178 """
179 179 pass
180 180
181 181 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
182 182
183 183 @contextmanager
184 184 def provisionalcompleter(action='ignore'):
185 185 """
186 186
187 187
188 188 This context manager has to be used in any place where unstable completer
189 189 behavior and API may be called.
190 190
191 191 >>> with provisionalcompleter():
192 192 ... completer.do_experimental_things() # works
193 193
194 194 >>> completer.do_experimental_things() # raises.
195 195
196 .. note:: Unstable
196 .. note::
197
198 Unstable
197 199
198 200 By using this context manager you agree that the API in use may change
199 201 without warning, and that you won't complain if they do so.
200 202
201 203 You also understand that, if the API is not to your liking, you should report
202 204 a bug to explain your use case upstream.
203 205
204 206 We'll be happy to get your feedback, feature requests, and improvements on
205 207 any of the unstable APIs!
206 208 """
207 209 with warnings.catch_warnings():
208 210 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
209 211 yield
210 212
211 213
212 214 def has_open_quotes(s):
213 215 """Return whether a string has open quotes.
214 216
215 217 This simply counts whether the number of quote characters of either type in
216 218 the string is odd.
217 219
218 220 Returns
219 221 -------
220 222 If there is an open quote, the quote character is returned. Else, return
221 223 False.
222 224 """
223 225 # We check " first, then ', so complex cases with nested quotes will get
224 226 # the " to take precedence.
225 227 if s.count('"') % 2:
226 228 return '"'
227 229 elif s.count("'") % 2:
228 230 return "'"
229 231 else:
230 232 return False
231 233
232 234
233 235 def protect_filename(s, protectables=PROTECTABLES):
234 236 """Escape a string to protect certain characters."""
235 237 if set(s) & set(protectables):
236 238 if sys.platform == "win32":
237 239 return '"' + s + '"'
238 240 else:
239 241 return "".join(("\\" + c if c in protectables else c) for c in s)
240 242 else:
241 243 return s
242 244
243 245
244 246 def expand_user(path:str) -> Tuple[str, bool, str]:
245 247 """Expand ``~``-style usernames in strings.
246 248
247 249 This is similar to :func:`os.path.expanduser`, but it computes and returns
248 250 extra information that will be useful if the input was being used in
249 251 computing completions, and you wish to return the completions with the
250 252 original '~' instead of its expanded value.
251 253
252 254 Parameters
253 255 ----------
254 256 path : str
255 257 String to be expanded. If no ~ is present, the output is the same as the
256 258 input.
257 259
258 260 Returns
259 261 -------
260 262 newpath : str
261 263 Result of ~ expansion in the input path.
262 264 tilde_expand : bool
263 265 Whether any expansion was performed or not.
264 266 tilde_val : str
265 267 The value that ~ was replaced with.
266 268 """
267 269 # Default values
268 270 tilde_expand = False
269 271 tilde_val = ''
270 272 newpath = path
271 273
272 274 if path.startswith('~'):
273 275 tilde_expand = True
274 276 rest = len(path)-1
275 277 newpath = os.path.expanduser(path)
276 278 if rest:
277 279 tilde_val = newpath[:-rest]
278 280 else:
279 281 tilde_val = newpath
280 282
281 283 return newpath, tilde_expand, tilde_val
282 284
283 285
284 286 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
285 287 """Does the opposite of expand_user, with its outputs.
286 288 """
287 289 if tilde_expand:
288 290 return path.replace(tilde_val, '~')
289 291 else:
290 292 return path
291 293
292 294
293 295 def completions_sorting_key(word):
294 296 """key for sorting completions
295 297
296 298 This does several things:
297 299
298 300 - Demote any completions starting with underscores to the end
299 301 - Insert any %magic and %%cellmagic completions in the alphabetical order
300 302 by their name
301 303 """
302 304 prio1, prio2 = 0, 0
303 305
304 306 if word.startswith('__'):
305 307 prio1 = 2
306 308 elif word.startswith('_'):
307 309 prio1 = 1
308 310
309 311 if word.endswith('='):
310 312 prio1 = -1
311 313
312 314 if word.startswith('%%'):
313 315 # If there's another % in there, this is something else, so leave it alone
314 316 if not "%" in word[2:]:
315 317 word = word[2:]
316 318 prio2 = 2
317 319 elif word.startswith('%'):
318 320 if not "%" in word[1:]:
319 321 word = word[1:]
320 322 prio2 = 1
321 323
322 324 return prio1, word, prio2
323 325
324 326
325 327 class _FakeJediCompletion:
326 328 """
327 329 This is a workaround to communicate to the UI that Jedi has crashed and to
328 330 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
329 331
330 332 Added in IPython 6.0 so should likely be removed for 7.0
331 333
332 334 """
333 335
334 336 def __init__(self, name):
335 337
336 338 self.name = name
337 339 self.complete = name
338 340 self.type = 'crashed'
339 341 self.name_with_symbols = name
340 342 self.signature = ''
341 343 self._origin = 'fake'
342 344
343 345 def __repr__(self):
344 346 return '<Fake completion object jedi has crashed>'
345 347
346 348
347 349 class Completion:
348 350 """
349 351 Completion object used and return by IPython completers.
350 352
351 .. warning:: Unstable
353 .. warning::
354
355 Unstable
352 356
353 357 This function is unstable, API may change without warning.
354 358 It will also raise unless use in proper context manager.
355 359
356 360 This act as a middle ground :any:`Completion` object between the
357 361 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
358 362 object. While Jedi need a lot of information about evaluator and how the
359 363 code should be ran/inspected, PromptToolkit (and other frontend) mostly
360 364 need user facing information.
361 365
362 366 - Which range should be replaced replaced by what.
363 367 - Some metadata (like completion type), or meta information to displayed to
364 368 the use user.
365 369
366 370 For debugging purpose we can also store the origin of the completion (``jedi``,
367 371 ``IPython.python_matches``, ``IPython.magics_matches``...).
368 372 """
369 373
370 374 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
371 375
372 376 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
373 377 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
374 378 "It may change without warnings. "
375 379 "Use in corresponding context manager.",
376 380 category=ProvisionalCompleterWarning, stacklevel=2)
377 381
378 382 self.start = start
379 383 self.end = end
380 384 self.text = text
381 385 self.type = type
382 386 self.signature = signature
383 387 self._origin = _origin
384 388
385 389 def __repr__(self):
386 390 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
387 391 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
388 392
389 393 def __eq__(self, other)->Bool:
390 394 """
391 395 Equality and hash do not hash the type (as some completer may not be
392 396 able to infer the type), but are use to (partially) de-duplicate
393 397 completion.
394 398
395 399 Completely de-duplicating completion is a bit tricker that just
396 400 comparing as it depends on surrounding text, which Completions are not
397 401 aware of.
398 402 """
399 403 return self.start == other.start and \
400 404 self.end == other.end and \
401 405 self.text == other.text
402 406
403 407 def __hash__(self):
404 408 return hash((self.start, self.end, self.text))
405 409
406 410
407 411 _IC = Iterable[Completion]
408 412
409 413
410 414 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
411 415 """
412 416 Deduplicate a set of completions.
413 417
414 .. warning:: Unstable
418 .. warning::
419
420 Unstable
415 421
416 422 This function is unstable, API may change without warning.
417 423
418 424 Parameters
419 425 ----------
420 426 text: str
421 427 text that should be completed.
422 428 completions: Iterator[Completion]
423 429 iterator over the completions to deduplicate
424 430
425 431 Yields
426 432 ------
427 433 `Completions` objects
428 434
429 435
430 436 Completions coming from multiple sources, may be different but end up having
431 437 the same effect when applied to ``text``. If this is the case, this will
432 438 consider completions as equal and only emit the first encountered.
433 439
434 440 Not folded in `completions()` yet for debugging purpose, and to detect when
435 441 the IPython completer does return things that Jedi does not, but should be
436 442 at some point.
437 443 """
438 444 completions = list(completions)
439 445 if not completions:
440 446 return
441 447
442 448 new_start = min(c.start for c in completions)
443 449 new_end = max(c.end for c in completions)
444 450
445 451 seen = set()
446 452 for c in completions:
447 453 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
448 454 if new_text not in seen:
449 455 yield c
450 456 seen.add(new_text)
451 457
452 458
453 459 def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC:
454 460 """
455 461 Rectify a set of completions to all have the same ``start`` and ``end``
456 462
457 .. warning:: Unstable
463 .. warning::
464
465 Unstable
458 466
459 467 This function is unstable, API may change without warning.
460 468 It will also raise unless use in proper context manager.
461 469
462 470 Parameters
463 471 ----------
464 472 text: str
465 473 text that should be completed.
466 474 completions: Iterator[Completion]
467 475 iterator over the completions to rectify
468 476
469 477
470 478 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
471 479 the Jupyter Protocol requires them to behave like so. This will readjust
472 480 the completion to have the same ``start`` and ``end`` by padding both
473 481 extremities with surrounding text.
474 482
475 483 During stabilisation should support a ``_debug`` option to log which
476 484 completion are return by the IPython completer and not found in Jedi in
477 485 order to make upstream bug report.
478 486 """
479 487 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
480 488 "It may change without warnings. "
481 489 "Use in corresponding context manager.",
482 490 category=ProvisionalCompleterWarning, stacklevel=2)
483 491
484 492 completions = list(completions)
485 493 if not completions:
486 494 return
487 495 starts = (c.start for c in completions)
488 496 ends = (c.end for c in completions)
489 497
490 498 new_start = min(starts)
491 499 new_end = max(ends)
492 500
493 501 seen_jedi = set()
494 502 seen_python_matches = set()
495 503 for c in completions:
496 504 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
497 505 if c._origin == 'jedi':
498 506 seen_jedi.add(new_text)
499 507 elif c._origin == 'IPCompleter.python_matches':
500 508 seen_python_matches.add(new_text)
501 509 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
502 510 diff = seen_python_matches.difference(seen_jedi)
503 511 if diff and _debug:
504 512 print('IPython.python matches have extras:', diff)
505 513
506 514
507 515 if sys.platform == 'win32':
508 516 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
509 517 else:
510 518 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
511 519
512 520 GREEDY_DELIMS = ' =\r\n'
513 521
514 522
515 523 class CompletionSplitter(object):
516 524 """An object to split an input line in a manner similar to readline.
517 525
518 526 By having our own implementation, we can expose readline-like completion in
519 527 a uniform manner to all frontends. This object only needs to be given the
520 528 line of text to be split and the cursor position on said line, and it
521 529 returns the 'word' to be completed on at the cursor after splitting the
522 530 entire line.
523 531
524 532 What characters are used as splitting delimiters can be controlled by
525 533 setting the ``delims`` attribute (this is a property that internally
526 534 automatically builds the necessary regular expression)"""
527 535
528 536 # Private interface
529 537
530 538 # A string of delimiter characters. The default value makes sense for
531 539 # IPython's most typical usage patterns.
532 540 _delims = DELIMS
533 541
534 542 # The expression (a normal string) to be compiled into a regular expression
535 543 # for actual splitting. We store it as an attribute mostly for ease of
536 544 # debugging, since this type of code can be so tricky to debug.
537 545 _delim_expr = None
538 546
539 547 # The regular expression that does the actual splitting
540 548 _delim_re = None
541 549
542 550 def __init__(self, delims=None):
543 551 delims = CompletionSplitter._delims if delims is None else delims
544 552 self.delims = delims
545 553
546 554 @property
547 555 def delims(self):
548 556 """Return the string of delimiter characters."""
549 557 return self._delims
550 558
551 559 @delims.setter
552 560 def delims(self, delims):
553 561 """Set the delimiters for line splitting."""
554 562 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
555 563 self._delim_re = re.compile(expr)
556 564 self._delims = delims
557 565 self._delim_expr = expr
558 566
559 567 def split_line(self, line, cursor_pos=None):
560 568 """Split a line of text with a cursor at the given position.
561 569 """
562 570 l = line if cursor_pos is None else line[:cursor_pos]
563 571 return self._delim_re.split(l)[-1]
564 572
565 573
566 574
567 575 class Completer(Configurable):
568 576
569 577 greedy = Bool(False,
570 578 help="""Activate greedy completion
571 579 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
572 580
573 581 This will enable completion on elements of lists, results of function calls, etc.,
574 582 but can be unsafe because the code is actually evaluated on TAB.
575 583 """
576 584 ).tag(config=True)
577 585
578 586 use_jedi = Bool(default_value=JEDI_INSTALLED,
579 587 help="Experimental: Use Jedi to generate autocompletions. "
580 588 "Default to True if jedi is installed.").tag(config=True)
581 589
582 590 jedi_compute_type_timeout = Int(default_value=400,
583 591 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
584 592 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
585 593 performance by preventing jedi to build its cache.
586 594 """).tag(config=True)
587 595
588 596 debug = Bool(default_value=False,
589 597 help='Enable debug for the Completer. Mostly print extra '
590 598 'information for experimental jedi integration.')\
591 599 .tag(config=True)
592 600
593 601 backslash_combining_completions = Bool(True,
594 602 help="Enable unicode completions, e.g. \\alpha<tab> . "
595 603 "Includes completion of latex commands, unicode names, and expanding "
596 604 "unicode characters back to latex commands.").tag(config=True)
597 605
598 606
599 607
600 608 def __init__(self, namespace=None, global_namespace=None, **kwargs):
601 609 """Create a new completer for the command line.
602 610
603 611 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
604 612
605 613 If unspecified, the default namespace where completions are performed
606 614 is __main__ (technically, __main__.__dict__). Namespaces should be
607 615 given as dictionaries.
608 616
609 617 An optional second namespace can be given. This allows the completer
610 618 to handle cases where both the local and global scopes need to be
611 619 distinguished.
612 620 """
613 621
614 622 # Don't bind to namespace quite yet, but flag whether the user wants a
615 623 # specific namespace or to use __main__.__dict__. This will allow us
616 624 # to bind to __main__.__dict__ at completion time, not now.
617 625 if namespace is None:
618 626 self.use_main_ns = True
619 627 else:
620 628 self.use_main_ns = False
621 629 self.namespace = namespace
622 630
623 631 # The global namespace, if given, can be bound directly
624 632 if global_namespace is None:
625 633 self.global_namespace = {}
626 634 else:
627 635 self.global_namespace = global_namespace
628 636
629 637 self.custom_matchers = []
630 638
631 639 super(Completer, self).__init__(**kwargs)
632 640
633 641 def complete(self, text, state):
634 642 """Return the next possible completion for 'text'.
635 643
636 644 This is called successively with state == 0, 1, 2, ... until it
637 645 returns None. The completion should begin with 'text'.
638 646
639 647 """
640 648 if self.use_main_ns:
641 649 self.namespace = __main__.__dict__
642 650
643 651 if state == 0:
644 652 if "." in text:
645 653 self.matches = self.attr_matches(text)
646 654 else:
647 655 self.matches = self.global_matches(text)
648 656 try:
649 657 return self.matches[state]
650 658 except IndexError:
651 659 return None
652 660
653 661 def global_matches(self, text):
654 662 """Compute matches when text is a simple name.
655 663
656 664 Return a list of all keywords, built-in functions and names currently
657 665 defined in self.namespace or self.global_namespace that match.
658 666
659 667 """
660 668 matches = []
661 669 match_append = matches.append
662 670 n = len(text)
663 671 for lst in [keyword.kwlist,
664 672 builtin_mod.__dict__.keys(),
665 673 self.namespace.keys(),
666 674 self.global_namespace.keys()]:
667 675 for word in lst:
668 676 if word[:n] == text and word != "__builtins__":
669 677 match_append(word)
670 678
671 679 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
672 680 for lst in [self.namespace.keys(),
673 681 self.global_namespace.keys()]:
674 682 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
675 683 for word in lst if snake_case_re.match(word)}
676 684 for word in shortened.keys():
677 685 if word[:n] == text and word != "__builtins__":
678 686 match_append(shortened[word])
679 687 return matches
680 688
681 689 def attr_matches(self, text):
682 690 """Compute matches when text contains a dot.
683 691
684 692 Assuming the text is of the form NAME.NAME....[NAME], and is
685 693 evaluatable in self.namespace or self.global_namespace, it will be
686 694 evaluated and its attributes (as revealed by dir()) are used as
687 695 possible completions. (For class instances, class members are
688 696 also considered.)
689 697
690 698 WARNING: this can still invoke arbitrary C code, if an object
691 699 with a __getattr__ hook is evaluated.
692 700
693 701 """
694 702
695 703 # Another option, seems to work great. Catches things like ''.<tab>
696 704 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
697 705
698 706 if m:
699 707 expr, attr = m.group(1, 3)
700 708 elif self.greedy:
701 709 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
702 710 if not m2:
703 711 return []
704 712 expr, attr = m2.group(1,2)
705 713 else:
706 714 return []
707 715
708 716 try:
709 717 obj = eval(expr, self.namespace)
710 718 except:
711 719 try:
712 720 obj = eval(expr, self.global_namespace)
713 721 except:
714 722 return []
715 723
716 724 if self.limit_to__all__ and hasattr(obj, '__all__'):
717 725 words = get__all__entries(obj)
718 726 else:
719 727 words = dir2(obj)
720 728
721 729 try:
722 730 words = generics.complete_object(obj, words)
723 731 except TryNext:
724 732 pass
725 733 except AssertionError:
726 734 raise
727 735 except Exception:
728 736 # Silence errors from completion function
729 737 #raise # dbg
730 738 pass
731 739 # Build match list to return
732 740 n = len(attr)
733 741 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
734 742
735 743
736 744 def get__all__entries(obj):
737 745 """returns the strings in the __all__ attribute"""
738 746 try:
739 747 words = getattr(obj, '__all__')
740 748 except:
741 749 return []
742 750
743 751 return [w for w in words if isinstance(w, str)]
744 752
745 753
746 754 def match_dict_keys(keys: List[str], prefix: str, delims: str):
747 755 """Used by dict_key_matches, matching the prefix to a list of keys
748 756
749 757 Parameters
750 758 ==========
751 759 keys:
752 760 list of keys in dictionary currently being completed.
753 761 prefix:
754 762 Part of the text already typed by the user. e.g. `mydict[b'fo`
755 763 delims:
756 764 String of delimiters to consider when finding the current key.
757 765
758 766 Returns
759 767 =======
760 768
761 769 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
762 770 ``quote`` being the quote that need to be used to close current string.
763 771 ``token_start`` the position where the replacement should start occurring,
764 772 ``matches`` a list of replacement/completion
765 773
766 774 """
767 775 if not prefix:
768 776 return None, 0, [repr(k) for k in keys
769 777 if isinstance(k, (str, bytes))]
770 778 quote_match = re.search('["\']', prefix)
771 779 quote = quote_match.group()
772 780 try:
773 781 prefix_str = eval(prefix + quote, {})
774 782 except Exception:
775 783 return None, 0, []
776 784
777 785 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
778 786 token_match = re.search(pattern, prefix, re.UNICODE)
779 787 token_start = token_match.start()
780 788 token_prefix = token_match.group()
781 789
782 790 matched = []
783 791 for key in keys:
784 792 try:
785 793 if not key.startswith(prefix_str):
786 794 continue
787 795 except (AttributeError, TypeError, UnicodeError):
788 796 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
789 797 continue
790 798
791 799 # reformat remainder of key to begin with prefix
792 800 rem = key[len(prefix_str):]
793 801 # force repr wrapped in '
794 802 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
795 803 if rem_repr.startswith('u') and prefix[0] not in 'uU':
796 804 # Found key is unicode, but prefix is Py2 string.
797 805 # Therefore attempt to interpret key as string.
798 806 try:
799 807 rem_repr = repr(rem.encode('ascii') + '"')
800 808 except UnicodeEncodeError:
801 809 continue
802 810
803 811 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
804 812 if quote == '"':
805 813 # The entered prefix is quoted with ",
806 814 # but the match is quoted with '.
807 815 # A contained " hence needs escaping for comparison:
808 816 rem_repr = rem_repr.replace('"', '\\"')
809 817
810 818 # then reinsert prefix from start of token
811 819 matched.append('%s%s' % (token_prefix, rem_repr))
812 820 return quote, token_start, matched
813 821
814 822
815 823 def cursor_to_position(text:str, line:int, column:int)->int:
816 824 """
817 825
818 826 Convert the (line,column) position of the cursor in text to an offset in a
819 827 string.
820 828
821 829 Parameters
822 830 ----------
823 831
824 832 text : str
825 833 The text in which to calculate the cursor offset
826 834 line : int
827 835 Line of the cursor; 0-indexed
828 836 column : int
829 837 Column of the cursor 0-indexed
830 838
831 839 Return
832 840 ------
833 841 Position of the cursor in ``text``, 0-indexed.
834 842
835 843 See Also
836 844 --------
837 845 position_to_cursor: reciprocal of this function
838 846
839 847 """
840 848 lines = text.split('\n')
841 849 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
842 850
843 851 return sum(len(l) + 1 for l in lines[:line]) + column
844 852
845 853 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
846 854 """
847 855 Convert the position of the cursor in text (0 indexed) to a line
848 856 number(0-indexed) and a column number (0-indexed) pair
849 857
850 858 Position should be a valid position in ``text``.
851 859
852 860 Parameters
853 861 ----------
854 862
855 863 text : str
856 864 The text in which to calculate the cursor offset
857 865 offset : int
858 866 Position of the cursor in ``text``, 0-indexed.
859 867
860 868 Return
861 869 ------
862 870 (line, column) : (int, int)
863 871 Line of the cursor; 0-indexed, column of the cursor 0-indexed
864 872
865 873
866 874 See Also
867 875 --------
868 876 cursor_to_position : reciprocal of this function
869 877
870 878
871 879 """
872 880
873 881 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
874 882
875 883 before = text[:offset]
876 884 blines = before.split('\n') # ! splitnes trim trailing \n
877 885 line = before.count('\n')
878 886 col = len(blines[-1])
879 887 return line, col
880 888
881 889
882 890 def _safe_isinstance(obj, module, class_name):
883 891 """Checks if obj is an instance of module.class_name if loaded
884 892 """
885 893 return (module in sys.modules and
886 894 isinstance(obj, getattr(import_module(module), class_name)))
887 895
888 896
889 897 def back_unicode_name_matches(text):
890 898 u"""Match unicode characters back to unicode name
891 899
892 900 This does ``β˜ƒ`` -> ``\\snowman``
893 901
894 902 Note that snowman is not a valid python3 combining character but will be expanded.
895 903 Though it will not recombine back to the snowman character by the completion machinery.
896 904
897 905 This will not either back-complete standard sequences like \\n, \\b ...
898 906
899 907 Used on Python 3 only.
900 908 """
901 909 if len(text)<2:
902 910 return u'', ()
903 911 maybe_slash = text[-2]
904 912 if maybe_slash != '\\':
905 913 return u'', ()
906 914
907 915 char = text[-1]
908 916 # no expand on quote for completion in strings.
909 917 # nor backcomplete standard ascii keys
910 918 if char in string.ascii_letters or char in ['"',"'"]:
911 919 return u'', ()
912 920 try :
913 921 unic = unicodedata.name(char)
914 922 return '\\'+char,['\\'+unic]
915 923 except KeyError:
916 924 pass
917 925 return u'', ()
918 926
919 927 def back_latex_name_matches(text:str):
920 928 """Match latex characters back to unicode name
921 929
922 930 This does ``\\β„΅`` -> ``\\aleph``
923 931
924 932 Used on Python 3 only.
925 933 """
926 934 if len(text)<2:
927 935 return u'', ()
928 936 maybe_slash = text[-2]
929 937 if maybe_slash != '\\':
930 938 return u'', ()
931 939
932 940
933 941 char = text[-1]
934 942 # no expand on quote for completion in strings.
935 943 # nor backcomplete standard ascii keys
936 944 if char in string.ascii_letters or char in ['"',"'"]:
937 945 return u'', ()
938 946 try :
939 947 latex = reverse_latex_symbol[char]
940 948 # '\\' replace the \ as well
941 949 return '\\'+char,[latex]
942 950 except KeyError:
943 951 pass
944 952 return u'', ()
945 953
946 954
947 955 def _formatparamchildren(parameter) -> str:
948 956 """
949 957 Get parameter name and value from Jedi Private API
950 958
951 959 Jedi does not expose a simple way to get `param=value` from its API.
952 960
953 961 Parameter
954 962 =========
955 963
956 964 parameter:
957 965 Jedi's function `Param`
958 966
959 967 Returns
960 968 =======
961 969
962 970 A string like 'a', 'b=1', '*args', '**kwargs'
963 971
964 972
965 973 """
966 974 description = parameter.description
967 975 if not description.startswith('param '):
968 976 raise ValueError('Jedi function parameter description have change format.'
969 977 'Expected "param ...", found %r".' % description)
970 978 return description[6:]
971 979
972 980 def _make_signature(completion)-> str:
973 981 """
974 982 Make the signature from a jedi completion
975 983
976 984 Parameter
977 985 =========
978 986
979 987 completion: jedi.Completion
980 988 object does not complete a function type
981 989
982 990 Returns
983 991 =======
984 992
985 993 a string consisting of the function signature, with the parenthesis but
986 994 without the function name. example:
987 995 `(a, *args, b=1, **kwargs)`
988 996
989 997 """
990 998
991 999 # it looks like this might work on jedi 0.17
992 1000 if hasattr(completion, 'get_signatures'):
993 1001 signatures = completion.get_signatures()
994 1002 if not signatures:
995 1003 return '(?)'
996 1004
997 1005 c0 = completion.get_signatures()[0]
998 1006 return '('+c0.to_string().split('(', maxsplit=1)[1]
999 1007
1000 1008 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1001 1009 for p in signature.defined_names()) if f])
1002 1010
1003 1011 class IPCompleter(Completer):
1004 1012 """Extension of the completer class with IPython-specific features"""
1005 1013
1006 1014 _names = None
1007 1015
1008 1016 @observe('greedy')
1009 1017 def _greedy_changed(self, change):
1010 1018 """update the splitter and readline delims when greedy is changed"""
1011 1019 if change['new']:
1012 1020 self.splitter.delims = GREEDY_DELIMS
1013 1021 else:
1014 1022 self.splitter.delims = DELIMS
1015 1023
1016 1024 dict_keys_only = Bool(False,
1017 1025 help="""Whether to show dict key matches only""")
1018 1026
1019 1027 merge_completions = Bool(True,
1020 1028 help="""Whether to merge completion results into a single list
1021 1029
1022 1030 If False, only the completion results from the first non-empty
1023 1031 completer will be returned.
1024 1032 """
1025 1033 ).tag(config=True)
1026 1034 omit__names = Enum((0,1,2), default_value=2,
1027 1035 help="""Instruct the completer to omit private method names
1028 1036
1029 1037 Specifically, when completing on ``object.<tab>``.
1030 1038
1031 1039 When 2 [default]: all names that start with '_' will be excluded.
1032 1040
1033 1041 When 1: all 'magic' names (``__foo__``) will be excluded.
1034 1042
1035 1043 When 0: nothing will be excluded.
1036 1044 """
1037 1045 ).tag(config=True)
1038 1046 limit_to__all__ = Bool(False,
1039 1047 help="""
1040 1048 DEPRECATED as of version 5.0.
1041 1049
1042 1050 Instruct the completer to use __all__ for the completion
1043 1051
1044 1052 Specifically, when completing on ``object.<tab>``.
1045 1053
1046 1054 When True: only those names in obj.__all__ will be included.
1047 1055
1048 1056 When False [default]: the __all__ attribute is ignored
1049 1057 """,
1050 1058 ).tag(config=True)
1051 1059
1052 1060 @observe('limit_to__all__')
1053 1061 def _limit_to_all_changed(self, change):
1054 1062 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1055 1063 'value has been deprecated since IPython 5.0, will be made to have '
1056 1064 'no effects and then removed in future version of IPython.',
1057 1065 UserWarning)
1058 1066
1059 1067 def __init__(self, shell=None, namespace=None, global_namespace=None,
1060 1068 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
1061 1069 """IPCompleter() -> completer
1062 1070
1063 1071 Return a completer object.
1064 1072
1065 1073 Parameters
1066 1074 ----------
1067 1075
1068 1076 shell
1069 1077 a pointer to the ipython shell itself. This is needed
1070 1078 because this completer knows about magic functions, and those can
1071 1079 only be accessed via the ipython instance.
1072 1080
1073 1081 namespace : dict, optional
1074 1082 an optional dict where completions are performed.
1075 1083
1076 1084 global_namespace : dict, optional
1077 1085 secondary optional dict for completions, to
1078 1086 handle cases (such as IPython embedded inside functions) where
1079 1087 both Python scopes are visible.
1080 1088
1081 1089 use_readline : bool, optional
1082 1090 DEPRECATED, ignored since IPython 6.0, will have no effects
1083 1091 """
1084 1092
1085 1093 self.magic_escape = ESC_MAGIC
1086 1094 self.splitter = CompletionSplitter()
1087 1095
1088 1096 if use_readline is not _deprecation_readline_sentinel:
1089 1097 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
1090 1098 DeprecationWarning, stacklevel=2)
1091 1099
1092 1100 # _greedy_changed() depends on splitter and readline being defined:
1093 1101 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
1094 1102 config=config, **kwargs)
1095 1103
1096 1104 # List where completion matches will be stored
1097 1105 self.matches = []
1098 1106 self.shell = shell
1099 1107 # Regexp to split filenames with spaces in them
1100 1108 self.space_name_re = re.compile(r'([^\\] )')
1101 1109 # Hold a local ref. to glob.glob for speed
1102 1110 self.glob = glob.glob
1103 1111
1104 1112 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1105 1113 # buffers, to avoid completion problems.
1106 1114 term = os.environ.get('TERM','xterm')
1107 1115 self.dumb_terminal = term in ['dumb','emacs']
1108 1116
1109 1117 # Special handling of backslashes needed in win32 platforms
1110 1118 if sys.platform == "win32":
1111 1119 self.clean_glob = self._clean_glob_win32
1112 1120 else:
1113 1121 self.clean_glob = self._clean_glob
1114 1122
1115 1123 #regexp to parse docstring for function signature
1116 1124 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1117 1125 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1118 1126 #use this if positional argument name is also needed
1119 1127 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1120 1128
1121 1129 self.magic_arg_matchers = [
1122 1130 self.magic_config_matches,
1123 1131 self.magic_color_matches,
1124 1132 ]
1125 1133
1126 1134 # This is set externally by InteractiveShell
1127 1135 self.custom_completers = None
1128 1136
1129 1137 @property
1130 1138 def matchers(self):
1131 1139 """All active matcher routines for completion"""
1132 1140 if self.dict_keys_only:
1133 1141 return [self.dict_key_matches]
1134 1142
1135 1143 if self.use_jedi:
1136 1144 return [
1137 1145 *self.custom_matchers,
1138 1146 self.file_matches,
1139 1147 self.magic_matches,
1140 1148 self.dict_key_matches,
1141 1149 ]
1142 1150 else:
1143 1151 return [
1144 1152 *self.custom_matchers,
1145 1153 self.python_matches,
1146 1154 self.file_matches,
1147 1155 self.magic_matches,
1148 1156 self.python_func_kw_matches,
1149 1157 self.dict_key_matches,
1150 1158 ]
1151 1159
1152 1160 def all_completions(self, text) -> List[str]:
1153 1161 """
1154 1162 Wrapper around the completion methods for the benefit of emacs.
1155 1163 """
1156 1164 prefix = text.rpartition('.')[0]
1157 1165 with provisionalcompleter():
1158 1166 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1159 1167 for c in self.completions(text, len(text))]
1160 1168
1161 1169 return self.complete(text)[1]
1162 1170
1163 1171 def _clean_glob(self, text):
1164 1172 return self.glob("%s*" % text)
1165 1173
1166 1174 def _clean_glob_win32(self,text):
1167 1175 return [f.replace("\\","/")
1168 1176 for f in self.glob("%s*" % text)]
1169 1177
1170 1178 def file_matches(self, text):
1171 1179 """Match filenames, expanding ~USER type strings.
1172 1180
1173 1181 Most of the seemingly convoluted logic in this completer is an
1174 1182 attempt to handle filenames with spaces in them. And yet it's not
1175 1183 quite perfect, because Python's readline doesn't expose all of the
1176 1184 GNU readline details needed for this to be done correctly.
1177 1185
1178 1186 For a filename with a space in it, the printed completions will be
1179 1187 only the parts after what's already been typed (instead of the
1180 1188 full completions, as is normally done). I don't think with the
1181 1189 current (as of Python 2.3) Python readline it's possible to do
1182 1190 better."""
1183 1191
1184 1192 # chars that require escaping with backslash - i.e. chars
1185 1193 # that readline treats incorrectly as delimiters, but we
1186 1194 # don't want to treat as delimiters in filename matching
1187 1195 # when escaped with backslash
1188 1196 if text.startswith('!'):
1189 1197 text = text[1:]
1190 1198 text_prefix = u'!'
1191 1199 else:
1192 1200 text_prefix = u''
1193 1201
1194 1202 text_until_cursor = self.text_until_cursor
1195 1203 # track strings with open quotes
1196 1204 open_quotes = has_open_quotes(text_until_cursor)
1197 1205
1198 1206 if '(' in text_until_cursor or '[' in text_until_cursor:
1199 1207 lsplit = text
1200 1208 else:
1201 1209 try:
1202 1210 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1203 1211 lsplit = arg_split(text_until_cursor)[-1]
1204 1212 except ValueError:
1205 1213 # typically an unmatched ", or backslash without escaped char.
1206 1214 if open_quotes:
1207 1215 lsplit = text_until_cursor.split(open_quotes)[-1]
1208 1216 else:
1209 1217 return []
1210 1218 except IndexError:
1211 1219 # tab pressed on empty line
1212 1220 lsplit = ""
1213 1221
1214 1222 if not open_quotes and lsplit != protect_filename(lsplit):
1215 1223 # if protectables are found, do matching on the whole escaped name
1216 1224 has_protectables = True
1217 1225 text0,text = text,lsplit
1218 1226 else:
1219 1227 has_protectables = False
1220 1228 text = os.path.expanduser(text)
1221 1229
1222 1230 if text == "":
1223 1231 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1224 1232
1225 1233 # Compute the matches from the filesystem
1226 1234 if sys.platform == 'win32':
1227 1235 m0 = self.clean_glob(text)
1228 1236 else:
1229 1237 m0 = self.clean_glob(text.replace('\\', ''))
1230 1238
1231 1239 if has_protectables:
1232 1240 # If we had protectables, we need to revert our changes to the
1233 1241 # beginning of filename so that we don't double-write the part
1234 1242 # of the filename we have so far
1235 1243 len_lsplit = len(lsplit)
1236 1244 matches = [text_prefix + text0 +
1237 1245 protect_filename(f[len_lsplit:]) for f in m0]
1238 1246 else:
1239 1247 if open_quotes:
1240 1248 # if we have a string with an open quote, we don't need to
1241 1249 # protect the names beyond the quote (and we _shouldn't_, as
1242 1250 # it would cause bugs when the filesystem call is made).
1243 1251 matches = m0 if sys.platform == "win32" else\
1244 1252 [protect_filename(f, open_quotes) for f in m0]
1245 1253 else:
1246 1254 matches = [text_prefix +
1247 1255 protect_filename(f) for f in m0]
1248 1256
1249 1257 # Mark directories in input list by appending '/' to their names.
1250 1258 return [x+'/' if os.path.isdir(x) else x for x in matches]
1251 1259
1252 1260 def magic_matches(self, text):
1253 1261 """Match magics"""
1254 1262 # Get all shell magics now rather than statically, so magics loaded at
1255 1263 # runtime show up too.
1256 1264 lsm = self.shell.magics_manager.lsmagic()
1257 1265 line_magics = lsm['line']
1258 1266 cell_magics = lsm['cell']
1259 1267 pre = self.magic_escape
1260 1268 pre2 = pre+pre
1261 1269
1262 1270 explicit_magic = text.startswith(pre)
1263 1271
1264 1272 # Completion logic:
1265 1273 # - user gives %%: only do cell magics
1266 1274 # - user gives %: do both line and cell magics
1267 1275 # - no prefix: do both
1268 1276 # In other words, line magics are skipped if the user gives %% explicitly
1269 1277 #
1270 1278 # We also exclude magics that match any currently visible names:
1271 1279 # https://github.com/ipython/ipython/issues/4877, unless the user has
1272 1280 # typed a %:
1273 1281 # https://github.com/ipython/ipython/issues/10754
1274 1282 bare_text = text.lstrip(pre)
1275 1283 global_matches = self.global_matches(bare_text)
1276 1284 if not explicit_magic:
1277 1285 def matches(magic):
1278 1286 """
1279 1287 Filter magics, in particular remove magics that match
1280 1288 a name present in global namespace.
1281 1289 """
1282 1290 return ( magic.startswith(bare_text) and
1283 1291 magic not in global_matches )
1284 1292 else:
1285 1293 def matches(magic):
1286 1294 return magic.startswith(bare_text)
1287 1295
1288 1296 comp = [ pre2+m for m in cell_magics if matches(m)]
1289 1297 if not text.startswith(pre2):
1290 1298 comp += [ pre+m for m in line_magics if matches(m)]
1291 1299
1292 1300 return comp
1293 1301
1294 1302 def magic_config_matches(self, text:str) -> List[str]:
1295 1303 """ Match class names and attributes for %config magic """
1296 1304 texts = text.strip().split()
1297 1305
1298 1306 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1299 1307 # get all configuration classes
1300 1308 classes = sorted(set([ c for c in self.shell.configurables
1301 1309 if c.__class__.class_traits(config=True)
1302 1310 ]), key=lambda x: x.__class__.__name__)
1303 1311 classnames = [ c.__class__.__name__ for c in classes ]
1304 1312
1305 1313 # return all classnames if config or %config is given
1306 1314 if len(texts) == 1:
1307 1315 return classnames
1308 1316
1309 1317 # match classname
1310 1318 classname_texts = texts[1].split('.')
1311 1319 classname = classname_texts[0]
1312 1320 classname_matches = [ c for c in classnames
1313 1321 if c.startswith(classname) ]
1314 1322
1315 1323 # return matched classes or the matched class with attributes
1316 1324 if texts[1].find('.') < 0:
1317 1325 return classname_matches
1318 1326 elif len(classname_matches) == 1 and \
1319 1327 classname_matches[0] == classname:
1320 1328 cls = classes[classnames.index(classname)].__class__
1321 1329 help = cls.class_get_help()
1322 1330 # strip leading '--' from cl-args:
1323 1331 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1324 1332 return [ attr.split('=')[0]
1325 1333 for attr in help.strip().splitlines()
1326 1334 if attr.startswith(texts[1]) ]
1327 1335 return []
1328 1336
1329 1337 def magic_color_matches(self, text:str) -> List[str] :
1330 1338 """ Match color schemes for %colors magic"""
1331 1339 texts = text.split()
1332 1340 if text.endswith(' '):
1333 1341 # .split() strips off the trailing whitespace. Add '' back
1334 1342 # so that: '%colors ' -> ['%colors', '']
1335 1343 texts.append('')
1336 1344
1337 1345 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1338 1346 prefix = texts[1]
1339 1347 return [ color for color in InspectColors.keys()
1340 1348 if color.startswith(prefix) ]
1341 1349 return []
1342 1350
1343 1351 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str):
1344 1352 """
1345 1353
1346 1354 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1347 1355 cursor position.
1348 1356
1349 1357 Parameters
1350 1358 ----------
1351 1359 cursor_column : int
1352 1360 column position of the cursor in ``text``, 0-indexed.
1353 1361 cursor_line : int
1354 1362 line position of the cursor in ``text``, 0-indexed
1355 1363 text : str
1356 1364 text to complete
1357 1365
1358 1366 Debugging
1359 1367 ---------
1360 1368
1361 1369 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1362 1370 object containing a string with the Jedi debug information attached.
1363 1371 """
1364 1372 namespaces = [self.namespace]
1365 1373 if self.global_namespace is not None:
1366 1374 namespaces.append(self.global_namespace)
1367 1375
1368 1376 completion_filter = lambda x:x
1369 1377 offset = cursor_to_position(text, cursor_line, cursor_column)
1370 1378 # filter output if we are completing for object members
1371 1379 if offset:
1372 1380 pre = text[offset-1]
1373 1381 if pre == '.':
1374 1382 if self.omit__names == 2:
1375 1383 completion_filter = lambda c:not c.name.startswith('_')
1376 1384 elif self.omit__names == 1:
1377 1385 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1378 1386 elif self.omit__names == 0:
1379 1387 completion_filter = lambda x:x
1380 1388 else:
1381 1389 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1382 1390
1383 1391 interpreter = jedi.Interpreter(text[:offset], namespaces)
1384 1392 try_jedi = True
1385 1393
1386 1394 try:
1387 1395 # find the first token in the current tree -- if it is a ' or " then we are in a string
1388 1396 completing_string = False
1389 1397 try:
1390 1398 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1391 1399 except StopIteration:
1392 1400 pass
1393 1401 else:
1394 1402 # note the value may be ', ", or it may also be ''' or """, or
1395 1403 # in some cases, """what/you/typed..., but all of these are
1396 1404 # strings.
1397 1405 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1398 1406
1399 1407 # if we are in a string jedi is likely not the right candidate for
1400 1408 # now. Skip it.
1401 1409 try_jedi = not completing_string
1402 1410 except Exception as e:
1403 1411 # many of things can go wrong, we are using private API just don't crash.
1404 1412 if self.debug:
1405 1413 print("Error detecting if completing a non-finished string :", e, '|')
1406 1414
1407 1415 if not try_jedi:
1408 1416 return []
1409 1417 try:
1410 1418 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1411 1419 except Exception as e:
1412 1420 if self.debug:
1413 1421 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1414 1422 else:
1415 1423 return []
1416 1424
1417 1425 def python_matches(self, text):
1418 1426 """Match attributes or global python names"""
1419 1427 if "." in text:
1420 1428 try:
1421 1429 matches = self.attr_matches(text)
1422 1430 if text.endswith('.') and self.omit__names:
1423 1431 if self.omit__names == 1:
1424 1432 # true if txt is _not_ a __ name, false otherwise:
1425 1433 no__name = (lambda txt:
1426 1434 re.match(r'.*\.__.*?__',txt) is None)
1427 1435 else:
1428 1436 # true if txt is _not_ a _ name, false otherwise:
1429 1437 no__name = (lambda txt:
1430 1438 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1431 1439 matches = filter(no__name, matches)
1432 1440 except NameError:
1433 1441 # catches <undefined attributes>.<tab>
1434 1442 matches = []
1435 1443 else:
1436 1444 matches = self.global_matches(text)
1437 1445 return matches
1438 1446
1439 1447 def _default_arguments_from_docstring(self, doc):
1440 1448 """Parse the first line of docstring for call signature.
1441 1449
1442 1450 Docstring should be of the form 'min(iterable[, key=func])\n'.
1443 1451 It can also parse cython docstring of the form
1444 1452 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1445 1453 """
1446 1454 if doc is None:
1447 1455 return []
1448 1456
1449 1457 #care only the firstline
1450 1458 line = doc.lstrip().splitlines()[0]
1451 1459
1452 1460 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1453 1461 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1454 1462 sig = self.docstring_sig_re.search(line)
1455 1463 if sig is None:
1456 1464 return []
1457 1465 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1458 1466 sig = sig.groups()[0].split(',')
1459 1467 ret = []
1460 1468 for s in sig:
1461 1469 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1462 1470 ret += self.docstring_kwd_re.findall(s)
1463 1471 return ret
1464 1472
1465 1473 def _default_arguments(self, obj):
1466 1474 """Return the list of default arguments of obj if it is callable,
1467 1475 or empty list otherwise."""
1468 1476 call_obj = obj
1469 1477 ret = []
1470 1478 if inspect.isbuiltin(obj):
1471 1479 pass
1472 1480 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1473 1481 if inspect.isclass(obj):
1474 1482 #for cython embedsignature=True the constructor docstring
1475 1483 #belongs to the object itself not __init__
1476 1484 ret += self._default_arguments_from_docstring(
1477 1485 getattr(obj, '__doc__', ''))
1478 1486 # for classes, check for __init__,__new__
1479 1487 call_obj = (getattr(obj, '__init__', None) or
1480 1488 getattr(obj, '__new__', None))
1481 1489 # for all others, check if they are __call__able
1482 1490 elif hasattr(obj, '__call__'):
1483 1491 call_obj = obj.__call__
1484 1492 ret += self._default_arguments_from_docstring(
1485 1493 getattr(call_obj, '__doc__', ''))
1486 1494
1487 1495 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1488 1496 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1489 1497
1490 1498 try:
1491 1499 sig = inspect.signature(call_obj)
1492 1500 ret.extend(k for k, v in sig.parameters.items() if
1493 1501 v.kind in _keeps)
1494 1502 except ValueError:
1495 1503 pass
1496 1504
1497 1505 return list(set(ret))
1498 1506
1499 1507 def python_func_kw_matches(self,text):
1500 1508 """Match named parameters (kwargs) of the last open function"""
1501 1509
1502 1510 if "." in text: # a parameter cannot be dotted
1503 1511 return []
1504 1512 try: regexp = self.__funcParamsRegex
1505 1513 except AttributeError:
1506 1514 regexp = self.__funcParamsRegex = re.compile(r'''
1507 1515 '.*?(?<!\\)' | # single quoted strings or
1508 1516 ".*?(?<!\\)" | # double quoted strings or
1509 1517 \w+ | # identifier
1510 1518 \S # other characters
1511 1519 ''', re.VERBOSE | re.DOTALL)
1512 1520 # 1. find the nearest identifier that comes before an unclosed
1513 1521 # parenthesis before the cursor
1514 1522 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1515 1523 tokens = regexp.findall(self.text_until_cursor)
1516 1524 iterTokens = reversed(tokens); openPar = 0
1517 1525
1518 1526 for token in iterTokens:
1519 1527 if token == ')':
1520 1528 openPar -= 1
1521 1529 elif token == '(':
1522 1530 openPar += 1
1523 1531 if openPar > 0:
1524 1532 # found the last unclosed parenthesis
1525 1533 break
1526 1534 else:
1527 1535 return []
1528 1536 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1529 1537 ids = []
1530 1538 isId = re.compile(r'\w+$').match
1531 1539
1532 1540 while True:
1533 1541 try:
1534 1542 ids.append(next(iterTokens))
1535 1543 if not isId(ids[-1]):
1536 1544 ids.pop(); break
1537 1545 if not next(iterTokens) == '.':
1538 1546 break
1539 1547 except StopIteration:
1540 1548 break
1541 1549
1542 1550 # Find all named arguments already assigned to, as to avoid suggesting
1543 1551 # them again
1544 1552 usedNamedArgs = set()
1545 1553 par_level = -1
1546 1554 for token, next_token in zip(tokens, tokens[1:]):
1547 1555 if token == '(':
1548 1556 par_level += 1
1549 1557 elif token == ')':
1550 1558 par_level -= 1
1551 1559
1552 1560 if par_level != 0:
1553 1561 continue
1554 1562
1555 1563 if next_token != '=':
1556 1564 continue
1557 1565
1558 1566 usedNamedArgs.add(token)
1559 1567
1560 1568 argMatches = []
1561 1569 try:
1562 1570 callableObj = '.'.join(ids[::-1])
1563 1571 namedArgs = self._default_arguments(eval(callableObj,
1564 1572 self.namespace))
1565 1573
1566 1574 # Remove used named arguments from the list, no need to show twice
1567 1575 for namedArg in set(namedArgs) - usedNamedArgs:
1568 1576 if namedArg.startswith(text):
1569 1577 argMatches.append(u"%s=" %namedArg)
1570 1578 except:
1571 1579 pass
1572 1580
1573 1581 return argMatches
1574 1582
1575 1583 def dict_key_matches(self, text):
1576 1584 "Match string keys in a dictionary, after e.g. 'foo[' "
1577 1585 def get_keys(obj):
1578 1586 # Objects can define their own completions by defining an
1579 1587 # _ipy_key_completions_() method.
1580 1588 method = get_real_method(obj, '_ipython_key_completions_')
1581 1589 if method is not None:
1582 1590 return method()
1583 1591
1584 1592 # Special case some common in-memory dict-like types
1585 1593 if isinstance(obj, dict) or\
1586 1594 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1587 1595 try:
1588 1596 return list(obj.keys())
1589 1597 except Exception:
1590 1598 return []
1591 1599 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1592 1600 _safe_isinstance(obj, 'numpy', 'void'):
1593 1601 return obj.dtype.names or []
1594 1602 return []
1595 1603
1596 1604 try:
1597 1605 regexps = self.__dict_key_regexps
1598 1606 except AttributeError:
1599 1607 dict_key_re_fmt = r'''(?x)
1600 1608 ( # match dict-referring expression wrt greedy setting
1601 1609 %s
1602 1610 )
1603 1611 \[ # open bracket
1604 1612 \s* # and optional whitespace
1605 1613 ([uUbB]? # string prefix (r not handled)
1606 1614 (?: # unclosed string
1607 1615 '(?:[^']|(?<!\\)\\')*
1608 1616 |
1609 1617 "(?:[^"]|(?<!\\)\\")*
1610 1618 )
1611 1619 )?
1612 1620 $
1613 1621 '''
1614 1622 regexps = self.__dict_key_regexps = {
1615 1623 False: re.compile(dict_key_re_fmt % r'''
1616 1624 # identifiers separated by .
1617 1625 (?!\d)\w+
1618 1626 (?:\.(?!\d)\w+)*
1619 1627 '''),
1620 1628 True: re.compile(dict_key_re_fmt % '''
1621 1629 .+
1622 1630 ''')
1623 1631 }
1624 1632
1625 1633 match = regexps[self.greedy].search(self.text_until_cursor)
1626 1634 if match is None:
1627 1635 return []
1628 1636
1629 1637 expr, prefix = match.groups()
1630 1638 try:
1631 1639 obj = eval(expr, self.namespace)
1632 1640 except Exception:
1633 1641 try:
1634 1642 obj = eval(expr, self.global_namespace)
1635 1643 except Exception:
1636 1644 return []
1637 1645
1638 1646 keys = get_keys(obj)
1639 1647 if not keys:
1640 1648 return keys
1641 1649 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1642 1650 if not matches:
1643 1651 return matches
1644 1652
1645 1653 # get the cursor position of
1646 1654 # - the text being completed
1647 1655 # - the start of the key text
1648 1656 # - the start of the completion
1649 1657 text_start = len(self.text_until_cursor) - len(text)
1650 1658 if prefix:
1651 1659 key_start = match.start(2)
1652 1660 completion_start = key_start + token_offset
1653 1661 else:
1654 1662 key_start = completion_start = match.end()
1655 1663
1656 1664 # grab the leading prefix, to make sure all completions start with `text`
1657 1665 if text_start > key_start:
1658 1666 leading = ''
1659 1667 else:
1660 1668 leading = text[text_start:completion_start]
1661 1669
1662 1670 # the index of the `[` character
1663 1671 bracket_idx = match.end(1)
1664 1672
1665 1673 # append closing quote and bracket as appropriate
1666 1674 # this is *not* appropriate if the opening quote or bracket is outside
1667 1675 # the text given to this method
1668 1676 suf = ''
1669 1677 continuation = self.line_buffer[len(self.text_until_cursor):]
1670 1678 if key_start > text_start and closing_quote:
1671 1679 # quotes were opened inside text, maybe close them
1672 1680 if continuation.startswith(closing_quote):
1673 1681 continuation = continuation[len(closing_quote):]
1674 1682 else:
1675 1683 suf += closing_quote
1676 1684 if bracket_idx > text_start:
1677 1685 # brackets were opened inside text, maybe close them
1678 1686 if not continuation.startswith(']'):
1679 1687 suf += ']'
1680 1688
1681 1689 return [leading + k + suf for k in matches]
1682 1690
1683 1691 def unicode_name_matches(self, text):
1684 1692 u"""Match Latex-like syntax for unicode characters base
1685 1693 on the name of the character.
1686 1694
1687 1695 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1688 1696
1689 1697 Works only on valid python 3 identifier, or on combining characters that
1690 1698 will combine to form a valid identifier.
1691 1699
1692 1700 Used on Python 3 only.
1693 1701 """
1694 1702 slashpos = text.rfind('\\')
1695 1703 if slashpos > -1:
1696 1704 s = text[slashpos+1:]
1697 1705 try :
1698 1706 unic = unicodedata.lookup(s)
1699 1707 # allow combining chars
1700 1708 if ('a'+unic).isidentifier():
1701 1709 return '\\'+s,[unic]
1702 1710 except KeyError:
1703 1711 pass
1704 1712 return u'', []
1705 1713
1706 1714
1707 1715 def latex_matches(self, text):
1708 1716 u"""Match Latex syntax for unicode characters.
1709 1717
1710 1718 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1711 1719 """
1712 1720 slashpos = text.rfind('\\')
1713 1721 if slashpos > -1:
1714 1722 s = text[slashpos:]
1715 1723 if s in latex_symbols:
1716 1724 # Try to complete a full latex symbol to unicode
1717 1725 # \\alpha -> Ξ±
1718 1726 return s, [latex_symbols[s]]
1719 1727 else:
1720 1728 # If a user has partially typed a latex symbol, give them
1721 1729 # a full list of options \al -> [\aleph, \alpha]
1722 1730 matches = [k for k in latex_symbols if k.startswith(s)]
1723 1731 if matches:
1724 1732 return s, matches
1725 1733 return u'', []
1726 1734
1727 1735 def dispatch_custom_completer(self, text):
1728 1736 if not self.custom_completers:
1729 1737 return
1730 1738
1731 1739 line = self.line_buffer
1732 1740 if not line.strip():
1733 1741 return None
1734 1742
1735 1743 # Create a little structure to pass all the relevant information about
1736 1744 # the current completion to any custom completer.
1737 1745 event = SimpleNamespace()
1738 1746 event.line = line
1739 1747 event.symbol = text
1740 1748 cmd = line.split(None,1)[0]
1741 1749 event.command = cmd
1742 1750 event.text_until_cursor = self.text_until_cursor
1743 1751
1744 1752 # for foo etc, try also to find completer for %foo
1745 1753 if not cmd.startswith(self.magic_escape):
1746 1754 try_magic = self.custom_completers.s_matches(
1747 1755 self.magic_escape + cmd)
1748 1756 else:
1749 1757 try_magic = []
1750 1758
1751 1759 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1752 1760 try_magic,
1753 1761 self.custom_completers.flat_matches(self.text_until_cursor)):
1754 1762 try:
1755 1763 res = c(event)
1756 1764 if res:
1757 1765 # first, try case sensitive match
1758 1766 withcase = [r for r in res if r.startswith(text)]
1759 1767 if withcase:
1760 1768 return withcase
1761 1769 # if none, then case insensitive ones are ok too
1762 1770 text_low = text.lower()
1763 1771 return [r for r in res if r.lower().startswith(text_low)]
1764 1772 except TryNext:
1765 1773 pass
1766 1774 except KeyboardInterrupt:
1767 1775 """
1768 1776 If custom completer take too long,
1769 1777 let keyboard interrupt abort and return nothing.
1770 1778 """
1771 1779 break
1772 1780
1773 1781 return None
1774 1782
1775 1783 def completions(self, text: str, offset: int)->Iterator[Completion]:
1776 1784 """
1777 1785 Returns an iterator over the possible completions
1778 1786
1779 .. warning:: Unstable
1787 .. warning::
1788
1789 Unstable
1780 1790
1781 1791 This function is unstable, API may change without warning.
1782 1792 It will also raise unless use in proper context manager.
1783 1793
1784 1794 Parameters
1785 1795 ----------
1786 1796
1787 1797 text:str
1788 1798 Full text of the current input, multi line string.
1789 1799 offset:int
1790 1800 Integer representing the position of the cursor in ``text``. Offset
1791 1801 is 0-based indexed.
1792 1802
1793 1803 Yields
1794 1804 ------
1795 1805 :any:`Completion` object
1796 1806
1797 1807
1798 1808 The cursor on a text can either be seen as being "in between"
1799 1809 characters or "On" a character depending on the interface visible to
1800 1810 the user. For consistency the cursor being on "in between" characters X
1801 1811 and Y is equivalent to the cursor being "on" character Y, that is to say
1802 1812 the character the cursor is on is considered as being after the cursor.
1803 1813
1804 1814 Combining characters may span more that one position in the
1805 1815 text.
1806 1816
1807 1817
1808 1818 .. note::
1809 1819
1810 1820 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1811 1821 fake Completion token to distinguish completion returned by Jedi
1812 1822 and usual IPython completion.
1813 1823
1814 1824 .. note::
1815 1825
1816 1826 Completions are not completely deduplicated yet. If identical
1817 1827 completions are coming from different sources this function does not
1818 1828 ensure that each completion object will only be present once.
1819 1829 """
1820 1830 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1821 1831 "It may change without warnings. "
1822 1832 "Use in corresponding context manager.",
1823 1833 category=ProvisionalCompleterWarning, stacklevel=2)
1824 1834
1825 1835 seen = set()
1826 1836 try:
1827 1837 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1828 1838 if c and (c in seen):
1829 1839 continue
1830 1840 yield c
1831 1841 seen.add(c)
1832 1842 except KeyboardInterrupt:
1833 1843 """if completions take too long and users send keyboard interrupt,
1834 1844 do not crash and return ASAP. """
1835 1845 pass
1836 1846
1837 1847 def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]:
1838 1848 """
1839 1849 Core completion module.Same signature as :any:`completions`, with the
1840 1850 extra `timeout` parameter (in seconds).
1841 1851
1842 1852
1843 1853 Computing jedi's completion ``.type`` can be quite expensive (it is a
1844 1854 lazy property) and can require some warm-up, more warm up than just
1845 1855 computing the ``name`` of a completion. The warm-up can be :
1846 1856
1847 1857 - Long warm-up the first time a module is encountered after
1848 1858 install/update: actually build parse/inference tree.
1849 1859
1850 1860 - first time the module is encountered in a session: load tree from
1851 1861 disk.
1852 1862
1853 1863 We don't want to block completions for tens of seconds so we give the
1854 1864 completer a "budget" of ``_timeout`` seconds per invocation to compute
1855 1865 completions types, the completions that have not yet been computed will
1856 1866 be marked as "unknown" an will have a chance to be computed next round
1857 1867 are things get cached.
1858 1868
1859 1869 Keep in mind that Jedi is not the only thing treating the completion so
1860 1870 keep the timeout short-ish as if we take more than 0.3 second we still
1861 1871 have lots of processing to do.
1862 1872
1863 1873 """
1864 1874 deadline = time.monotonic() + _timeout
1865 1875
1866 1876
1867 1877 before = full_text[:offset]
1868 1878 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1869 1879
1870 1880 matched_text, matches, matches_origin, jedi_matches = self._complete(
1871 1881 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1872 1882
1873 1883 iter_jm = iter(jedi_matches)
1874 1884 if _timeout:
1875 1885 for jm in iter_jm:
1876 1886 try:
1877 1887 type_ = jm.type
1878 1888 except Exception:
1879 1889 if self.debug:
1880 1890 print("Error in Jedi getting type of ", jm)
1881 1891 type_ = None
1882 1892 delta = len(jm.name_with_symbols) - len(jm.complete)
1883 1893 if type_ == 'function':
1884 1894 signature = _make_signature(jm)
1885 1895 else:
1886 1896 signature = ''
1887 1897 yield Completion(start=offset - delta,
1888 1898 end=offset,
1889 1899 text=jm.name_with_symbols,
1890 1900 type=type_,
1891 1901 signature=signature,
1892 1902 _origin='jedi')
1893 1903
1894 1904 if time.monotonic() > deadline:
1895 1905 break
1896 1906
1897 1907 for jm in iter_jm:
1898 1908 delta = len(jm.name_with_symbols) - len(jm.complete)
1899 1909 yield Completion(start=offset - delta,
1900 1910 end=offset,
1901 1911 text=jm.name_with_symbols,
1902 1912 type='<unknown>', # don't compute type for speed
1903 1913 _origin='jedi',
1904 1914 signature='')
1905 1915
1906 1916
1907 1917 start_offset = before.rfind(matched_text)
1908 1918
1909 1919 # TODO:
1910 1920 # Suppress this, right now just for debug.
1911 1921 if jedi_matches and matches and self.debug:
1912 1922 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
1913 1923 _origin='debug', type='none', signature='')
1914 1924
1915 1925 # I'm unsure if this is always true, so let's assert and see if it
1916 1926 # crash
1917 1927 assert before.endswith(matched_text)
1918 1928 for m, t in zip(matches, matches_origin):
1919 1929 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
1920 1930
1921 1931
1922 1932 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1923 1933 """Find completions for the given text and line context.
1924 1934
1925 1935 Note that both the text and the line_buffer are optional, but at least
1926 1936 one of them must be given.
1927 1937
1928 1938 Parameters
1929 1939 ----------
1930 1940 text : string, optional
1931 1941 Text to perform the completion on. If not given, the line buffer
1932 1942 is split using the instance's CompletionSplitter object.
1933 1943
1934 1944 line_buffer : string, optional
1935 1945 If not given, the completer attempts to obtain the current line
1936 1946 buffer via readline. This keyword allows clients which are
1937 1947 requesting for text completions in non-readline contexts to inform
1938 1948 the completer of the entire text.
1939 1949
1940 1950 cursor_pos : int, optional
1941 1951 Index of the cursor in the full line buffer. Should be provided by
1942 1952 remote frontends where kernel has no access to frontend state.
1943 1953
1944 1954 Returns
1945 1955 -------
1946 1956 text : str
1947 1957 Text that was actually used in the completion.
1948 1958
1949 1959 matches : list
1950 1960 A list of completion matches.
1951 1961
1952 1962
1953 1963 .. note::
1954 1964
1955 1965 This API is likely to be deprecated and replaced by
1956 1966 :any:`IPCompleter.completions` in the future.
1957 1967
1958 1968
1959 1969 """
1960 1970 warnings.warn('`Completer.complete` is pending deprecation since '
1961 1971 'IPython 6.0 and will be replaced by `Completer.completions`.',
1962 1972 PendingDeprecationWarning)
1963 1973 # potential todo, FOLD the 3rd throw away argument of _complete
1964 1974 # into the first 2 one.
1965 1975 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
1966 1976
1967 1977 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
1968 1978 full_text=None) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]:
1969 1979 """
1970 1980
1971 1981 Like complete but can also returns raw jedi completions as well as the
1972 1982 origin of the completion text. This could (and should) be made much
1973 1983 cleaner but that will be simpler once we drop the old (and stateful)
1974 1984 :any:`complete` API.
1975 1985
1976 1986
1977 1987 With current provisional API, cursor_pos act both (depending on the
1978 1988 caller) as the offset in the ``text`` or ``line_buffer``, or as the
1979 1989 ``column`` when passing multiline strings this could/should be renamed
1980 1990 but would add extra noise.
1981 1991 """
1982 1992
1983 1993 # if the cursor position isn't given, the only sane assumption we can
1984 1994 # make is that it's at the end of the line (the common case)
1985 1995 if cursor_pos is None:
1986 1996 cursor_pos = len(line_buffer) if text is None else len(text)
1987 1997
1988 1998 if self.use_main_ns:
1989 1999 self.namespace = __main__.__dict__
1990 2000
1991 2001 # if text is either None or an empty string, rely on the line buffer
1992 2002 if (not line_buffer) and full_text:
1993 2003 line_buffer = full_text.split('\n')[cursor_line]
1994 2004 if not text: # issue #11508: check line_buffer before calling split_line
1995 2005 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
1996 2006
1997 2007 if self.backslash_combining_completions:
1998 2008 # allow deactivation of these on windows.
1999 2009 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2000 2010 latex_text, latex_matches = self.latex_matches(base_text)
2001 2011 if latex_matches:
2002 2012 return latex_text, latex_matches, ['latex_matches']*len(latex_matches), ()
2003 2013 name_text = ''
2004 2014 name_matches = []
2005 2015 # need to add self.fwd_unicode_match() function here when done
2006 2016 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches, self.fwd_unicode_match):
2007 2017 name_text, name_matches = meth(base_text)
2008 2018 if name_text:
2009 2019 return name_text, name_matches[:MATCHES_LIMIT], \
2010 2020 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ()
2011 2021
2012 2022
2013 2023 # If no line buffer is given, assume the input text is all there was
2014 2024 if line_buffer is None:
2015 2025 line_buffer = text
2016 2026
2017 2027 self.line_buffer = line_buffer
2018 2028 self.text_until_cursor = self.line_buffer[:cursor_pos]
2019 2029
2020 2030 # Do magic arg matches
2021 2031 for matcher in self.magic_arg_matchers:
2022 2032 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2023 2033 if matches:
2024 2034 origins = [matcher.__qualname__] * len(matches)
2025 2035 return text, matches, origins, ()
2026 2036
2027 2037 # Start with a clean slate of completions
2028 2038 matches = []
2029 2039
2030 2040 # FIXME: we should extend our api to return a dict with completions for
2031 2041 # different types of objects. The rlcomplete() method could then
2032 2042 # simply collapse the dict into a list for readline, but we'd have
2033 2043 # richer completion semantics in other environments.
2034 2044 completions = ()
2035 2045 if self.use_jedi:
2036 2046 if not full_text:
2037 2047 full_text = line_buffer
2038 2048 completions = self._jedi_matches(
2039 2049 cursor_pos, cursor_line, full_text)
2040 2050
2041 2051 if self.merge_completions:
2042 2052 matches = []
2043 2053 for matcher in self.matchers:
2044 2054 try:
2045 2055 matches.extend([(m, matcher.__qualname__)
2046 2056 for m in matcher(text)])
2047 2057 except:
2048 2058 # Show the ugly traceback if the matcher causes an
2049 2059 # exception, but do NOT crash the kernel!
2050 2060 sys.excepthook(*sys.exc_info())
2051 2061 else:
2052 2062 for matcher in self.matchers:
2053 2063 matches = [(m, matcher.__qualname__)
2054 2064 for m in matcher(text)]
2055 2065 if matches:
2056 2066 break
2057 2067
2058 2068 seen = set()
2059 2069 filtered_matches = set()
2060 2070 for m in matches:
2061 2071 t, c = m
2062 2072 if t not in seen:
2063 2073 filtered_matches.add(m)
2064 2074 seen.add(t)
2065 2075
2066 2076 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2067 2077
2068 2078 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2069 2079
2070 2080 _filtered_matches = custom_res or _filtered_matches
2071 2081
2072 2082 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2073 2083 _matches = [m[0] for m in _filtered_matches]
2074 2084 origins = [m[1] for m in _filtered_matches]
2075 2085
2076 2086 self.matches = _matches
2077 2087
2078 2088 return text, _matches, origins, completions
2079 2089
2080 2090 def fwd_unicode_match(self, text:str) -> Tuple[str, list]:
2081 2091 if self._names is None:
2082 2092 self._names = []
2083 2093 for c in range(0,0x10FFFF + 1):
2084 2094 try:
2085 2095 self._names.append(unicodedata.name(chr(c)))
2086 2096 except ValueError:
2087 2097 pass
2088 2098
2089 2099 slashpos = text.rfind('\\')
2090 2100 # if text starts with slash
2091 2101 if slashpos > -1:
2092 2102 s = text[slashpos+1:]
2093 2103 candidates = [x for x in self._names if x.startswith(s)]
2094 2104 if candidates:
2095 2105 return s, candidates
2096 2106 else:
2097 2107 return '', ()
2098 2108
2099 2109 # if text does not start with slash
2100 2110 else:
2101 2111 return u'', ()
@@ -1,1527 +1,1527 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Top-level display functions for displaying object in different formats."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7
8 8 from binascii import b2a_hex, b2a_base64, hexlify
9 9 import json
10 10 import mimetypes
11 11 import os
12 12 import struct
13 13 import sys
14 14 import warnings
15 15 from copy import deepcopy
16 16 from os.path import splitext
17 17 from pathlib import Path, PurePath
18 18
19 19 from IPython.utils.py3compat import cast_unicode
20 20 from IPython.testing.skipdoctest import skip_doctest
21 21
22 22 __all__ = ['display', 'display_pretty', 'display_html', 'display_markdown',
23 23 'display_svg', 'display_png', 'display_jpeg', 'display_latex', 'display_json',
24 24 'display_javascript', 'display_pdf', 'DisplayObject', 'TextDisplayObject',
25 25 'Pretty', 'HTML', 'Markdown', 'Math', 'Latex', 'SVG', 'ProgressBar', 'JSON',
26 26 'GeoJSON', 'Javascript', 'Image', 'clear_output', 'set_matplotlib_formats',
27 27 'set_matplotlib_close', 'publish_display_data', 'update_display', 'DisplayHandle',
28 28 'Video']
29 29
30 30 #-----------------------------------------------------------------------------
31 31 # utility functions
32 32 #-----------------------------------------------------------------------------
33 33
34 34 def _safe_exists(path):
35 35 """Check path, but don't let exceptions raise"""
36 36 try:
37 37 return os.path.exists(path)
38 38 except Exception:
39 39 return False
40 40
41 41 def _merge(d1, d2):
42 42 """Like update, but merges sub-dicts instead of clobbering at the top level.
43 43
44 44 Updates d1 in-place
45 45 """
46 46
47 47 if not isinstance(d2, dict) or not isinstance(d1, dict):
48 48 return d2
49 49 for key, value in d2.items():
50 50 d1[key] = _merge(d1.get(key), value)
51 51 return d1
52 52
53 53 def _display_mimetype(mimetype, objs, raw=False, metadata=None):
54 54 """internal implementation of all display_foo methods
55 55
56 56 Parameters
57 57 ----------
58 58 mimetype : str
59 59 The mimetype to be published (e.g. 'image/png')
60 60 objs : tuple of objects
61 61 The Python objects to display, or if raw=True raw text data to
62 62 display.
63 63 raw : bool
64 64 Are the data objects raw data or Python objects that need to be
65 65 formatted before display? [default: False]
66 66 metadata : dict (optional)
67 67 Metadata to be associated with the specific mimetype output.
68 68 """
69 69 if metadata:
70 70 metadata = {mimetype: metadata}
71 71 if raw:
72 72 # turn list of pngdata into list of { 'image/png': pngdata }
73 73 objs = [ {mimetype: obj} for obj in objs ]
74 74 display(*objs, raw=raw, metadata=metadata, include=[mimetype])
75 75
76 76 #-----------------------------------------------------------------------------
77 77 # Main functions
78 78 #-----------------------------------------------------------------------------
79 79
80 80 # use * to indicate transient is keyword-only
81 81 def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
82 82 """Publish data and metadata to all frontends.
83 83
84 84 See the ``display_data`` message in the messaging documentation for
85 85 more details about this message type.
86 86
87 87 Keys of data and metadata can be any mime-type.
88 88
89 89 Parameters
90 90 ----------
91 91 data : dict
92 92 A dictionary having keys that are valid MIME types (like
93 93 'text/plain' or 'image/svg+xml') and values that are the data for
94 94 that MIME type. The data itself must be a JSON'able data
95 95 structure. Minimally all data should have the 'text/plain' data,
96 96 which can be displayed by all frontends. If more than the plain
97 97 text is given, it is up to the frontend to decide which
98 98 representation to use.
99 99 metadata : dict
100 100 A dictionary for metadata related to the data. This can contain
101 101 arbitrary key, value pairs that frontends can use to interpret
102 102 the data. mime-type keys matching those in data can be used
103 103 to specify metadata about particular representations.
104 104 source : str, deprecated
105 105 Unused.
106 106 transient : dict, keyword-only
107 107 A dictionary of transient data, such as display_id.
108 108 """
109 109 from IPython.core.interactiveshell import InteractiveShell
110 110
111 111 display_pub = InteractiveShell.instance().display_pub
112 112
113 113 # only pass transient if supplied,
114 114 # to avoid errors with older ipykernel.
115 115 # TODO: We could check for ipykernel version and provide a detailed upgrade message.
116 116 if transient:
117 117 kwargs['transient'] = transient
118 118
119 119 display_pub.publish(
120 120 data=data,
121 121 metadata=metadata,
122 122 **kwargs
123 123 )
124 124
125 125
126 126 def _new_id():
127 127 """Generate a new random text id with urandom"""
128 128 return b2a_hex(os.urandom(16)).decode('ascii')
129 129
130 130
131 131 def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
132 132 """Display a Python object in all frontends.
133 133
134 134 By default all representations will be computed and sent to the frontends.
135 135 Frontends can decide which representation is used and how.
136 136
137 137 In terminal IPython this will be similar to using :func:`print`, for use in richer
138 138 frontends see Jupyter notebook examples with rich display logic.
139 139
140 140 Parameters
141 141 ----------
142 142 objs : tuple of objects
143 143 The Python objects to display.
144 144 raw : bool, optional
145 145 Are the objects to be displayed already mimetype-keyed dicts of raw display data,
146 146 or Python objects that need to be formatted before display? [default: False]
147 147 include : list, tuple or set, optional
148 148 A list of format type strings (MIME types) to include in the
149 149 format data dict. If this is set *only* the format types included
150 150 in this list will be computed.
151 151 exclude : list, tuple or set, optional
152 152 A list of format type strings (MIME types) to exclude in the format
153 153 data dict. If this is set all format types will be computed,
154 154 except for those included in this argument.
155 155 metadata : dict, optional
156 156 A dictionary of metadata to associate with the output.
157 157 mime-type keys in this dictionary will be associated with the individual
158 158 representation formats, if they exist.
159 159 transient : dict, optional
160 160 A dictionary of transient data to associate with the output.
161 161 Data in this dict should not be persisted to files (e.g. notebooks).
162 162 display_id : str, bool optional
163 163 Set an id for the display.
164 164 This id can be used for updating this display area later via update_display.
165 165 If given as `True`, generate a new `display_id`
166 166 kwargs: additional keyword-args, optional
167 167 Additional keyword-arguments are passed through to the display publisher.
168 168
169 169 Returns
170 170 -------
171 171
172 172 handle: DisplayHandle
173 173 Returns a handle on updatable displays for use with :func:`update_display`,
174 174 if `display_id` is given. Returns :any:`None` if no `display_id` is given
175 175 (default).
176 176
177 177 Examples
178 178 --------
179 179
180 180 >>> class Json(object):
181 181 ... def __init__(self, json):
182 182 ... self.json = json
183 183 ... def _repr_pretty_(self, pp, cycle):
184 184 ... import json
185 185 ... pp.text(json.dumps(self.json, indent=2))
186 186 ... def __repr__(self):
187 187 ... return str(self.json)
188 188 ...
189 189
190 190 >>> d = Json({1:2, 3: {4:5}})
191 191
192 192 >>> print(d)
193 193 {1: 2, 3: {4: 5}}
194 194
195 195 >>> display(d)
196 196 {
197 197 "1": 2,
198 198 "3": {
199 199 "4": 5
200 200 }
201 201 }
202 202
203 203 >>> def int_formatter(integer, pp, cycle):
204 204 ... pp.text('I'*integer)
205 205
206 206 >>> plain = get_ipython().display_formatter.formatters['text/plain']
207 207 >>> plain.for_type(int, int_formatter)
208 208 <function _repr_pprint at 0x...>
209 209 >>> display(7-5)
210 210 II
211 211
212 212 >>> del plain.type_printers[int]
213 213 >>> display(7-5)
214 214 2
215 215
216 216 See Also
217 217 --------
218 218
219 219 :func:`update_display`
220 220
221 221 Notes
222 222 -----
223 223
224 224 In Python, objects can declare their textual representation using the
225 225 `__repr__` method. IPython expands on this idea and allows objects to declare
226 226 other, rich representations including:
227 227
228 228 - HTML
229 229 - JSON
230 230 - PNG
231 231 - JPEG
232 232 - SVG
233 233 - LaTeX
234 234
235 235 A single object can declare some or all of these representations; all are
236 236 handled by IPython's display system.
237 237
238 238 The main idea of the first approach is that you have to implement special
239 239 display methods when you define your class, one for each representation you
240 240 want to use. Here is a list of the names of the special methods and the
241 241 values they must return:
242 242
243 243 - `_repr_html_`: return raw HTML as a string, or a tuple (see below).
244 244 - `_repr_json_`: return a JSONable dict, or a tuple (see below).
245 245 - `_repr_jpeg_`: return raw JPEG data, or a tuple (see below).
246 246 - `_repr_png_`: return raw PNG data, or a tuple (see below).
247 247 - `_repr_svg_`: return raw SVG data as a string, or a tuple (see below).
248 248 - `_repr_latex_`: return LaTeX commands in a string surrounded by "$",
249 249 or a tuple (see below).
250 250 - `_repr_mimebundle_`: return a full mimebundle containing the mapping
251 251 from all mimetypes to data.
252 252 Use this for any mime-type not listed above.
253 253
254 254 The above functions may also return the object's metadata alonside the
255 255 data. If the metadata is available, the functions will return a tuple
256 256 containing the data and metadata, in that order. If there is no metadata
257 257 available, then the functions will return the data only.
258 258
259 259 When you are directly writing your own classes, you can adapt them for
260 260 display in IPython by following the above approach. But in practice, you
261 261 often need to work with existing classes that you can't easily modify.
262 262
263 263 You can refer to the documentation on integrating with the display system in
264 264 order to register custom formatters for already existing types
265 265 (:ref:`integrating_rich_display`).
266 266
267 267 .. versionadded:: 5.4 display available without import
268 268 .. versionadded:: 6.1 display available without import
269 269
270 270 Since IPython 5.4 and 6.1 :func:`display` is automatically made available to
271 271 the user without import. If you are using display in a document that might
272 272 be used in a pure python context or with older version of IPython, use the
273 273 following import at the top of your file::
274 274
275 275 from IPython.display import display
276 276
277 277 """
278 278 from IPython.core.interactiveshell import InteractiveShell
279 279
280 280 if not InteractiveShell.initialized():
281 281 # Directly print objects.
282 282 print(*objs)
283 283 return
284 284
285 285 raw = kwargs.pop('raw', False)
286 286 if transient is None:
287 287 transient = {}
288 288 if metadata is None:
289 289 metadata={}
290 290 if display_id:
291 291 if display_id is True:
292 292 display_id = _new_id()
293 293 transient['display_id'] = display_id
294 294 if kwargs.get('update') and 'display_id' not in transient:
295 295 raise TypeError('display_id required for update_display')
296 296 if transient:
297 297 kwargs['transient'] = transient
298 298
299 299 if not objs and display_id:
300 300 # if given no objects, but still a request for a display_id,
301 301 # we assume the user wants to insert an empty output that
302 302 # can be updated later
303 303 objs = [{}]
304 304 raw = True
305 305
306 306 if not raw:
307 307 format = InteractiveShell.instance().display_formatter.format
308 308
309 309 for obj in objs:
310 310 if raw:
311 311 publish_display_data(data=obj, metadata=metadata, **kwargs)
312 312 else:
313 313 format_dict, md_dict = format(obj, include=include, exclude=exclude)
314 314 if not format_dict:
315 315 # nothing to display (e.g. _ipython_display_ took over)
316 316 continue
317 317 if metadata:
318 318 # kwarg-specified metadata gets precedence
319 319 _merge(md_dict, metadata)
320 320 publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
321 321 if display_id:
322 322 return DisplayHandle(display_id)
323 323
324 324
325 325 # use * for keyword-only display_id arg
326 326 def update_display(obj, *, display_id, **kwargs):
327 327 """Update an existing display by id
328 328
329 329 Parameters
330 330 ----------
331 331
332 332 obj:
333 333 The object with which to update the display
334 334 display_id: keyword-only
335 335 The id of the display to update
336 336
337 337 See Also
338 338 --------
339 339
340 340 :func:`display`
341 341 """
342 342 kwargs['update'] = True
343 343 display(obj, display_id=display_id, **kwargs)
344 344
345 345
346 346 class DisplayHandle(object):
347 347 """A handle on an updatable display
348 348
349 349 Call `.update(obj)` to display a new object.
350 350
351 351 Call `.display(obj`) to add a new instance of this display,
352 352 and update existing instances.
353 353
354 354 See Also
355 355 --------
356 356
357 357 :func:`display`, :func:`update_display`
358 358
359 359 """
360 360
361 361 def __init__(self, display_id=None):
362 362 if display_id is None:
363 363 display_id = _new_id()
364 364 self.display_id = display_id
365 365
366 366 def __repr__(self):
367 367 return "<%s display_id=%s>" % (self.__class__.__name__, self.display_id)
368 368
369 369 def display(self, obj, **kwargs):
370 370 """Make a new display with my id, updating existing instances.
371 371
372 372 Parameters
373 373 ----------
374 374
375 375 obj:
376 376 object to display
377 377 **kwargs:
378 378 additional keyword arguments passed to display
379 379 """
380 380 display(obj, display_id=self.display_id, **kwargs)
381 381
382 382 def update(self, obj, **kwargs):
383 383 """Update existing displays with my id
384 384
385 385 Parameters
386 386 ----------
387 387
388 388 obj:
389 389 object to display
390 390 **kwargs:
391 391 additional keyword arguments passed to update_display
392 392 """
393 393 update_display(obj, display_id=self.display_id, **kwargs)
394 394
395 395
396 396 def display_pretty(*objs, **kwargs):
397 397 """Display the pretty (default) representation of an object.
398 398
399 399 Parameters
400 400 ----------
401 401 objs : tuple of objects
402 402 The Python objects to display, or if raw=True raw text data to
403 403 display.
404 404 raw : bool
405 405 Are the data objects raw data or Python objects that need to be
406 406 formatted before display? [default: False]
407 407 metadata : dict (optional)
408 408 Metadata to be associated with the specific mimetype output.
409 409 """
410 410 _display_mimetype('text/plain', objs, **kwargs)
411 411
412 412
413 413 def display_html(*objs, **kwargs):
414 414 """Display the HTML representation of an object.
415 415
416 416 Note: If raw=False and the object does not have a HTML
417 417 representation, no HTML will be shown.
418 418
419 419 Parameters
420 420 ----------
421 421 objs : tuple of objects
422 422 The Python objects to display, or if raw=True raw HTML data to
423 423 display.
424 424 raw : bool
425 425 Are the data objects raw data or Python objects that need to be
426 426 formatted before display? [default: False]
427 427 metadata : dict (optional)
428 428 Metadata to be associated with the specific mimetype output.
429 429 """
430 430 _display_mimetype('text/html', objs, **kwargs)
431 431
432 432
433 433 def display_markdown(*objs, **kwargs):
434 434 """Displays the Markdown representation of an object.
435 435
436 436 Parameters
437 437 ----------
438 438 objs : tuple of objects
439 439 The Python objects to display, or if raw=True raw markdown data to
440 440 display.
441 441 raw : bool
442 442 Are the data objects raw data or Python objects that need to be
443 443 formatted before display? [default: False]
444 444 metadata : dict (optional)
445 445 Metadata to be associated with the specific mimetype output.
446 446 """
447 447
448 448 _display_mimetype('text/markdown', objs, **kwargs)
449 449
450 450
451 451 def display_svg(*objs, **kwargs):
452 452 """Display the SVG representation of an object.
453 453
454 454 Parameters
455 455 ----------
456 456 objs : tuple of objects
457 457 The Python objects to display, or if raw=True raw svg data to
458 458 display.
459 459 raw : bool
460 460 Are the data objects raw data or Python objects that need to be
461 461 formatted before display? [default: False]
462 462 metadata : dict (optional)
463 463 Metadata to be associated with the specific mimetype output.
464 464 """
465 465 _display_mimetype('image/svg+xml', objs, **kwargs)
466 466
467 467
468 468 def display_png(*objs, **kwargs):
469 469 """Display the PNG representation of an object.
470 470
471 471 Parameters
472 472 ----------
473 473 objs : tuple of objects
474 474 The Python objects to display, or if raw=True raw png data to
475 475 display.
476 476 raw : bool
477 477 Are the data objects raw data or Python objects that need to be
478 478 formatted before display? [default: False]
479 479 metadata : dict (optional)
480 480 Metadata to be associated with the specific mimetype output.
481 481 """
482 482 _display_mimetype('image/png', objs, **kwargs)
483 483
484 484
485 485 def display_jpeg(*objs, **kwargs):
486 486 """Display the JPEG representation of an object.
487 487
488 488 Parameters
489 489 ----------
490 490 objs : tuple of objects
491 491 The Python objects to display, or if raw=True raw JPEG data to
492 492 display.
493 493 raw : bool
494 494 Are the data objects raw data or Python objects that need to be
495 495 formatted before display? [default: False]
496 496 metadata : dict (optional)
497 497 Metadata to be associated with the specific mimetype output.
498 498 """
499 499 _display_mimetype('image/jpeg', objs, **kwargs)
500 500
501 501
502 502 def display_latex(*objs, **kwargs):
503 503 """Display the LaTeX representation of an object.
504 504
505 505 Parameters
506 506 ----------
507 507 objs : tuple of objects
508 508 The Python objects to display, or if raw=True raw latex data to
509 509 display.
510 510 raw : bool
511 511 Are the data objects raw data or Python objects that need to be
512 512 formatted before display? [default: False]
513 513 metadata : dict (optional)
514 514 Metadata to be associated with the specific mimetype output.
515 515 """
516 516 _display_mimetype('text/latex', objs, **kwargs)
517 517
518 518
519 519 def display_json(*objs, **kwargs):
520 520 """Display the JSON representation of an object.
521 521
522 522 Note that not many frontends support displaying JSON.
523 523
524 524 Parameters
525 525 ----------
526 526 objs : tuple of objects
527 527 The Python objects to display, or if raw=True raw json data to
528 528 display.
529 529 raw : bool
530 530 Are the data objects raw data or Python objects that need to be
531 531 formatted before display? [default: False]
532 532 metadata : dict (optional)
533 533 Metadata to be associated with the specific mimetype output.
534 534 """
535 535 _display_mimetype('application/json', objs, **kwargs)
536 536
537 537
538 538 def display_javascript(*objs, **kwargs):
539 539 """Display the Javascript representation of an object.
540 540
541 541 Parameters
542 542 ----------
543 543 objs : tuple of objects
544 544 The Python objects to display, or if raw=True raw javascript data to
545 545 display.
546 546 raw : bool
547 547 Are the data objects raw data or Python objects that need to be
548 548 formatted before display? [default: False]
549 549 metadata : dict (optional)
550 550 Metadata to be associated with the specific mimetype output.
551 551 """
552 552 _display_mimetype('application/javascript', objs, **kwargs)
553 553
554 554
555 555 def display_pdf(*objs, **kwargs):
556 556 """Display the PDF representation of an object.
557 557
558 558 Parameters
559 559 ----------
560 560 objs : tuple of objects
561 561 The Python objects to display, or if raw=True raw javascript data to
562 562 display.
563 563 raw : bool
564 564 Are the data objects raw data or Python objects that need to be
565 565 formatted before display? [default: False]
566 566 metadata : dict (optional)
567 567 Metadata to be associated with the specific mimetype output.
568 568 """
569 569 _display_mimetype('application/pdf', objs, **kwargs)
570 570
571 571
572 572 #-----------------------------------------------------------------------------
573 573 # Smart classes
574 574 #-----------------------------------------------------------------------------
575 575
576 576
577 577 class DisplayObject(object):
578 578 """An object that wraps data to be displayed."""
579 579
580 580 _read_flags = 'r'
581 581 _show_mem_addr = False
582 582 metadata = None
583 583
584 584 def __init__(self, data=None, url=None, filename=None, metadata=None):
585 585 """Create a display object given raw data.
586 586
587 587 When this object is returned by an expression or passed to the
588 588 display function, it will result in the data being displayed
589 589 in the frontend. The MIME type of the data should match the
590 590 subclasses used, so the Png subclass should be used for 'image/png'
591 591 data. If the data is a URL, the data will first be downloaded
592 592 and then displayed. If
593 593
594 594 Parameters
595 595 ----------
596 596 data : unicode, str or bytes
597 597 The raw data or a URL or file to load the data from
598 598 url : unicode
599 599 A URL to download the data from.
600 600 filename : unicode
601 601 Path to a local file to load the data from.
602 602 metadata : dict
603 603 Dict of metadata associated to be the object when displayed
604 604 """
605 605 if isinstance(data, (Path, PurePath)):
606 606 data = str(data)
607 607
608 608 if data is not None and isinstance(data, str):
609 609 if data.startswith('http') and url is None:
610 610 url = data
611 611 filename = None
612 612 data = None
613 613 elif _safe_exists(data) and filename is None:
614 614 url = None
615 615 filename = data
616 616 data = None
617 617
618 618 self.url = url
619 619 self.filename = filename
620 620 # because of @data.setter methods in
621 621 # subclasses ensure url and filename are set
622 622 # before assigning to self.data
623 623 self.data = data
624 624
625 625 if metadata is not None:
626 626 self.metadata = metadata
627 627 elif self.metadata is None:
628 628 self.metadata = {}
629 629
630 630 self.reload()
631 631 self._check_data()
632 632
633 633 def __repr__(self):
634 634 if not self._show_mem_addr:
635 635 cls = self.__class__
636 636 r = "<%s.%s object>" % (cls.__module__, cls.__name__)
637 637 else:
638 638 r = super(DisplayObject, self).__repr__()
639 639 return r
640 640
641 641 def _check_data(self):
642 642 """Override in subclasses if there's something to check."""
643 643 pass
644 644
645 645 def _data_and_metadata(self):
646 646 """shortcut for returning metadata with shape information, if defined"""
647 647 if self.metadata:
648 648 return self.data, deepcopy(self.metadata)
649 649 else:
650 650 return self.data
651 651
652 652 def reload(self):
653 653 """Reload the raw data from file or URL."""
654 654 if self.filename is not None:
655 655 with open(self.filename, self._read_flags) as f:
656 656 self.data = f.read()
657 657 elif self.url is not None:
658 658 # Deferred import
659 659 from urllib.request import urlopen
660 660 response = urlopen(self.url)
661 661 data = response.read()
662 662 # extract encoding from header, if there is one:
663 663 encoding = None
664 664 if 'content-type' in response.headers:
665 665 for sub in response.headers['content-type'].split(';'):
666 666 sub = sub.strip()
667 667 if sub.startswith('charset'):
668 668 encoding = sub.split('=')[-1].strip()
669 669 break
670 670 if 'content-encoding' in response.headers:
671 671 # TODO: do deflate?
672 672 if 'gzip' in response.headers['content-encoding']:
673 673 import gzip
674 674 from io import BytesIO
675 675 with gzip.open(BytesIO(data), 'rt', encoding=encoding) as fp:
676 676 encoding = None
677 677 data = fp.read()
678 678
679 679 # decode data, if an encoding was specified
680 680 # We only touch self.data once since
681 681 # subclasses such as SVG have @data.setter methods
682 682 # that transform self.data into ... well svg.
683 683 if encoding:
684 684 self.data = data.decode(encoding, 'replace')
685 685 else:
686 686 self.data = data
687 687
688 688
689 689 class TextDisplayObject(DisplayObject):
690 690 """Validate that display data is text"""
691 691 def _check_data(self):
692 692 if self.data is not None and not isinstance(self.data, str):
693 693 raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
694 694
695 695 class Pretty(TextDisplayObject):
696 696
697 697 def _repr_pretty_(self, pp, cycle):
698 698 return pp.text(self.data)
699 699
700 700
701 701 class HTML(TextDisplayObject):
702 702
703 703 def __init__(self, data=None, url=None, filename=None, metadata=None):
704 704 def warn():
705 705 if not data:
706 706 return False
707 707
708 708 #
709 709 # Avoid calling lower() on the entire data, because it could be a
710 710 # long string and we're only interested in its beginning and end.
711 711 #
712 712 prefix = data[:10].lower()
713 713 suffix = data[-10:].lower()
714 714 return prefix.startswith("<iframe ") and suffix.endswith("</iframe>")
715 715
716 716 if warn():
717 717 warnings.warn("Consider using IPython.display.IFrame instead")
718 718 super(HTML, self).__init__(data=data, url=url, filename=filename, metadata=metadata)
719 719
720 720 def _repr_html_(self):
721 721 return self._data_and_metadata()
722 722
723 723 def __html__(self):
724 724 """
725 725 This method exists to inform other HTML-using modules (e.g. Markupsafe,
726 726 htmltag, etc) that this object is HTML and does not need things like
727 727 special characters (<>&) escaped.
728 728 """
729 729 return self._repr_html_()
730 730
731 731
732 732 class Markdown(TextDisplayObject):
733 733
734 734 def _repr_markdown_(self):
735 735 return self._data_and_metadata()
736 736
737 737
738 738 class Math(TextDisplayObject):
739 739
740 740 def _repr_latex_(self):
741 741 s = r"$\displaystyle %s$" % self.data.strip('$')
742 742 if self.metadata:
743 743 return s, deepcopy(self.metadata)
744 744 else:
745 745 return s
746 746
747 747
748 748 class Latex(TextDisplayObject):
749 749
750 750 def _repr_latex_(self):
751 751 return self._data_and_metadata()
752 752
753 753
754 754 class SVG(DisplayObject):
755 755 """Embed an SVG into the display.
756 756
757 757 Note if you just want to view a svg image via a URL use `:class:Image` with
758 758 a url=URL keyword argument.
759 759 """
760 760
761 761 _read_flags = 'rb'
762 762 # wrap data in a property, which extracts the <svg> tag, discarding
763 763 # document headers
764 764 _data = None
765 765
766 766 @property
767 767 def data(self):
768 768 return self._data
769 769
770 770 @data.setter
771 771 def data(self, svg):
772 772 if svg is None:
773 773 self._data = None
774 774 return
775 775 # parse into dom object
776 776 from xml.dom import minidom
777 777 x = minidom.parseString(svg)
778 778 # get svg tag (should be 1)
779 779 found_svg = x.getElementsByTagName('svg')
780 780 if found_svg:
781 781 svg = found_svg[0].toxml()
782 782 else:
783 783 # fallback on the input, trust the user
784 784 # but this is probably an error.
785 785 pass
786 786 svg = cast_unicode(svg)
787 787 self._data = svg
788 788
789 789 def _repr_svg_(self):
790 790 return self._data_and_metadata()
791 791
792 792 class ProgressBar(DisplayObject):
793 793 """Progressbar supports displaying a progressbar like element
794 794 """
795 795 def __init__(self, total):
796 796 """Creates a new progressbar
797 797
798 798 Parameters
799 799 ----------
800 800 total : int
801 801 maximum size of the progressbar
802 802 """
803 803 self.total = total
804 804 self._progress = 0
805 805 self.html_width = '60ex'
806 806 self.text_width = 60
807 807 self._display_id = hexlify(os.urandom(8)).decode('ascii')
808 808
809 809 def __repr__(self):
810 810 fraction = self.progress / self.total
811 811 filled = '=' * int(fraction * self.text_width)
812 812 rest = ' ' * (self.text_width - len(filled))
813 813 return '[{}{}] {}/{}'.format(
814 814 filled, rest,
815 815 self.progress, self.total,
816 816 )
817 817
818 818 def _repr_html_(self):
819 819 return "<progress style='width:{}' max='{}' value='{}'></progress>".format(
820 820 self.html_width, self.total, self.progress)
821 821
822 822 def display(self):
823 823 display(self, display_id=self._display_id)
824 824
825 825 def update(self):
826 826 display(self, display_id=self._display_id, update=True)
827 827
828 828 @property
829 829 def progress(self):
830 830 return self._progress
831 831
832 832 @progress.setter
833 833 def progress(self, value):
834 834 self._progress = value
835 835 self.update()
836 836
837 837 def __iter__(self):
838 838 self.display()
839 839 self._progress = -1 # First iteration is 0
840 840 return self
841 841
842 842 def __next__(self):
843 843 """Returns current value and increments display by one."""
844 844 self.progress += 1
845 845 if self.progress < self.total:
846 846 return self.progress
847 847 else:
848 848 raise StopIteration()
849 849
850 850 class JSON(DisplayObject):
851 851 """JSON expects a JSON-able dict or list
852 852
853 853 not an already-serialized JSON string.
854 854
855 855 Scalar types (None, number, string) are not allowed, only dict or list containers.
856 856 """
857 857 # wrap data in a property, which warns about passing already-serialized JSON
858 858 _data = None
859 859 def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, root='root', **kwargs):
860 860 """Create a JSON display object given raw data.
861 861
862 862 Parameters
863 863 ----------
864 864 data : dict or list
865 865 JSON data to display. Not an already-serialized JSON string.
866 866 Scalar types (None, number, string) are not allowed, only dict
867 867 or list containers.
868 868 url : unicode
869 869 A URL to download the data from.
870 870 filename : unicode
871 871 Path to a local file to load the data from.
872 872 expanded : boolean
873 873 Metadata to control whether a JSON display component is expanded.
874 874 metadata: dict
875 875 Specify extra metadata to attach to the json display object.
876 876 root : str
877 877 The name of the root element of the JSON tree
878 878 """
879 879 self.metadata = {
880 880 'expanded': expanded,
881 881 'root': root,
882 882 }
883 883 if metadata:
884 884 self.metadata.update(metadata)
885 885 if kwargs:
886 886 self.metadata.update(kwargs)
887 887 super(JSON, self).__init__(data=data, url=url, filename=filename)
888 888
889 889 def _check_data(self):
890 890 if self.data is not None and not isinstance(self.data, (dict, list)):
891 891 raise TypeError("%s expects JSONable dict or list, not %r" % (self.__class__.__name__, self.data))
892 892
893 893 @property
894 894 def data(self):
895 895 return self._data
896 896
897 897 @data.setter
898 898 def data(self, data):
899 899 if isinstance(data, (Path, PurePath)):
900 900 data = str(data)
901 901
902 902 if isinstance(data, str):
903 903 if self.filename is None and self.url is None:
904 904 warnings.warn("JSON expects JSONable dict or list, not JSON strings")
905 905 data = json.loads(data)
906 906 self._data = data
907 907
908 908 def _data_and_metadata(self):
909 909 return self.data, self.metadata
910 910
911 911 def _repr_json_(self):
912 912 return self._data_and_metadata()
913 913
914 914 _css_t = """var link = document.createElement("link");
915 915 link.ref = "stylesheet";
916 916 link.type = "text/css";
917 917 link.href = "%s";
918 918 document.head.appendChild(link);
919 919 """
920 920
921 921 _lib_t1 = """new Promise(function(resolve, reject) {
922 922 var script = document.createElement("script");
923 923 script.onload = resolve;
924 924 script.onerror = reject;
925 925 script.src = "%s";
926 926 document.head.appendChild(script);
927 927 }).then(() => {
928 928 """
929 929
930 930 _lib_t2 = """
931 931 });"""
932 932
933 933 class GeoJSON(JSON):
934 934 """GeoJSON expects JSON-able dict
935 935
936 936 not an already-serialized JSON string.
937 937
938 938 Scalar types (None, number, string) are not allowed, only dict containers.
939 939 """
940 940
941 941 def __init__(self, *args, **kwargs):
942 942 """Create a GeoJSON display object given raw data.
943 943
944 944 Parameters
945 945 ----------
946 946 data : dict or list
947 947 VegaLite data. Not an already-serialized JSON string.
948 948 Scalar types (None, number, string) are not allowed, only dict
949 949 or list containers.
950 950 url_template : string
951 951 Leaflet TileLayer URL template: http://leafletjs.com/reference.html#url-template
952 952 layer_options : dict
953 953 Leaflet TileLayer options: http://leafletjs.com/reference.html#tilelayer-options
954 954 url : unicode
955 955 A URL to download the data from.
956 956 filename : unicode
957 957 Path to a local file to load the data from.
958 958 metadata: dict
959 959 Specify extra metadata to attach to the json display object.
960 960
961 961 Examples
962 962 --------
963 963
964 964 The following will display an interactive map of Mars with a point of
965 965 interest on frontend that do support GeoJSON display.
966 966
967 967 >>> from IPython.display import GeoJSON
968 968
969 969 >>> GeoJSON(data={
970 970 ... "type": "Feature",
971 971 ... "geometry": {
972 972 ... "type": "Point",
973 973 ... "coordinates": [-81.327, 296.038]
974 974 ... }
975 975 ... },
976 976 ... url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png",
977 977 ... layer_options={
978 978 ... "basemap_id": "celestia_mars-shaded-16k_global",
979 979 ... "attribution" : "Celestia/praesepe",
980 980 ... "minZoom" : 0,
981 981 ... "maxZoom" : 18,
982 982 ... })
983 983 <IPython.core.display.GeoJSON object>
984 984
985 985 In the terminal IPython, you will only see the text representation of
986 986 the GeoJSON object.
987 987
988 988 """
989 989
990 990 super(GeoJSON, self).__init__(*args, **kwargs)
991 991
992 992
993 993 def _ipython_display_(self):
994 994 bundle = {
995 995 'application/geo+json': self.data,
996 996 'text/plain': '<IPython.display.GeoJSON object>'
997 997 }
998 998 metadata = {
999 999 'application/geo+json': self.metadata
1000 1000 }
1001 1001 display(bundle, metadata=metadata, raw=True)
1002 1002
1003 1003 class Javascript(TextDisplayObject):
1004 1004
1005 1005 def __init__(self, data=None, url=None, filename=None, lib=None, css=None):
1006 1006 """Create a Javascript display object given raw data.
1007 1007
1008 1008 When this object is returned by an expression or passed to the
1009 1009 display function, it will result in the data being displayed
1010 1010 in the frontend. If the data is a URL, the data will first be
1011 1011 downloaded and then displayed.
1012 1012
1013 1013 In the Notebook, the containing element will be available as `element`,
1014 1014 and jQuery will be available. Content appended to `element` will be
1015 1015 visible in the output area.
1016 1016
1017 1017 Parameters
1018 1018 ----------
1019 1019 data : unicode, str or bytes
1020 1020 The Javascript source code or a URL to download it from.
1021 1021 url : unicode
1022 1022 A URL to download the data from.
1023 1023 filename : unicode
1024 1024 Path to a local file to load the data from.
1025 1025 lib : list or str
1026 1026 A sequence of Javascript library URLs to load asynchronously before
1027 1027 running the source code. The full URLs of the libraries should
1028 1028 be given. A single Javascript library URL can also be given as a
1029 1029 string.
1030 1030 css: : list or str
1031 1031 A sequence of css files to load before running the source code.
1032 1032 The full URLs of the css files should be given. A single css URL
1033 1033 can also be given as a string.
1034 1034 """
1035 1035 if isinstance(lib, str):
1036 1036 lib = [lib]
1037 1037 elif lib is None:
1038 1038 lib = []
1039 1039 if isinstance(css, str):
1040 1040 css = [css]
1041 1041 elif css is None:
1042 1042 css = []
1043 1043 if not isinstance(lib, (list,tuple)):
1044 1044 raise TypeError('expected sequence, got: %r' % lib)
1045 1045 if not isinstance(css, (list,tuple)):
1046 1046 raise TypeError('expected sequence, got: %r' % css)
1047 1047 self.lib = lib
1048 1048 self.css = css
1049 1049 super(Javascript, self).__init__(data=data, url=url, filename=filename)
1050 1050
1051 1051 def _repr_javascript_(self):
1052 1052 r = ''
1053 1053 for c in self.css:
1054 1054 r += _css_t % c
1055 1055 for l in self.lib:
1056 1056 r += _lib_t1 % l
1057 1057 r += self.data
1058 1058 r += _lib_t2*len(self.lib)
1059 1059 return r
1060 1060
1061 1061 # constants for identifying png/jpeg data
1062 1062 _PNG = b'\x89PNG\r\n\x1a\n'
1063 1063 _JPEG = b'\xff\xd8'
1064 1064
1065 1065 def _pngxy(data):
1066 1066 """read the (width, height) from a PNG header"""
1067 1067 ihdr = data.index(b'IHDR')
1068 1068 # next 8 bytes are width/height
1069 1069 return struct.unpack('>ii', data[ihdr+4:ihdr+12])
1070 1070
1071 1071 def _jpegxy(data):
1072 1072 """read the (width, height) from a JPEG header"""
1073 1073 # adapted from http://www.64lines.com/jpeg-width-height
1074 1074
1075 1075 idx = 4
1076 1076 while True:
1077 1077 block_size = struct.unpack('>H', data[idx:idx+2])[0]
1078 1078 idx = idx + block_size
1079 1079 if data[idx:idx+2] == b'\xFF\xC0':
1080 1080 # found Start of Frame
1081 1081 iSOF = idx
1082 1082 break
1083 1083 else:
1084 1084 # read another block
1085 1085 idx += 2
1086 1086
1087 1087 h, w = struct.unpack('>HH', data[iSOF+5:iSOF+9])
1088 1088 return w, h
1089 1089
1090 1090 def _gifxy(data):
1091 1091 """read the (width, height) from a GIF header"""
1092 1092 return struct.unpack('<HH', data[6:10])
1093 1093
1094 1094
1095 1095 class Image(DisplayObject):
1096 1096
1097 1097 _read_flags = 'rb'
1098 1098 _FMT_JPEG = u'jpeg'
1099 1099 _FMT_PNG = u'png'
1100 1100 _FMT_GIF = u'gif'
1101 1101 _ACCEPTABLE_EMBEDDINGS = [_FMT_JPEG, _FMT_PNG, _FMT_GIF]
1102 1102 _MIMETYPES = {
1103 1103 _FMT_PNG: 'image/png',
1104 1104 _FMT_JPEG: 'image/jpeg',
1105 1105 _FMT_GIF: 'image/gif',
1106 1106 }
1107 1107
1108 1108 def __init__(self, data=None, url=None, filename=None, format=None,
1109 1109 embed=None, width=None, height=None, retina=False,
1110 1110 unconfined=False, metadata=None):
1111 1111 """Create a PNG/JPEG/GIF image object given raw data.
1112 1112
1113 1113 When this object is returned by an input cell or passed to the
1114 1114 display function, it will result in the image being displayed
1115 1115 in the frontend.
1116 1116
1117 1117 Parameters
1118 1118 ----------
1119 1119 data : unicode, str or bytes
1120 1120 The raw image data or a URL or filename to load the data from.
1121 1121 This always results in embedded image data.
1122 1122 url : unicode
1123 1123 A URL to download the data from. If you specify `url=`,
1124 1124 the image data will not be embedded unless you also specify `embed=True`.
1125 1125 filename : unicode
1126 1126 Path to a local file to load the data from.
1127 1127 Images from a file are always embedded.
1128 1128 format : unicode
1129 1129 The format of the image data (png/jpeg/jpg/gif). If a filename or URL is given
1130 1130 for format will be inferred from the filename extension.
1131 1131 embed : bool
1132 1132 Should the image data be embedded using a data URI (True) or be
1133 1133 loaded using an <img> tag. Set this to True if you want the image
1134 1134 to be viewable later with no internet connection in the notebook.
1135 1135
1136 1136 Default is `True`, unless the keyword argument `url` is set, then
1137 1137 default value is `False`.
1138 1138
1139 1139 Note that QtConsole is not able to display images if `embed` is set to `False`
1140 1140 width : int
1141 1141 Width in pixels to which to constrain the image in html
1142 1142 height : int
1143 1143 Height in pixels to which to constrain the image in html
1144 1144 retina : bool
1145 1145 Automatically set the width and height to half of the measured
1146 1146 width and height.
1147 1147 This only works for embedded images because it reads the width/height
1148 1148 from image data.
1149 1149 For non-embedded images, you can just set the desired display width
1150 1150 and height directly.
1151 1151 unconfined: bool
1152 1152 Set unconfined=True to disable max-width confinement of the image.
1153 1153 metadata: dict
1154 1154 Specify extra metadata to attach to the image.
1155 1155
1156 1156 Examples
1157 1157 --------
1158 1158 # embedded image data, works in qtconsole and notebook
1159 1159 # when passed positionally, the first arg can be any of raw image data,
1160 1160 # a URL, or a filename from which to load image data.
1161 1161 # The result is always embedding image data for inline images.
1162 1162 Image('http://www.google.fr/images/srpr/logo3w.png')
1163 1163 Image('/path/to/image.jpg')
1164 1164 Image(b'RAW_PNG_DATA...')
1165 1165
1166 1166 # Specifying Image(url=...) does not embed the image data,
1167 1167 # it only generates `<img>` tag with a link to the source.
1168 1168 # This will not work in the qtconsole or offline.
1169 1169 Image(url='http://www.google.fr/images/srpr/logo3w.png')
1170 1170
1171 1171 """
1172 1172 if isinstance(data, (Path, PurePath)):
1173 1173 data = str(data)
1174 1174
1175 1175 if filename is not None:
1176 1176 ext = self._find_ext(filename)
1177 1177 elif url is not None:
1178 1178 ext = self._find_ext(url)
1179 1179 elif data is None:
1180 1180 raise ValueError("No image data found. Expecting filename, url, or data.")
1181 1181 elif isinstance(data, str) and (
1182 1182 data.startswith('http') or _safe_exists(data)
1183 1183 ):
1184 1184 ext = self._find_ext(data)
1185 1185 else:
1186 1186 ext = None
1187 1187
1188 1188 if format is None:
1189 1189 if ext is not None:
1190 1190 if ext == u'jpg' or ext == u'jpeg':
1191 1191 format = self._FMT_JPEG
1192 1192 elif ext == u'png':
1193 1193 format = self._FMT_PNG
1194 1194 elif ext == u'gif':
1195 1195 format = self._FMT_GIF
1196 1196 else:
1197 1197 format = ext.lower()
1198 1198 elif isinstance(data, bytes):
1199 1199 # infer image type from image data header,
1200 1200 # only if format has not been specified.
1201 1201 if data[:2] == _JPEG:
1202 1202 format = self._FMT_JPEG
1203 1203
1204 1204 # failed to detect format, default png
1205 1205 if format is None:
1206 1206 format = self._FMT_PNG
1207 1207
1208 1208 if format.lower() == 'jpg':
1209 1209 # jpg->jpeg
1210 1210 format = self._FMT_JPEG
1211 1211
1212 1212 self.format = format.lower()
1213 1213 self.embed = embed if embed is not None else (url is None)
1214 1214
1215 1215 if self.embed and self.format not in self._ACCEPTABLE_EMBEDDINGS:
1216 1216 raise ValueError("Cannot embed the '%s' image format" % (self.format))
1217 1217 if self.embed:
1218 1218 self._mimetype = self._MIMETYPES.get(self.format)
1219 1219
1220 1220 self.width = width
1221 1221 self.height = height
1222 1222 self.retina = retina
1223 1223 self.unconfined = unconfined
1224 1224 super(Image, self).__init__(data=data, url=url, filename=filename,
1225 1225 metadata=metadata)
1226 1226
1227 1227 if self.width is None and self.metadata.get('width', {}):
1228 1228 self.width = metadata['width']
1229 1229
1230 1230 if self.height is None and self.metadata.get('height', {}):
1231 1231 self.height = metadata['height']
1232 1232
1233 1233 if retina:
1234 1234 self._retina_shape()
1235 1235
1236 1236
1237 1237 def _retina_shape(self):
1238 1238 """load pixel-doubled width and height from image data"""
1239 1239 if not self.embed:
1240 1240 return
1241 1241 if self.format == self._FMT_PNG:
1242 1242 w, h = _pngxy(self.data)
1243 1243 elif self.format == self._FMT_JPEG:
1244 1244 w, h = _jpegxy(self.data)
1245 1245 elif self.format == self._FMT_GIF:
1246 1246 w, h = _gifxy(self.data)
1247 1247 else:
1248 1248 # retina only supports png
1249 1249 return
1250 1250 self.width = w // 2
1251 1251 self.height = h // 2
1252 1252
1253 1253 def reload(self):
1254 1254 """Reload the raw data from file or URL."""
1255 1255 if self.embed:
1256 1256 super(Image,self).reload()
1257 1257 if self.retina:
1258 1258 self._retina_shape()
1259 1259
1260 1260 def _repr_html_(self):
1261 1261 if not self.embed:
1262 1262 width = height = klass = ''
1263 1263 if self.width:
1264 1264 width = ' width="%d"' % self.width
1265 1265 if self.height:
1266 1266 height = ' height="%d"' % self.height
1267 1267 if self.unconfined:
1268 1268 klass = ' class="unconfined"'
1269 1269 return u'<img src="{url}"{width}{height}{klass}/>'.format(
1270 1270 url=self.url,
1271 1271 width=width,
1272 1272 height=height,
1273 1273 klass=klass,
1274 1274 )
1275 1275
1276 1276 def _repr_mimebundle_(self, include=None, exclude=None):
1277 1277 """Return the image as a mimebundle
1278 1278
1279 1279 Any new mimetype support should be implemented here.
1280 1280 """
1281 1281 if self.embed:
1282 1282 mimetype = self._mimetype
1283 1283 data, metadata = self._data_and_metadata(always_both=True)
1284 1284 if metadata:
1285 1285 metadata = {mimetype: metadata}
1286 1286 return {mimetype: data}, metadata
1287 1287 else:
1288 1288 return {'text/html': self._repr_html_()}
1289 1289
1290 1290 def _data_and_metadata(self, always_both=False):
1291 1291 """shortcut for returning metadata with shape information, if defined"""
1292 1292 try:
1293 1293 b64_data = b2a_base64(self.data).decode('ascii')
1294 1294 except TypeError:
1295 1295 raise FileNotFoundError(
1296 1296 "No such file or directory: '%s'" % (self.data))
1297 1297 md = {}
1298 1298 if self.metadata:
1299 1299 md.update(self.metadata)
1300 1300 if self.width:
1301 1301 md['width'] = self.width
1302 1302 if self.height:
1303 1303 md['height'] = self.height
1304 1304 if self.unconfined:
1305 1305 md['unconfined'] = self.unconfined
1306 1306 if md or always_both:
1307 1307 return b64_data, md
1308 1308 else:
1309 1309 return b64_data
1310 1310
1311 1311 def _repr_png_(self):
1312 1312 if self.embed and self.format == self._FMT_PNG:
1313 1313 return self._data_and_metadata()
1314 1314
1315 1315 def _repr_jpeg_(self):
1316 1316 if self.embed and self.format == self._FMT_JPEG:
1317 1317 return self._data_and_metadata()
1318 1318
1319 1319 def _find_ext(self, s):
1320 1320 base, ext = splitext(s)
1321 1321
1322 1322 if not ext:
1323 1323 return base
1324 1324
1325 1325 # `splitext` includes leading period, so we skip it
1326 1326 return ext[1:].lower()
1327 1327
1328 1328
1329 1329 class Video(DisplayObject):
1330 1330
1331 1331 def __init__(self, data=None, url=None, filename=None, embed=False,
1332 1332 mimetype=None, width=None, height=None, html_attributes="controls"):
1333 1333 """Create a video object given raw data or an URL.
1334 1334
1335 1335 When this object is returned by an input cell or passed to the
1336 1336 display function, it will result in the video being displayed
1337 1337 in the frontend.
1338 1338
1339 1339 Parameters
1340 1340 ----------
1341 1341 data : unicode, str or bytes
1342 1342 The raw video data or a URL or filename to load the data from.
1343 Raw data will require passing `embed=True`.
1343 Raw data will require passing ``embed=True``.
1344 1344 url : unicode
1345 A URL for the video. If you specify `url=`,
1345 A URL for the video. If you specify ``url=``,
1346 1346 the image data will not be embedded.
1347 1347 filename : unicode
1348 1348 Path to a local file containing the video.
1349 Will be interpreted as a local URL unless `embed=True`.
1349 Will be interpreted as a local URL unless ``embed=True``.
1350 1350 embed : bool
1351 1351 Should the video be embedded using a data URI (True) or be
1352 1352 loaded using a <video> tag (False).
1353 1353
1354 1354 Since videos are large, embedding them should be avoided, if possible.
1355 You must confirm embedding as your intention by passing `embed=True`.
1355 You must confirm embedding as your intention by passing ``embed=True``.
1356 1356
1357 1357 Local files can be displayed with URLs without embedding the content, via::
1358 1358
1359 1359 Video('./video.mp4')
1360 1360
1361 1361 mimetype: unicode
1362 1362 Specify the mimetype for embedded videos.
1363 1363 Default will be guessed from file extension, if available.
1364 1364 width : int
1365 1365 Width in pixels to which to constrain the video in HTML.
1366 1366 If not supplied, defaults to the width of the video.
1367 1367 height : int
1368 1368 Height in pixels to which to constrain the video in html.
1369 1369 If not supplied, defaults to the height of the video.
1370 1370 html_attributes : str
1371 Attributes for the HTML `<video>` block.
1372 Default: `"controls"` to get video controls.
1373 Other examples: `"controls muted"` for muted video with controls,
1374 `"loop autoplay"` for looping autoplaying video without controls.
1371 Attributes for the HTML ``<video>`` block.
1372 Default: ``"controls"`` to get video controls.
1373 Other examples: ``"controls muted"`` for muted video with controls,
1374 ``"loop autoplay"`` for looping autoplaying video without controls.
1375 1375
1376 1376 Examples
1377 1377 --------
1378 1378
1379 1379 ::
1380 1380
1381 1381 Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
1382 1382 Video('path/to/video.mp4')
1383 1383 Video('path/to/video.mp4', embed=True)
1384 1384 Video('path/to/video.mp4', embed=True, html_attributes="controls muted autoplay")
1385 1385 Video(b'raw-videodata', embed=True)
1386 1386 """
1387 1387 if isinstance(data, (Path, PurePath)):
1388 1388 data = str(data)
1389 1389
1390 1390 if url is None and isinstance(data, str) and data.startswith(('http:', 'https:')):
1391 1391 url = data
1392 1392 data = None
1393 1393 elif os.path.exists(data):
1394 1394 filename = data
1395 1395 data = None
1396 1396
1397 1397 if data and not embed:
1398 1398 msg = ''.join([
1399 1399 "To embed videos, you must pass embed=True ",
1400 1400 "(this may make your notebook files huge)\n",
1401 1401 "Consider passing Video(url='...')",
1402 1402 ])
1403 1403 raise ValueError(msg)
1404 1404
1405 1405 self.mimetype = mimetype
1406 1406 self.embed = embed
1407 1407 self.width = width
1408 1408 self.height = height
1409 1409 self.html_attributes = html_attributes
1410 1410 super(Video, self).__init__(data=data, url=url, filename=filename)
1411 1411
1412 1412 def _repr_html_(self):
1413 1413 width = height = ''
1414 1414 if self.width:
1415 1415 width = ' width="%d"' % self.width
1416 1416 if self.height:
1417 1417 height = ' height="%d"' % self.height
1418 1418
1419 1419 # External URLs and potentially local files are not embedded into the
1420 1420 # notebook output.
1421 1421 if not self.embed:
1422 1422 url = self.url if self.url is not None else self.filename
1423 1423 output = """<video src="{0}" {1} {2} {3}>
1424 1424 Your browser does not support the <code>video</code> element.
1425 1425 </video>""".format(url, self.html_attributes, width, height)
1426 1426 return output
1427 1427
1428 1428 # Embedded videos are base64-encoded.
1429 1429 mimetype = self.mimetype
1430 1430 if self.filename is not None:
1431 1431 if not mimetype:
1432 1432 mimetype, _ = mimetypes.guess_type(self.filename)
1433 1433
1434 1434 with open(self.filename, 'rb') as f:
1435 1435 video = f.read()
1436 1436 else:
1437 1437 video = self.data
1438 1438 if isinstance(video, str):
1439 1439 # unicode input is already b64-encoded
1440 1440 b64_video = video
1441 1441 else:
1442 1442 b64_video = b2a_base64(video).decode('ascii').rstrip()
1443 1443
1444 1444 output = """<video {0} {1} {2}>
1445 1445 <source src="data:{3};base64,{4}" type="{3}">
1446 1446 Your browser does not support the video tag.
1447 1447 </video>""".format(self.html_attributes, width, height, mimetype, b64_video)
1448 1448 return output
1449 1449
1450 1450 def reload(self):
1451 1451 # TODO
1452 1452 pass
1453 1453
1454 1454
1455 1455 def clear_output(wait=False):
1456 1456 """Clear the output of the current cell receiving output.
1457 1457
1458 1458 Parameters
1459 1459 ----------
1460 1460 wait : bool [default: false]
1461 1461 Wait to clear the output until new output is available to replace it."""
1462 1462 from IPython.core.interactiveshell import InteractiveShell
1463 1463 if InteractiveShell.initialized():
1464 1464 InteractiveShell.instance().display_pub.clear_output(wait)
1465 1465 else:
1466 1466 print('\033[2K\r', end='')
1467 1467 sys.stdout.flush()
1468 1468 print('\033[2K\r', end='')
1469 1469 sys.stderr.flush()
1470 1470
1471 1471
1472 1472 @skip_doctest
1473 1473 def set_matplotlib_formats(*formats, **kwargs):
1474 1474 """Select figure formats for the inline backend. Optionally pass quality for JPEG.
1475 1475
1476 1476 For example, this enables PNG and JPEG output with a JPEG quality of 90%::
1477 1477
1478 1478 In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)
1479 1479
1480 1480 To set this in your config files use the following::
1481 1481
1482 1482 c.InlineBackend.figure_formats = {'png', 'jpeg'}
1483 1483 c.InlineBackend.print_figure_kwargs.update({'quality' : 90})
1484 1484
1485 1485 Parameters
1486 1486 ----------
1487 1487 *formats : strs
1488 1488 One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
1489 1489 **kwargs :
1490 1490 Keyword args will be relayed to ``figure.canvas.print_figure``.
1491 1491 """
1492 1492 from IPython.core.interactiveshell import InteractiveShell
1493 1493 from IPython.core.pylabtools import select_figure_formats
1494 1494 # build kwargs, starting with InlineBackend config
1495 1495 kw = {}
1496 1496 from ipykernel.pylab.config import InlineBackend
1497 1497 cfg = InlineBackend.instance()
1498 1498 kw.update(cfg.print_figure_kwargs)
1499 1499 kw.update(**kwargs)
1500 1500 shell = InteractiveShell.instance()
1501 1501 select_figure_formats(shell, formats, **kw)
1502 1502
1503 1503 @skip_doctest
1504 1504 def set_matplotlib_close(close=True):
1505 1505 """Set whether the inline backend closes all figures automatically or not.
1506 1506
1507 1507 By default, the inline backend used in the IPython Notebook will close all
1508 1508 matplotlib figures automatically after each cell is run. This means that
1509 1509 plots in different cells won't interfere. Sometimes, you may want to make
1510 1510 a plot in one cell and then refine it in later cells. This can be accomplished
1511 1511 by::
1512 1512
1513 1513 In [1]: set_matplotlib_close(False)
1514 1514
1515 1515 To set this in your config files use the following::
1516 1516
1517 1517 c.InlineBackend.close_figures = False
1518 1518
1519 1519 Parameters
1520 1520 ----------
1521 1521 close : bool
1522 1522 Should all matplotlib figures be automatically closed after each cell is
1523 1523 run?
1524 1524 """
1525 1525 from ipykernel.pylab.config import InlineBackend
1526 1526 cfg = InlineBackend.instance()
1527 1527 cfg.close_figures = close
General Comments 0
You need to be logged in to leave comments. Login now