##// END OF EJS Templates
fix autoge
Matthias Bussonnier -
Show More
@@ -1,2262 +1,2261 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 uuid
125 125 import warnings
126 126 from contextlib import contextmanager
127 127 from importlib import import_module
128 128 from types import SimpleNamespace
129 129 from typing import Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, NamedTuple, Pattern, Optional
130 130
131 131 from IPython.core.error import TryNext
132 132 from IPython.core.inputtransformer2 import ESC_MAGIC
133 133 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
134 134 from IPython.core.oinspect import InspectColors
135 135 from IPython.testing.skipdoctest import skip_doctest
136 136 from IPython.utils import generics
137 137 from IPython.utils.dir2 import dir2, get_real_method
138 138 from IPython.utils.path import ensure_dir_exists
139 139 from IPython.utils.process import arg_split
140 140 from traitlets import Bool, Enum, Int, List as ListTrait, Unicode, default, observe
141 141 from traitlets.config.configurable import Configurable
142 142
143 143 import __main__
144 144
145 145 # skip module docstests
146 146 __skip_doctest__ = True
147 147
148 148 try:
149 149 import jedi
150 150 jedi.settings.case_insensitive_completion = False
151 151 import jedi.api.helpers
152 152 import jedi.api.classes
153 153 JEDI_INSTALLED = True
154 154 except ImportError:
155 155 JEDI_INSTALLED = False
156 156 #-----------------------------------------------------------------------------
157 157 # Globals
158 158 #-----------------------------------------------------------------------------
159 159
160 160 # ranges where we have most of the valid unicode names. We could be more finer
161 161 # grained but is it worth it for performance While unicode have character in the
162 162 # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
163 163 # write this). With below range we cover them all, with a density of ~67%
164 164 # biggest next gap we consider only adds up about 1% density and there are 600
165 165 # gaps that would need hard coding.
166 166 _UNICODE_RANGES = [(32, 0x3134b), (0xe0001, 0xe01f0)]
167 167
168 168 # Public API
169 169 __all__ = ['Completer','IPCompleter']
170 170
171 171 if sys.platform == 'win32':
172 172 PROTECTABLES = ' '
173 173 else:
174 174 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
175 175
176 176 # Protect against returning an enormous number of completions which the frontend
177 177 # may have trouble processing.
178 178 MATCHES_LIMIT = 500
179 179
180 180
181 181 class ProvisionalCompleterWarning(FutureWarning):
182 182 """
183 183 Exception raise by an experimental feature in this module.
184 184
185 185 Wrap code in :any:`provisionalcompleter` context manager if you
186 186 are certain you want to use an unstable feature.
187 187 """
188 188 pass
189 189
190 190 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
191 191
192 192
193 193 @skip_doctest
194 194 @contextmanager
195 195 def provisionalcompleter(action='ignore'):
196 196 """
197 197 This context manager has to be used in any place where unstable completer
198 198 behavior and API may be called.
199 199
200 200 >>> with provisionalcompleter():
201 201 ... completer.do_experimental_things() # works
202 202
203 203 >>> completer.do_experimental_things() # raises.
204 204
205 205 .. note::
206 206
207 207 Unstable
208 208
209 209 By using this context manager you agree that the API in use may change
210 210 without warning, and that you won't complain if they do so.
211 211
212 212 You also understand that, if the API is not to your liking, you should report
213 213 a bug to explain your use case upstream.
214 214
215 215 We'll be happy to get your feedback, feature requests, and improvements on
216 216 any of the unstable APIs!
217 217 """
218 218 with warnings.catch_warnings():
219 219 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
220 220 yield
221 221
222 222
223 223 def has_open_quotes(s):
224 224 """Return whether a string has open quotes.
225 225
226 226 This simply counts whether the number of quote characters of either type in
227 227 the string is odd.
228 228
229 229 Returns
230 230 -------
231 231 If there is an open quote, the quote character is returned. Else, return
232 232 False.
233 233 """
234 234 # We check " first, then ', so complex cases with nested quotes will get
235 235 # the " to take precedence.
236 236 if s.count('"') % 2:
237 237 return '"'
238 238 elif s.count("'") % 2:
239 239 return "'"
240 240 else:
241 241 return False
242 242
243 243
244 244 def protect_filename(s, protectables=PROTECTABLES):
245 245 """Escape a string to protect certain characters."""
246 246 if set(s) & set(protectables):
247 247 if sys.platform == "win32":
248 248 return '"' + s + '"'
249 249 else:
250 250 return "".join(("\\" + c if c in protectables else c) for c in s)
251 251 else:
252 252 return s
253 253
254 254
255 255 def expand_user(path:str) -> Tuple[str, bool, str]:
256 256 """Expand ``~``-style usernames in strings.
257 257
258 258 This is similar to :func:`os.path.expanduser`, but it computes and returns
259 259 extra information that will be useful if the input was being used in
260 260 computing completions, and you wish to return the completions with the
261 261 original '~' instead of its expanded value.
262 262
263 263 Parameters
264 264 ----------
265 265 path : str
266 266 String to be expanded. If no ~ is present, the output is the same as the
267 267 input.
268 268
269 269 Returns
270 270 -------
271 271 newpath : str
272 272 Result of ~ expansion in the input path.
273 273 tilde_expand : bool
274 274 Whether any expansion was performed or not.
275 275 tilde_val : str
276 276 The value that ~ was replaced with.
277 277 """
278 278 # Default values
279 279 tilde_expand = False
280 280 tilde_val = ''
281 281 newpath = path
282 282
283 283 if path.startswith('~'):
284 284 tilde_expand = True
285 285 rest = len(path)-1
286 286 newpath = os.path.expanduser(path)
287 287 if rest:
288 288 tilde_val = newpath[:-rest]
289 289 else:
290 290 tilde_val = newpath
291 291
292 292 return newpath, tilde_expand, tilde_val
293 293
294 294
295 295 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
296 296 """Does the opposite of expand_user, with its outputs.
297 297 """
298 298 if tilde_expand:
299 299 return path.replace(tilde_val, '~')
300 300 else:
301 301 return path
302 302
303 303
304 304 def completions_sorting_key(word):
305 305 """key for sorting completions
306 306
307 307 This does several things:
308 308
309 309 - Demote any completions starting with underscores to the end
310 310 - Insert any %magic and %%cellmagic completions in the alphabetical order
311 311 by their name
312 312 """
313 313 prio1, prio2 = 0, 0
314 314
315 315 if word.startswith('__'):
316 316 prio1 = 2
317 317 elif word.startswith('_'):
318 318 prio1 = 1
319 319
320 320 if word.endswith('='):
321 321 prio1 = -1
322 322
323 323 if word.startswith('%%'):
324 324 # If there's another % in there, this is something else, so leave it alone
325 325 if not "%" in word[2:]:
326 326 word = word[2:]
327 327 prio2 = 2
328 328 elif word.startswith('%'):
329 329 if not "%" in word[1:]:
330 330 word = word[1:]
331 331 prio2 = 1
332 332
333 333 return prio1, word, prio2
334 334
335 335
336 336 class _FakeJediCompletion:
337 337 """
338 338 This is a workaround to communicate to the UI that Jedi has crashed and to
339 339 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
340 340
341 341 Added in IPython 6.0 so should likely be removed for 7.0
342 342
343 343 """
344 344
345 345 def __init__(self, name):
346 346
347 347 self.name = name
348 348 self.complete = name
349 349 self.type = 'crashed'
350 350 self.name_with_symbols = name
351 351 self.signature = ''
352 352 self._origin = 'fake'
353 353
354 354 def __repr__(self):
355 355 return '<Fake completion object jedi has crashed>'
356 356
357 357
358 358 class Completion:
359 359 """
360 360 Completion object used and return by IPython completers.
361 361
362 362 .. warning::
363 363
364 364 Unstable
365 365
366 366 This function is unstable, API may change without warning.
367 367 It will also raise unless use in proper context manager.
368 368
369 369 This act as a middle ground :any:`Completion` object between the
370 370 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
371 371 object. While Jedi need a lot of information about evaluator and how the
372 372 code should be ran/inspected, PromptToolkit (and other frontend) mostly
373 373 need user facing information.
374 374
375 375 - Which range should be replaced replaced by what.
376 376 - Some metadata (like completion type), or meta information to displayed to
377 377 the use user.
378 378
379 379 For debugging purpose we can also store the origin of the completion (``jedi``,
380 380 ``IPython.python_matches``, ``IPython.magics_matches``...).
381 381 """
382 382
383 383 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
384 384
385 385 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
386 386 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
387 387 "It may change without warnings. "
388 388 "Use in corresponding context manager.",
389 389 category=ProvisionalCompleterWarning, stacklevel=2)
390 390
391 391 self.start = start
392 392 self.end = end
393 393 self.text = text
394 394 self.type = type
395 395 self.signature = signature
396 396 self._origin = _origin
397 397
398 398 def __repr__(self):
399 399 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
400 400 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
401 401
402 402 def __eq__(self, other)->Bool:
403 403 """
404 404 Equality and hash do not hash the type (as some completer may not be
405 405 able to infer the type), but are use to (partially) de-duplicate
406 406 completion.
407 407
408 408 Completely de-duplicating completion is a bit tricker that just
409 409 comparing as it depends on surrounding text, which Completions are not
410 410 aware of.
411 411 """
412 412 return self.start == other.start and \
413 413 self.end == other.end and \
414 414 self.text == other.text
415 415
416 416 def __hash__(self):
417 417 return hash((self.start, self.end, self.text))
418 418
419 419
420 420 _IC = Iterable[Completion]
421 421
422 422
423 423 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
424 424 """
425 425 Deduplicate a set of completions.
426 426
427 427 .. warning::
428 428
429 429 Unstable
430 430
431 431 This function is unstable, API may change without warning.
432 432
433 433 Parameters
434 434 ----------
435 435 text : str
436 436 text that should be completed.
437 437 completions : Iterator[Completion]
438 438 iterator over the completions to deduplicate
439 439
440 440 Yields
441 441 ------
442 442 `Completions` objects
443 443 Completions coming from multiple sources, may be different but end up having
444 444 the same effect when applied to ``text``. If this is the case, this will
445 445 consider completions as equal and only emit the first encountered.
446 446 Not folded in `completions()` yet for debugging purpose, and to detect when
447 447 the IPython completer does return things that Jedi does not, but should be
448 448 at some point.
449 449 """
450 450 completions = list(completions)
451 451 if not completions:
452 452 return
453 453
454 454 new_start = min(c.start for c in completions)
455 455 new_end = max(c.end for c in completions)
456 456
457 457 seen = set()
458 458 for c in completions:
459 459 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
460 460 if new_text not in seen:
461 461 yield c
462 462 seen.add(new_text)
463 463
464 464
465 465 def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
466 466 """
467 467 Rectify a set of completions to all have the same ``start`` and ``end``
468 468
469 469 .. warning::
470 470
471 471 Unstable
472 472
473 473 This function is unstable, API may change without warning.
474 474 It will also raise unless use in proper context manager.
475 475
476 476 Parameters
477 477 ----------
478 478 text : str
479 479 text that should be completed.
480 480 completions : Iterator[Completion]
481 481 iterator over the completions to rectify
482 482 _debug : bool
483 483 Log failed completion
484 484
485 485 Notes
486 486 -----
487 487 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
488 488 the Jupyter Protocol requires them to behave like so. This will readjust
489 489 the completion to have the same ``start`` and ``end`` by padding both
490 490 extremities with surrounding text.
491 491
492 492 During stabilisation should support a ``_debug`` option to log which
493 493 completion are return by the IPython completer and not found in Jedi in
494 494 order to make upstream bug report.
495 495 """
496 496 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
497 497 "It may change without warnings. "
498 498 "Use in corresponding context manager.",
499 499 category=ProvisionalCompleterWarning, stacklevel=2)
500 500
501 501 completions = list(completions)
502 502 if not completions:
503 503 return
504 504 starts = (c.start for c in completions)
505 505 ends = (c.end for c in completions)
506 506
507 507 new_start = min(starts)
508 508 new_end = max(ends)
509 509
510 510 seen_jedi = set()
511 511 seen_python_matches = set()
512 512 for c in completions:
513 513 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
514 514 if c._origin == 'jedi':
515 515 seen_jedi.add(new_text)
516 516 elif c._origin == 'IPCompleter.python_matches':
517 517 seen_python_matches.add(new_text)
518 518 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
519 519 diff = seen_python_matches.difference(seen_jedi)
520 520 if diff and _debug:
521 521 print('IPython.python matches have extras:', diff)
522 522
523 523
524 524 if sys.platform == 'win32':
525 525 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
526 526 else:
527 527 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
528 528
529 529 GREEDY_DELIMS = ' =\r\n'
530 530
531 531
532 532 class CompletionSplitter(object):
533 533 """An object to split an input line in a manner similar to readline.
534 534
535 535 By having our own implementation, we can expose readline-like completion in
536 536 a uniform manner to all frontends. This object only needs to be given the
537 537 line of text to be split and the cursor position on said line, and it
538 538 returns the 'word' to be completed on at the cursor after splitting the
539 539 entire line.
540 540
541 541 What characters are used as splitting delimiters can be controlled by
542 542 setting the ``delims`` attribute (this is a property that internally
543 543 automatically builds the necessary regular expression)"""
544 544
545 545 # Private interface
546 546
547 547 # A string of delimiter characters. The default value makes sense for
548 548 # IPython's most typical usage patterns.
549 549 _delims = DELIMS
550 550
551 551 # The expression (a normal string) to be compiled into a regular expression
552 552 # for actual splitting. We store it as an attribute mostly for ease of
553 553 # debugging, since this type of code can be so tricky to debug.
554 554 _delim_expr = None
555 555
556 556 # The regular expression that does the actual splitting
557 557 _delim_re = None
558 558
559 559 def __init__(self, delims=None):
560 560 delims = CompletionSplitter._delims if delims is None else delims
561 561 self.delims = delims
562 562
563 563 @property
564 564 def delims(self):
565 565 """Return the string of delimiter characters."""
566 566 return self._delims
567 567
568 568 @delims.setter
569 569 def delims(self, delims):
570 570 """Set the delimiters for line splitting."""
571 571 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
572 572 self._delim_re = re.compile(expr)
573 573 self._delims = delims
574 574 self._delim_expr = expr
575 575
576 576 def split_line(self, line, cursor_pos=None):
577 577 """Split a line of text with a cursor at the given position.
578 578 """
579 579 l = line if cursor_pos is None else line[:cursor_pos]
580 580 return self._delim_re.split(l)[-1]
581 581
582 582
583 583
584 584 class Completer(Configurable):
585 585
586 586 greedy = Bool(False,
587 587 help="""Activate greedy completion
588 588 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
589 589
590 590 This will enable completion on elements of lists, results of function calls, etc.,
591 591 but can be unsafe because the code is actually evaluated on TAB.
592 592 """
593 593 ).tag(config=True)
594 594
595 595 use_jedi = Bool(default_value=JEDI_INSTALLED,
596 596 help="Experimental: Use Jedi to generate autocompletions. "
597 597 "Default to True if jedi is installed.").tag(config=True)
598 598
599 599 jedi_compute_type_timeout = Int(default_value=400,
600 600 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
601 601 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
602 602 performance by preventing jedi to build its cache.
603 603 """).tag(config=True)
604 604
605 605 debug = Bool(default_value=False,
606 606 help='Enable debug for the Completer. Mostly print extra '
607 607 'information for experimental jedi integration.')\
608 608 .tag(config=True)
609 609
610 610 backslash_combining_completions = Bool(True,
611 611 help="Enable unicode completions, e.g. \\alpha<tab> . "
612 612 "Includes completion of latex commands, unicode names, and expanding "
613 613 "unicode characters back to latex commands.").tag(config=True)
614 614
615 615 def __init__(self, namespace=None, global_namespace=None, **kwargs):
616 616 """Create a new completer for the command line.
617 617
618 618 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
619 619
620 620 If unspecified, the default namespace where completions are performed
621 621 is __main__ (technically, __main__.__dict__). Namespaces should be
622 622 given as dictionaries.
623 623
624 624 An optional second namespace can be given. This allows the completer
625 625 to handle cases where both the local and global scopes need to be
626 626 distinguished.
627 627 """
628 628
629 629 # Don't bind to namespace quite yet, but flag whether the user wants a
630 630 # specific namespace or to use __main__.__dict__. This will allow us
631 631 # to bind to __main__.__dict__ at completion time, not now.
632 632 if namespace is None:
633 633 self.use_main_ns = True
634 634 else:
635 635 self.use_main_ns = False
636 636 self.namespace = namespace
637 637
638 638 # The global namespace, if given, can be bound directly
639 639 if global_namespace is None:
640 640 self.global_namespace = {}
641 641 else:
642 642 self.global_namespace = global_namespace
643 643
644 644 self.custom_matchers = []
645 645
646 646 super(Completer, self).__init__(**kwargs)
647 647
648 648 def complete(self, text, state):
649 649 """Return the next possible completion for 'text'.
650 650
651 651 This is called successively with state == 0, 1, 2, ... until it
652 652 returns None. The completion should begin with 'text'.
653 653
654 654 """
655 655 if self.use_main_ns:
656 656 self.namespace = __main__.__dict__
657 657
658 658 if state == 0:
659 659 if "." in text:
660 660 self.matches = self.attr_matches(text)
661 661 else:
662 662 self.matches = self.global_matches(text)
663 663 try:
664 664 return self.matches[state]
665 665 except IndexError:
666 666 return None
667 667
668 668 def global_matches(self, text):
669 669 """Compute matches when text is a simple name.
670 670
671 671 Return a list of all keywords, built-in functions and names currently
672 672 defined in self.namespace or self.global_namespace that match.
673 673
674 674 """
675 675 matches = []
676 676 match_append = matches.append
677 677 n = len(text)
678 678 for lst in [keyword.kwlist,
679 679 builtin_mod.__dict__.keys(),
680 680 self.namespace.keys(),
681 681 self.global_namespace.keys()]:
682 682 for word in lst:
683 683 if word[:n] == text and word != "__builtins__":
684 684 match_append(word)
685 685
686 686 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
687 687 for lst in [self.namespace.keys(),
688 688 self.global_namespace.keys()]:
689 689 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
690 690 for word in lst if snake_case_re.match(word)}
691 691 for word in shortened.keys():
692 692 if word[:n] == text and word != "__builtins__":
693 693 match_append(shortened[word])
694 694 return matches
695 695
696 696 def attr_matches(self, text):
697 697 """Compute matches when text contains a dot.
698 698
699 699 Assuming the text is of the form NAME.NAME....[NAME], and is
700 700 evaluatable in self.namespace or self.global_namespace, it will be
701 701 evaluated and its attributes (as revealed by dir()) are used as
702 702 possible completions. (For class instances, class members are
703 703 also considered.)
704 704
705 705 WARNING: this can still invoke arbitrary C code, if an object
706 706 with a __getattr__ hook is evaluated.
707 707
708 708 """
709 709
710 710 # Another option, seems to work great. Catches things like ''.<tab>
711 711 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
712 712
713 713 if m:
714 714 expr, attr = m.group(1, 3)
715 715 elif self.greedy:
716 716 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
717 717 if not m2:
718 718 return []
719 719 expr, attr = m2.group(1,2)
720 720 else:
721 721 return []
722 722
723 723 try:
724 724 obj = eval(expr, self.namespace)
725 725 except:
726 726 try:
727 727 obj = eval(expr, self.global_namespace)
728 728 except:
729 729 return []
730 730
731 731 if self.limit_to__all__ and hasattr(obj, '__all__'):
732 732 words = get__all__entries(obj)
733 733 else:
734 734 words = dir2(obj)
735 735
736 736 try:
737 737 words = generics.complete_object(obj, words)
738 738 except TryNext:
739 739 pass
740 740 except AssertionError:
741 741 raise
742 742 except Exception:
743 743 # Silence errors from completion function
744 744 #raise # dbg
745 745 pass
746 746 # Build match list to return
747 747 n = len(attr)
748 748 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
749 749
750 750
751 751 def get__all__entries(obj):
752 752 """returns the strings in the __all__ attribute"""
753 753 try:
754 754 words = getattr(obj, '__all__')
755 755 except:
756 756 return []
757 757
758 758 return [w for w in words if isinstance(w, str)]
759 759
760 760
761 761 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
762 762 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
763 763 """Used by dict_key_matches, matching the prefix to a list of keys
764 764
765 765 Parameters
766 766 ----------
767 767 keys
768 768 list of keys in dictionary currently being completed.
769 769 prefix
770 770 Part of the text already typed by the user. E.g. `mydict[b'fo`
771 771 delims
772 772 String of delimiters to consider when finding the current key.
773 773 extra_prefix : optional
774 774 Part of the text already typed in multi-key index cases. E.g. for
775 775 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
776 776
777 777 Returns
778 778 -------
779 779 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
780 780 ``quote`` being the quote that need to be used to close current string.
781 781 ``token_start`` the position where the replacement should start occurring,
782 782 ``matches`` a list of replacement/completion
783 783
784 784 """
785 785 prefix_tuple = extra_prefix if extra_prefix else ()
786 786 Nprefix = len(prefix_tuple)
787 787 def filter_prefix_tuple(key):
788 788 # Reject too short keys
789 789 if len(key) <= Nprefix:
790 790 return False
791 791 # Reject keys with non str/bytes in it
792 792 for k in key:
793 793 if not isinstance(k, (str, bytes)):
794 794 return False
795 795 # Reject keys that do not match the prefix
796 796 for k, pt in zip(key, prefix_tuple):
797 797 if k != pt:
798 798 return False
799 799 # All checks passed!
800 800 return True
801 801
802 802 filtered_keys:List[Union[str,bytes]] = []
803 803 def _add_to_filtered_keys(key):
804 804 if isinstance(key, (str, bytes)):
805 805 filtered_keys.append(key)
806 806
807 807 for k in keys:
808 808 if isinstance(k, tuple):
809 809 if filter_prefix_tuple(k):
810 810 _add_to_filtered_keys(k[Nprefix])
811 811 else:
812 812 _add_to_filtered_keys(k)
813 813
814 814 if not prefix:
815 815 return '', 0, [repr(k) for k in filtered_keys]
816 816 quote_match = re.search('["\']', prefix)
817 817 assert quote_match is not None # silence mypy
818 818 quote = quote_match.group()
819 819 try:
820 820 prefix_str = eval(prefix + quote, {})
821 821 except Exception:
822 822 return '', 0, []
823 823
824 824 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
825 825 token_match = re.search(pattern, prefix, re.UNICODE)
826 826 assert token_match is not None # silence mypy
827 827 token_start = token_match.start()
828 828 token_prefix = token_match.group()
829 829
830 830 matched:List[str] = []
831 831 for key in filtered_keys:
832 832 try:
833 833 if not key.startswith(prefix_str):
834 834 continue
835 835 except (AttributeError, TypeError, UnicodeError):
836 836 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
837 837 continue
838 838
839 839 # reformat remainder of key to begin with prefix
840 840 rem = key[len(prefix_str):]
841 841 # force repr wrapped in '
842 842 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
843 843 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
844 844 if quote == '"':
845 845 # The entered prefix is quoted with ",
846 846 # but the match is quoted with '.
847 847 # A contained " hence needs escaping for comparison:
848 848 rem_repr = rem_repr.replace('"', '\\"')
849 849
850 850 # then reinsert prefix from start of token
851 851 matched.append('%s%s' % (token_prefix, rem_repr))
852 852 return quote, token_start, matched
853 853
854 854
855 855 def cursor_to_position(text:str, line:int, column:int)->int:
856 856 """
857 857 Convert the (line,column) position of the cursor in text to an offset in a
858 858 string.
859 859
860 860 Parameters
861 861 ----------
862 862 text : str
863 863 The text in which to calculate the cursor offset
864 864 line : int
865 865 Line of the cursor; 0-indexed
866 866 column : int
867 867 Column of the cursor 0-indexed
868 868
869 869 Returns
870 870 -------
871 871 Position of the cursor in ``text``, 0-indexed.
872 872
873 873 See Also
874 874 --------
875 875 position_to_cursor : reciprocal of this function
876 876
877 877 """
878 878 lines = text.split('\n')
879 879 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
880 880
881 881 return sum(len(l) + 1 for l in lines[:line]) + column
882 882
883 883 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
884 884 """
885 885 Convert the position of the cursor in text (0 indexed) to a line
886 886 number(0-indexed) and a column number (0-indexed) pair
887 887
888 888 Position should be a valid position in ``text``.
889 889
890 890 Parameters
891 891 ----------
892 892 text : str
893 893 The text in which to calculate the cursor offset
894 894 offset : int
895 895 Position of the cursor in ``text``, 0-indexed.
896 896
897 897 Returns
898 898 -------
899 899 (line, column) : (int, int)
900 900 Line of the cursor; 0-indexed, column of the cursor 0-indexed
901 901
902 902 See Also
903 903 --------
904 904 cursor_to_position : reciprocal of this function
905 905
906 906 """
907 907
908 908 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
909 909
910 910 before = text[:offset]
911 911 blines = before.split('\n') # ! splitnes trim trailing \n
912 912 line = before.count('\n')
913 913 col = len(blines[-1])
914 914 return line, col
915 915
916 916
917 917 def _safe_isinstance(obj, module, class_name):
918 918 """Checks if obj is an instance of module.class_name if loaded
919 919 """
920 920 return (module in sys.modules and
921 921 isinstance(obj, getattr(import_module(module), class_name)))
922 922
923 923 def back_unicode_name_matches(text:str) -> Tuple[str, Sequence[str]]:
924 924 """Match Unicode characters back to Unicode name
925 925
926 926 This does ``β˜ƒ`` -> ``\\snowman``
927 927
928 928 Note that snowman is not a valid python3 combining character but will be expanded.
929 929 Though it will not recombine back to the snowman character by the completion machinery.
930 930
931 931 This will not either back-complete standard sequences like \\n, \\b ...
932 932
933 933 Returns
934 934 =======
935 935
936 936 Return a tuple with two elements:
937 937
938 938 - The Unicode character that was matched (preceded with a backslash), or
939 939 empty string,
940 940 - a sequence (of 1), name for the match Unicode character, preceded by
941 941 backslash, or empty if no match.
942 942
943 943 """
944 944 if len(text)<2:
945 945 return '', ()
946 946 maybe_slash = text[-2]
947 947 if maybe_slash != '\\':
948 948 return '', ()
949 949
950 950 char = text[-1]
951 951 # no expand on quote for completion in strings.
952 952 # nor backcomplete standard ascii keys
953 953 if char in string.ascii_letters or char in ('"',"'"):
954 954 return '', ()
955 955 try :
956 956 unic = unicodedata.name(char)
957 957 return '\\'+char,('\\'+unic,)
958 958 except KeyError:
959 959 pass
960 960 return '', ()
961 961
962 962 def back_latex_name_matches(text:str) -> Tuple[str, Sequence[str]] :
963 963 """Match latex characters back to unicode name
964 964
965 965 This does ``\\β„΅`` -> ``\\aleph``
966 966
967 967 """
968 968 if len(text)<2:
969 969 return '', ()
970 970 maybe_slash = text[-2]
971 971 if maybe_slash != '\\':
972 972 return '', ()
973 973
974 974
975 975 char = text[-1]
976 976 # no expand on quote for completion in strings.
977 977 # nor backcomplete standard ascii keys
978 978 if char in string.ascii_letters or char in ('"',"'"):
979 979 return '', ()
980 980 try :
981 981 latex = reverse_latex_symbol[char]
982 982 # '\\' replace the \ as well
983 983 return '\\'+char,[latex]
984 984 except KeyError:
985 985 pass
986 986 return '', ()
987 987
988 988
989 989 def _formatparamchildren(parameter) -> str:
990 990 """
991 991 Get parameter name and value from Jedi Private API
992 992
993 993 Jedi does not expose a simple way to get `param=value` from its API.
994 994
995 995 Parameters
996 996 ----------
997 997 parameter
998 998 Jedi's function `Param`
999 999
1000 1000 Returns
1001 1001 -------
1002 1002 A string like 'a', 'b=1', '*args', '**kwargs'
1003 1003
1004 1004 """
1005 1005 description = parameter.description
1006 1006 if not description.startswith('param '):
1007 1007 raise ValueError('Jedi function parameter description have change format.'
1008 1008 'Expected "param ...", found %r".' % description)
1009 1009 return description[6:]
1010 1010
1011 1011 def _make_signature(completion)-> str:
1012 1012 """
1013 1013 Make the signature from a jedi completion
1014 1014
1015 1015 Parameters
1016 1016 ----------
1017 1017 completion : jedi.Completion
1018 1018 object does not complete a function type
1019 1019
1020 1020 Returns
1021 1021 -------
1022 1022 a string consisting of the function signature, with the parenthesis but
1023 1023 without the function name. example:
1024 1024 `(a, *args, b=1, **kwargs)`
1025 1025
1026 1026 """
1027 1027
1028 1028 # it looks like this might work on jedi 0.17
1029 1029 if hasattr(completion, 'get_signatures'):
1030 1030 signatures = completion.get_signatures()
1031 1031 if not signatures:
1032 1032 return '(?)'
1033 1033
1034 1034 c0 = completion.get_signatures()[0]
1035 1035 return '('+c0.to_string().split('(', maxsplit=1)[1]
1036 1036
1037 1037 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1038 1038 for p in signature.defined_names()) if f])
1039 1039
1040 1040
1041 1041 class _CompleteResult(NamedTuple):
1042 1042 matched_text : str
1043 1043 matches: Sequence[str]
1044 1044 matches_origin: Sequence[str]
1045 1045 jedi_matches: Any
1046 1046
1047 1047
1048 1048 class IPCompleter(Completer):
1049 1049 """Extension of the completer class with IPython-specific features"""
1050 1050
1051 1051 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1052 1052
1053 1053 @observe('greedy')
1054 1054 def _greedy_changed(self, change):
1055 1055 """update the splitter and readline delims when greedy is changed"""
1056 1056 if change['new']:
1057 1057 self.splitter.delims = GREEDY_DELIMS
1058 1058 else:
1059 1059 self.splitter.delims = DELIMS
1060 1060
1061 1061 dict_keys_only = Bool(False,
1062 1062 help="""Whether to show dict key matches only""")
1063 1063
1064 1064 merge_completions = Bool(True,
1065 1065 help="""Whether to merge completion results into a single list
1066 1066
1067 1067 If False, only the completion results from the first non-empty
1068 1068 completer will be returned.
1069 1069 """
1070 1070 ).tag(config=True)
1071 1071 omit__names = Enum((0,1,2), default_value=2,
1072 1072 help="""Instruct the completer to omit private method names
1073 1073
1074 1074 Specifically, when completing on ``object.<tab>``.
1075 1075
1076 1076 When 2 [default]: all names that start with '_' will be excluded.
1077 1077
1078 1078 When 1: all 'magic' names (``__foo__``) will be excluded.
1079 1079
1080 1080 When 0: nothing will be excluded.
1081 1081 """
1082 1082 ).tag(config=True)
1083 1083 limit_to__all__ = Bool(False,
1084 1084 help="""
1085 1085 DEPRECATED as of version 5.0.
1086 1086
1087 1087 Instruct the completer to use __all__ for the completion
1088 1088
1089 1089 Specifically, when completing on ``object.<tab>``.
1090 1090
1091 1091 When True: only those names in obj.__all__ will be included.
1092 1092
1093 1093 When False [default]: the __all__ attribute is ignored
1094 1094 """,
1095 1095 ).tag(config=True)
1096 1096
1097 1097 profile_completions = Bool(
1098 1098 default_value=False,
1099 1099 help="If True, emit profiling data for completion subsystem using cProfile."
1100 1100 ).tag(config=True)
1101 1101
1102 1102 profiler_output_dir = Unicode(
1103 1103 default_value=".completion_profiles",
1104 1104 help="Template for path at which to output profile data for completions."
1105 1105 ).tag(config=True)
1106 1106
1107 1107 @observe('limit_to__all__')
1108 1108 def _limit_to_all_changed(self, change):
1109 1109 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1110 1110 'value has been deprecated since IPython 5.0, will be made to have '
1111 1111 'no effects and then removed in future version of IPython.',
1112 1112 UserWarning)
1113 1113
1114 1114 def __init__(
1115 1115 self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
1116 1116 ):
1117 1117 """IPCompleter() -> completer
1118 1118
1119 1119 Return a completer object.
1120 1120
1121 1121 Parameters
1122 1122 ----------
1123 1123 shell
1124 1124 a pointer to the ipython shell itself. This is needed
1125 1125 because this completer knows about magic functions, and those can
1126 1126 only be accessed via the ipython instance.
1127 1127 namespace : dict, optional
1128 1128 an optional dict where completions are performed.
1129 1129 global_namespace : dict, optional
1130 1130 secondary optional dict for completions, to
1131 1131 handle cases (such as IPython embedded inside functions) where
1132 1132 both Python scopes are visible.
1133 1133 config : Config
1134 1134 traitlet's config object
1135 1135 **kwargs
1136 1136 passed to super class unmodified.
1137 1137 """
1138 1138
1139 1139 self.magic_escape = ESC_MAGIC
1140 1140 self.splitter = CompletionSplitter()
1141 1141
1142 1142 # _greedy_changed() depends on splitter and readline being defined:
1143 1143 super().__init__(
1144 self,
1145 1144 namespace=namespace,
1146 1145 global_namespace=global_namespace,
1147 1146 config=config,
1148 1147 **kwargs
1149 1148 )
1150 1149
1151 1150 # List where completion matches will be stored
1152 1151 self.matches = []
1153 1152 self.shell = shell
1154 1153 # Regexp to split filenames with spaces in them
1155 1154 self.space_name_re = re.compile(r'([^\\] )')
1156 1155 # Hold a local ref. to glob.glob for speed
1157 1156 self.glob = glob.glob
1158 1157
1159 1158 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1160 1159 # buffers, to avoid completion problems.
1161 1160 term = os.environ.get('TERM','xterm')
1162 1161 self.dumb_terminal = term in ['dumb','emacs']
1163 1162
1164 1163 # Special handling of backslashes needed in win32 platforms
1165 1164 if sys.platform == "win32":
1166 1165 self.clean_glob = self._clean_glob_win32
1167 1166 else:
1168 1167 self.clean_glob = self._clean_glob
1169 1168
1170 1169 #regexp to parse docstring for function signature
1171 1170 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1172 1171 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1173 1172 #use this if positional argument name is also needed
1174 1173 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1175 1174
1176 1175 self.magic_arg_matchers = [
1177 1176 self.magic_config_matches,
1178 1177 self.magic_color_matches,
1179 1178 ]
1180 1179
1181 1180 # This is set externally by InteractiveShell
1182 1181 self.custom_completers = None
1183 1182
1184 1183 # This is a list of names of unicode characters that can be completed
1185 1184 # into their corresponding unicode value. The list is large, so we
1186 1185 # laziliy initialize it on first use. Consuming code should access this
1187 1186 # attribute through the `@unicode_names` property.
1188 1187 self._unicode_names = None
1189 1188
1190 1189 @property
1191 1190 def matchers(self) -> List[Any]:
1192 1191 """All active matcher routines for completion"""
1193 1192 if self.dict_keys_only:
1194 1193 return [self.dict_key_matches]
1195 1194
1196 1195 if self.use_jedi:
1197 1196 return [
1198 1197 *self.custom_matchers,
1199 1198 self.dict_key_matches,
1200 1199 self.file_matches,
1201 1200 self.magic_matches,
1202 1201 ]
1203 1202 else:
1204 1203 return [
1205 1204 *self.custom_matchers,
1206 1205 self.dict_key_matches,
1207 1206 self.python_matches,
1208 1207 self.file_matches,
1209 1208 self.magic_matches,
1210 1209 self.python_func_kw_matches,
1211 1210 ]
1212 1211
1213 1212 def all_completions(self, text:str) -> List[str]:
1214 1213 """
1215 1214 Wrapper around the completion methods for the benefit of emacs.
1216 1215 """
1217 1216 prefix = text.rpartition('.')[0]
1218 1217 with provisionalcompleter():
1219 1218 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1220 1219 for c in self.completions(text, len(text))]
1221 1220
1222 1221 return self.complete(text)[1]
1223 1222
1224 1223 def _clean_glob(self, text:str):
1225 1224 return self.glob("%s*" % text)
1226 1225
1227 1226 def _clean_glob_win32(self, text:str):
1228 1227 return [f.replace("\\","/")
1229 1228 for f in self.glob("%s*" % text)]
1230 1229
1231 1230 def file_matches(self, text:str)->List[str]:
1232 1231 """Match filenames, expanding ~USER type strings.
1233 1232
1234 1233 Most of the seemingly convoluted logic in this completer is an
1235 1234 attempt to handle filenames with spaces in them. And yet it's not
1236 1235 quite perfect, because Python's readline doesn't expose all of the
1237 1236 GNU readline details needed for this to be done correctly.
1238 1237
1239 1238 For a filename with a space in it, the printed completions will be
1240 1239 only the parts after what's already been typed (instead of the
1241 1240 full completions, as is normally done). I don't think with the
1242 1241 current (as of Python 2.3) Python readline it's possible to do
1243 1242 better."""
1244 1243
1245 1244 # chars that require escaping with backslash - i.e. chars
1246 1245 # that readline treats incorrectly as delimiters, but we
1247 1246 # don't want to treat as delimiters in filename matching
1248 1247 # when escaped with backslash
1249 1248 if text.startswith('!'):
1250 1249 text = text[1:]
1251 1250 text_prefix = u'!'
1252 1251 else:
1253 1252 text_prefix = u''
1254 1253
1255 1254 text_until_cursor = self.text_until_cursor
1256 1255 # track strings with open quotes
1257 1256 open_quotes = has_open_quotes(text_until_cursor)
1258 1257
1259 1258 if '(' in text_until_cursor or '[' in text_until_cursor:
1260 1259 lsplit = text
1261 1260 else:
1262 1261 try:
1263 1262 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1264 1263 lsplit = arg_split(text_until_cursor)[-1]
1265 1264 except ValueError:
1266 1265 # typically an unmatched ", or backslash without escaped char.
1267 1266 if open_quotes:
1268 1267 lsplit = text_until_cursor.split(open_quotes)[-1]
1269 1268 else:
1270 1269 return []
1271 1270 except IndexError:
1272 1271 # tab pressed on empty line
1273 1272 lsplit = ""
1274 1273
1275 1274 if not open_quotes and lsplit != protect_filename(lsplit):
1276 1275 # if protectables are found, do matching on the whole escaped name
1277 1276 has_protectables = True
1278 1277 text0,text = text,lsplit
1279 1278 else:
1280 1279 has_protectables = False
1281 1280 text = os.path.expanduser(text)
1282 1281
1283 1282 if text == "":
1284 1283 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1285 1284
1286 1285 # Compute the matches from the filesystem
1287 1286 if sys.platform == 'win32':
1288 1287 m0 = self.clean_glob(text)
1289 1288 else:
1290 1289 m0 = self.clean_glob(text.replace('\\', ''))
1291 1290
1292 1291 if has_protectables:
1293 1292 # If we had protectables, we need to revert our changes to the
1294 1293 # beginning of filename so that we don't double-write the part
1295 1294 # of the filename we have so far
1296 1295 len_lsplit = len(lsplit)
1297 1296 matches = [text_prefix + text0 +
1298 1297 protect_filename(f[len_lsplit:]) for f in m0]
1299 1298 else:
1300 1299 if open_quotes:
1301 1300 # if we have a string with an open quote, we don't need to
1302 1301 # protect the names beyond the quote (and we _shouldn't_, as
1303 1302 # it would cause bugs when the filesystem call is made).
1304 1303 matches = m0 if sys.platform == "win32" else\
1305 1304 [protect_filename(f, open_quotes) for f in m0]
1306 1305 else:
1307 1306 matches = [text_prefix +
1308 1307 protect_filename(f) for f in m0]
1309 1308
1310 1309 # Mark directories in input list by appending '/' to their names.
1311 1310 return [x+'/' if os.path.isdir(x) else x for x in matches]
1312 1311
1313 1312 def magic_matches(self, text:str):
1314 1313 """Match magics"""
1315 1314 # Get all shell magics now rather than statically, so magics loaded at
1316 1315 # runtime show up too.
1317 1316 lsm = self.shell.magics_manager.lsmagic()
1318 1317 line_magics = lsm['line']
1319 1318 cell_magics = lsm['cell']
1320 1319 pre = self.magic_escape
1321 1320 pre2 = pre+pre
1322 1321
1323 1322 explicit_magic = text.startswith(pre)
1324 1323
1325 1324 # Completion logic:
1326 1325 # - user gives %%: only do cell magics
1327 1326 # - user gives %: do both line and cell magics
1328 1327 # - no prefix: do both
1329 1328 # In other words, line magics are skipped if the user gives %% explicitly
1330 1329 #
1331 1330 # We also exclude magics that match any currently visible names:
1332 1331 # https://github.com/ipython/ipython/issues/4877, unless the user has
1333 1332 # typed a %:
1334 1333 # https://github.com/ipython/ipython/issues/10754
1335 1334 bare_text = text.lstrip(pre)
1336 1335 global_matches = self.global_matches(bare_text)
1337 1336 if not explicit_magic:
1338 1337 def matches(magic):
1339 1338 """
1340 1339 Filter magics, in particular remove magics that match
1341 1340 a name present in global namespace.
1342 1341 """
1343 1342 return ( magic.startswith(bare_text) and
1344 1343 magic not in global_matches )
1345 1344 else:
1346 1345 def matches(magic):
1347 1346 return magic.startswith(bare_text)
1348 1347
1349 1348 comp = [ pre2+m for m in cell_magics if matches(m)]
1350 1349 if not text.startswith(pre2):
1351 1350 comp += [ pre+m for m in line_magics if matches(m)]
1352 1351
1353 1352 return comp
1354 1353
1355 1354 def magic_config_matches(self, text:str) -> List[str]:
1356 1355 """ Match class names and attributes for %config magic """
1357 1356 texts = text.strip().split()
1358 1357
1359 1358 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1360 1359 # get all configuration classes
1361 1360 classes = sorted(set([ c for c in self.shell.configurables
1362 1361 if c.__class__.class_traits(config=True)
1363 1362 ]), key=lambda x: x.__class__.__name__)
1364 1363 classnames = [ c.__class__.__name__ for c in classes ]
1365 1364
1366 1365 # return all classnames if config or %config is given
1367 1366 if len(texts) == 1:
1368 1367 return classnames
1369 1368
1370 1369 # match classname
1371 1370 classname_texts = texts[1].split('.')
1372 1371 classname = classname_texts[0]
1373 1372 classname_matches = [ c for c in classnames
1374 1373 if c.startswith(classname) ]
1375 1374
1376 1375 # return matched classes or the matched class with attributes
1377 1376 if texts[1].find('.') < 0:
1378 1377 return classname_matches
1379 1378 elif len(classname_matches) == 1 and \
1380 1379 classname_matches[0] == classname:
1381 1380 cls = classes[classnames.index(classname)].__class__
1382 1381 help = cls.class_get_help()
1383 1382 # strip leading '--' from cl-args:
1384 1383 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1385 1384 return [ attr.split('=')[0]
1386 1385 for attr in help.strip().splitlines()
1387 1386 if attr.startswith(texts[1]) ]
1388 1387 return []
1389 1388
1390 1389 def magic_color_matches(self, text:str) -> List[str] :
1391 1390 """ Match color schemes for %colors magic"""
1392 1391 texts = text.split()
1393 1392 if text.endswith(' '):
1394 1393 # .split() strips off the trailing whitespace. Add '' back
1395 1394 # so that: '%colors ' -> ['%colors', '']
1396 1395 texts.append('')
1397 1396
1398 1397 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1399 1398 prefix = texts[1]
1400 1399 return [ color for color in InspectColors.keys()
1401 1400 if color.startswith(prefix) ]
1402 1401 return []
1403 1402
1404 1403 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str) -> Iterable[Any]:
1405 1404 """
1406 1405 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1407 1406 cursor position.
1408 1407
1409 1408 Parameters
1410 1409 ----------
1411 1410 cursor_column : int
1412 1411 column position of the cursor in ``text``, 0-indexed.
1413 1412 cursor_line : int
1414 1413 line position of the cursor in ``text``, 0-indexed
1415 1414 text : str
1416 1415 text to complete
1417 1416
1418 1417 Notes
1419 1418 -----
1420 1419 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1421 1420 object containing a string with the Jedi debug information attached.
1422 1421 """
1423 1422 namespaces = [self.namespace]
1424 1423 if self.global_namespace is not None:
1425 1424 namespaces.append(self.global_namespace)
1426 1425
1427 1426 completion_filter = lambda x:x
1428 1427 offset = cursor_to_position(text, cursor_line, cursor_column)
1429 1428 # filter output if we are completing for object members
1430 1429 if offset:
1431 1430 pre = text[offset-1]
1432 1431 if pre == '.':
1433 1432 if self.omit__names == 2:
1434 1433 completion_filter = lambda c:not c.name.startswith('_')
1435 1434 elif self.omit__names == 1:
1436 1435 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1437 1436 elif self.omit__names == 0:
1438 1437 completion_filter = lambda x:x
1439 1438 else:
1440 1439 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1441 1440
1442 1441 interpreter = jedi.Interpreter(text[:offset], namespaces)
1443 1442 try_jedi = True
1444 1443
1445 1444 try:
1446 1445 # find the first token in the current tree -- if it is a ' or " then we are in a string
1447 1446 completing_string = False
1448 1447 try:
1449 1448 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1450 1449 except StopIteration:
1451 1450 pass
1452 1451 else:
1453 1452 # note the value may be ', ", or it may also be ''' or """, or
1454 1453 # in some cases, """what/you/typed..., but all of these are
1455 1454 # strings.
1456 1455 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1457 1456
1458 1457 # if we are in a string jedi is likely not the right candidate for
1459 1458 # now. Skip it.
1460 1459 try_jedi = not completing_string
1461 1460 except Exception as e:
1462 1461 # many of things can go wrong, we are using private API just don't crash.
1463 1462 if self.debug:
1464 1463 print("Error detecting if completing a non-finished string :", e, '|')
1465 1464
1466 1465 if not try_jedi:
1467 1466 return []
1468 1467 try:
1469 1468 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1470 1469 except Exception as e:
1471 1470 if self.debug:
1472 1471 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1473 1472 else:
1474 1473 return []
1475 1474
1476 1475 def python_matches(self, text:str)->List[str]:
1477 1476 """Match attributes or global python names"""
1478 1477 if "." in text:
1479 1478 try:
1480 1479 matches = self.attr_matches(text)
1481 1480 if text.endswith('.') and self.omit__names:
1482 1481 if self.omit__names == 1:
1483 1482 # true if txt is _not_ a __ name, false otherwise:
1484 1483 no__name = (lambda txt:
1485 1484 re.match(r'.*\.__.*?__',txt) is None)
1486 1485 else:
1487 1486 # true if txt is _not_ a _ name, false otherwise:
1488 1487 no__name = (lambda txt:
1489 1488 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1490 1489 matches = filter(no__name, matches)
1491 1490 except NameError:
1492 1491 # catches <undefined attributes>.<tab>
1493 1492 matches = []
1494 1493 else:
1495 1494 matches = self.global_matches(text)
1496 1495 return matches
1497 1496
1498 1497 def _default_arguments_from_docstring(self, doc):
1499 1498 """Parse the first line of docstring for call signature.
1500 1499
1501 1500 Docstring should be of the form 'min(iterable[, key=func])\n'.
1502 1501 It can also parse cython docstring of the form
1503 1502 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1504 1503 """
1505 1504 if doc is None:
1506 1505 return []
1507 1506
1508 1507 #care only the firstline
1509 1508 line = doc.lstrip().splitlines()[0]
1510 1509
1511 1510 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1512 1511 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1513 1512 sig = self.docstring_sig_re.search(line)
1514 1513 if sig is None:
1515 1514 return []
1516 1515 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1517 1516 sig = sig.groups()[0].split(',')
1518 1517 ret = []
1519 1518 for s in sig:
1520 1519 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1521 1520 ret += self.docstring_kwd_re.findall(s)
1522 1521 return ret
1523 1522
1524 1523 def _default_arguments(self, obj):
1525 1524 """Return the list of default arguments of obj if it is callable,
1526 1525 or empty list otherwise."""
1527 1526 call_obj = obj
1528 1527 ret = []
1529 1528 if inspect.isbuiltin(obj):
1530 1529 pass
1531 1530 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1532 1531 if inspect.isclass(obj):
1533 1532 #for cython embedsignature=True the constructor docstring
1534 1533 #belongs to the object itself not __init__
1535 1534 ret += self._default_arguments_from_docstring(
1536 1535 getattr(obj, '__doc__', ''))
1537 1536 # for classes, check for __init__,__new__
1538 1537 call_obj = (getattr(obj, '__init__', None) or
1539 1538 getattr(obj, '__new__', None))
1540 1539 # for all others, check if they are __call__able
1541 1540 elif hasattr(obj, '__call__'):
1542 1541 call_obj = obj.__call__
1543 1542 ret += self._default_arguments_from_docstring(
1544 1543 getattr(call_obj, '__doc__', ''))
1545 1544
1546 1545 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1547 1546 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1548 1547
1549 1548 try:
1550 1549 sig = inspect.signature(obj)
1551 1550 ret.extend(k for k, v in sig.parameters.items() if
1552 1551 v.kind in _keeps)
1553 1552 except ValueError:
1554 1553 pass
1555 1554
1556 1555 return list(set(ret))
1557 1556
1558 1557 def python_func_kw_matches(self, text):
1559 1558 """Match named parameters (kwargs) of the last open function"""
1560 1559
1561 1560 if "." in text: # a parameter cannot be dotted
1562 1561 return []
1563 1562 try: regexp = self.__funcParamsRegex
1564 1563 except AttributeError:
1565 1564 regexp = self.__funcParamsRegex = re.compile(r'''
1566 1565 '.*?(?<!\\)' | # single quoted strings or
1567 1566 ".*?(?<!\\)" | # double quoted strings or
1568 1567 \w+ | # identifier
1569 1568 \S # other characters
1570 1569 ''', re.VERBOSE | re.DOTALL)
1571 1570 # 1. find the nearest identifier that comes before an unclosed
1572 1571 # parenthesis before the cursor
1573 1572 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1574 1573 tokens = regexp.findall(self.text_until_cursor)
1575 1574 iterTokens = reversed(tokens); openPar = 0
1576 1575
1577 1576 for token in iterTokens:
1578 1577 if token == ')':
1579 1578 openPar -= 1
1580 1579 elif token == '(':
1581 1580 openPar += 1
1582 1581 if openPar > 0:
1583 1582 # found the last unclosed parenthesis
1584 1583 break
1585 1584 else:
1586 1585 return []
1587 1586 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1588 1587 ids = []
1589 1588 isId = re.compile(r'\w+$').match
1590 1589
1591 1590 while True:
1592 1591 try:
1593 1592 ids.append(next(iterTokens))
1594 1593 if not isId(ids[-1]):
1595 1594 ids.pop(); break
1596 1595 if not next(iterTokens) == '.':
1597 1596 break
1598 1597 except StopIteration:
1599 1598 break
1600 1599
1601 1600 # Find all named arguments already assigned to, as to avoid suggesting
1602 1601 # them again
1603 1602 usedNamedArgs = set()
1604 1603 par_level = -1
1605 1604 for token, next_token in zip(tokens, tokens[1:]):
1606 1605 if token == '(':
1607 1606 par_level += 1
1608 1607 elif token == ')':
1609 1608 par_level -= 1
1610 1609
1611 1610 if par_level != 0:
1612 1611 continue
1613 1612
1614 1613 if next_token != '=':
1615 1614 continue
1616 1615
1617 1616 usedNamedArgs.add(token)
1618 1617
1619 1618 argMatches = []
1620 1619 try:
1621 1620 callableObj = '.'.join(ids[::-1])
1622 1621 namedArgs = self._default_arguments(eval(callableObj,
1623 1622 self.namespace))
1624 1623
1625 1624 # Remove used named arguments from the list, no need to show twice
1626 1625 for namedArg in set(namedArgs) - usedNamedArgs:
1627 1626 if namedArg.startswith(text):
1628 1627 argMatches.append("%s=" %namedArg)
1629 1628 except:
1630 1629 pass
1631 1630
1632 1631 return argMatches
1633 1632
1634 1633 @staticmethod
1635 1634 def _get_keys(obj: Any) -> List[Any]:
1636 1635 # Objects can define their own completions by defining an
1637 1636 # _ipy_key_completions_() method.
1638 1637 method = get_real_method(obj, '_ipython_key_completions_')
1639 1638 if method is not None:
1640 1639 return method()
1641 1640
1642 1641 # Special case some common in-memory dict-like types
1643 1642 if isinstance(obj, dict) or\
1644 1643 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1645 1644 try:
1646 1645 return list(obj.keys())
1647 1646 except Exception:
1648 1647 return []
1649 1648 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1650 1649 _safe_isinstance(obj, 'numpy', 'void'):
1651 1650 return obj.dtype.names or []
1652 1651 return []
1653 1652
1654 1653 def dict_key_matches(self, text:str) -> List[str]:
1655 1654 "Match string keys in a dictionary, after e.g. 'foo[' "
1656 1655
1657 1656
1658 1657 if self.__dict_key_regexps is not None:
1659 1658 regexps = self.__dict_key_regexps
1660 1659 else:
1661 1660 dict_key_re_fmt = r'''(?x)
1662 1661 ( # match dict-referring expression wrt greedy setting
1663 1662 %s
1664 1663 )
1665 1664 \[ # open bracket
1666 1665 \s* # and optional whitespace
1667 1666 # Capture any number of str-like objects (e.g. "a", "b", 'c')
1668 1667 ((?:[uUbB]? # string prefix (r not handled)
1669 1668 (?:
1670 1669 '(?:[^']|(?<!\\)\\')*'
1671 1670 |
1672 1671 "(?:[^"]|(?<!\\)\\")*"
1673 1672 )
1674 1673 \s*,\s*
1675 1674 )*)
1676 1675 ([uUbB]? # string prefix (r not handled)
1677 1676 (?: # unclosed string
1678 1677 '(?:[^']|(?<!\\)\\')*
1679 1678 |
1680 1679 "(?:[^"]|(?<!\\)\\")*
1681 1680 )
1682 1681 )?
1683 1682 $
1684 1683 '''
1685 1684 regexps = self.__dict_key_regexps = {
1686 1685 False: re.compile(dict_key_re_fmt % r'''
1687 1686 # identifiers separated by .
1688 1687 (?!\d)\w+
1689 1688 (?:\.(?!\d)\w+)*
1690 1689 '''),
1691 1690 True: re.compile(dict_key_re_fmt % '''
1692 1691 .+
1693 1692 ''')
1694 1693 }
1695 1694
1696 1695 match = regexps[self.greedy].search(self.text_until_cursor)
1697 1696
1698 1697 if match is None:
1699 1698 return []
1700 1699
1701 1700 expr, prefix0, prefix = match.groups()
1702 1701 try:
1703 1702 obj = eval(expr, self.namespace)
1704 1703 except Exception:
1705 1704 try:
1706 1705 obj = eval(expr, self.global_namespace)
1707 1706 except Exception:
1708 1707 return []
1709 1708
1710 1709 keys = self._get_keys(obj)
1711 1710 if not keys:
1712 1711 return keys
1713 1712
1714 1713 extra_prefix = eval(prefix0) if prefix0 != '' else None
1715 1714
1716 1715 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
1717 1716 if not matches:
1718 1717 return matches
1719 1718
1720 1719 # get the cursor position of
1721 1720 # - the text being completed
1722 1721 # - the start of the key text
1723 1722 # - the start of the completion
1724 1723 text_start = len(self.text_until_cursor) - len(text)
1725 1724 if prefix:
1726 1725 key_start = match.start(3)
1727 1726 completion_start = key_start + token_offset
1728 1727 else:
1729 1728 key_start = completion_start = match.end()
1730 1729
1731 1730 # grab the leading prefix, to make sure all completions start with `text`
1732 1731 if text_start > key_start:
1733 1732 leading = ''
1734 1733 else:
1735 1734 leading = text[text_start:completion_start]
1736 1735
1737 1736 # the index of the `[` character
1738 1737 bracket_idx = match.end(1)
1739 1738
1740 1739 # append closing quote and bracket as appropriate
1741 1740 # this is *not* appropriate if the opening quote or bracket is outside
1742 1741 # the text given to this method
1743 1742 suf = ''
1744 1743 continuation = self.line_buffer[len(self.text_until_cursor):]
1745 1744 if key_start > text_start and closing_quote:
1746 1745 # quotes were opened inside text, maybe close them
1747 1746 if continuation.startswith(closing_quote):
1748 1747 continuation = continuation[len(closing_quote):]
1749 1748 else:
1750 1749 suf += closing_quote
1751 1750 if bracket_idx > text_start:
1752 1751 # brackets were opened inside text, maybe close them
1753 1752 if not continuation.startswith(']'):
1754 1753 suf += ']'
1755 1754
1756 1755 return [leading + k + suf for k in matches]
1757 1756
1758 1757 @staticmethod
1759 1758 def unicode_name_matches(text:str) -> Tuple[str, List[str]] :
1760 1759 """Match Latex-like syntax for unicode characters base
1761 1760 on the name of the character.
1762 1761
1763 1762 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1764 1763
1765 1764 Works only on valid python 3 identifier, or on combining characters that
1766 1765 will combine to form a valid identifier.
1767 1766 """
1768 1767 slashpos = text.rfind('\\')
1769 1768 if slashpos > -1:
1770 1769 s = text[slashpos+1:]
1771 1770 try :
1772 1771 unic = unicodedata.lookup(s)
1773 1772 # allow combining chars
1774 1773 if ('a'+unic).isidentifier():
1775 1774 return '\\'+s,[unic]
1776 1775 except KeyError:
1777 1776 pass
1778 1777 return '', []
1779 1778
1780 1779
1781 1780 def latex_matches(self, text:str) -> Tuple[str, Sequence[str]]:
1782 1781 """Match Latex syntax for unicode characters.
1783 1782
1784 1783 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1785 1784 """
1786 1785 slashpos = text.rfind('\\')
1787 1786 if slashpos > -1:
1788 1787 s = text[slashpos:]
1789 1788 if s in latex_symbols:
1790 1789 # Try to complete a full latex symbol to unicode
1791 1790 # \\alpha -> Ξ±
1792 1791 return s, [latex_symbols[s]]
1793 1792 else:
1794 1793 # If a user has partially typed a latex symbol, give them
1795 1794 # a full list of options \al -> [\aleph, \alpha]
1796 1795 matches = [k for k in latex_symbols if k.startswith(s)]
1797 1796 if matches:
1798 1797 return s, matches
1799 1798 return '', ()
1800 1799
1801 1800 def dispatch_custom_completer(self, text):
1802 1801 if not self.custom_completers:
1803 1802 return
1804 1803
1805 1804 line = self.line_buffer
1806 1805 if not line.strip():
1807 1806 return None
1808 1807
1809 1808 # Create a little structure to pass all the relevant information about
1810 1809 # the current completion to any custom completer.
1811 1810 event = SimpleNamespace()
1812 1811 event.line = line
1813 1812 event.symbol = text
1814 1813 cmd = line.split(None,1)[0]
1815 1814 event.command = cmd
1816 1815 event.text_until_cursor = self.text_until_cursor
1817 1816
1818 1817 # for foo etc, try also to find completer for %foo
1819 1818 if not cmd.startswith(self.magic_escape):
1820 1819 try_magic = self.custom_completers.s_matches(
1821 1820 self.magic_escape + cmd)
1822 1821 else:
1823 1822 try_magic = []
1824 1823
1825 1824 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1826 1825 try_magic,
1827 1826 self.custom_completers.flat_matches(self.text_until_cursor)):
1828 1827 try:
1829 1828 res = c(event)
1830 1829 if res:
1831 1830 # first, try case sensitive match
1832 1831 withcase = [r for r in res if r.startswith(text)]
1833 1832 if withcase:
1834 1833 return withcase
1835 1834 # if none, then case insensitive ones are ok too
1836 1835 text_low = text.lower()
1837 1836 return [r for r in res if r.lower().startswith(text_low)]
1838 1837 except TryNext:
1839 1838 pass
1840 1839 except KeyboardInterrupt:
1841 1840 """
1842 1841 If custom completer take too long,
1843 1842 let keyboard interrupt abort and return nothing.
1844 1843 """
1845 1844 break
1846 1845
1847 1846 return None
1848 1847
1849 1848 def completions(self, text: str, offset: int)->Iterator[Completion]:
1850 1849 """
1851 1850 Returns an iterator over the possible completions
1852 1851
1853 1852 .. warning::
1854 1853
1855 1854 Unstable
1856 1855
1857 1856 This function is unstable, API may change without warning.
1858 1857 It will also raise unless use in proper context manager.
1859 1858
1860 1859 Parameters
1861 1860 ----------
1862 1861 text : str
1863 1862 Full text of the current input, multi line string.
1864 1863 offset : int
1865 1864 Integer representing the position of the cursor in ``text``. Offset
1866 1865 is 0-based indexed.
1867 1866
1868 1867 Yields
1869 1868 ------
1870 1869 Completion
1871 1870
1872 1871 Notes
1873 1872 -----
1874 1873 The cursor on a text can either be seen as being "in between"
1875 1874 characters or "On" a character depending on the interface visible to
1876 1875 the user. For consistency the cursor being on "in between" characters X
1877 1876 and Y is equivalent to the cursor being "on" character Y, that is to say
1878 1877 the character the cursor is on is considered as being after the cursor.
1879 1878
1880 1879 Combining characters may span more that one position in the
1881 1880 text.
1882 1881
1883 1882 .. note::
1884 1883
1885 1884 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1886 1885 fake Completion token to distinguish completion returned by Jedi
1887 1886 and usual IPython completion.
1888 1887
1889 1888 .. note::
1890 1889
1891 1890 Completions are not completely deduplicated yet. If identical
1892 1891 completions are coming from different sources this function does not
1893 1892 ensure that each completion object will only be present once.
1894 1893 """
1895 1894 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1896 1895 "It may change without warnings. "
1897 1896 "Use in corresponding context manager.",
1898 1897 category=ProvisionalCompleterWarning, stacklevel=2)
1899 1898
1900 1899 seen = set()
1901 1900 profiler:Optional[cProfile.Profile]
1902 1901 try:
1903 1902 if self.profile_completions:
1904 1903 import cProfile
1905 1904 profiler = cProfile.Profile()
1906 1905 profiler.enable()
1907 1906 else:
1908 1907 profiler = None
1909 1908
1910 1909 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1911 1910 if c and (c in seen):
1912 1911 continue
1913 1912 yield c
1914 1913 seen.add(c)
1915 1914 except KeyboardInterrupt:
1916 1915 """if completions take too long and users send keyboard interrupt,
1917 1916 do not crash and return ASAP. """
1918 1917 pass
1919 1918 finally:
1920 1919 if profiler is not None:
1921 1920 profiler.disable()
1922 1921 ensure_dir_exists(self.profiler_output_dir)
1923 1922 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
1924 1923 print("Writing profiler output to", output_path)
1925 1924 profiler.dump_stats(output_path)
1926 1925
1927 1926 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
1928 1927 """
1929 1928 Core completion module.Same signature as :any:`completions`, with the
1930 1929 extra `timeout` parameter (in seconds).
1931 1930
1932 1931 Computing jedi's completion ``.type`` can be quite expensive (it is a
1933 1932 lazy property) and can require some warm-up, more warm up than just
1934 1933 computing the ``name`` of a completion. The warm-up can be :
1935 1934
1936 1935 - Long warm-up the first time a module is encountered after
1937 1936 install/update: actually build parse/inference tree.
1938 1937
1939 1938 - first time the module is encountered in a session: load tree from
1940 1939 disk.
1941 1940
1942 1941 We don't want to block completions for tens of seconds so we give the
1943 1942 completer a "budget" of ``_timeout`` seconds per invocation to compute
1944 1943 completions types, the completions that have not yet been computed will
1945 1944 be marked as "unknown" an will have a chance to be computed next round
1946 1945 are things get cached.
1947 1946
1948 1947 Keep in mind that Jedi is not the only thing treating the completion so
1949 1948 keep the timeout short-ish as if we take more than 0.3 second we still
1950 1949 have lots of processing to do.
1951 1950
1952 1951 """
1953 1952 deadline = time.monotonic() + _timeout
1954 1953
1955 1954
1956 1955 before = full_text[:offset]
1957 1956 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1958 1957
1959 1958 matched_text, matches, matches_origin, jedi_matches = self._complete(
1960 1959 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1961 1960
1962 1961 iter_jm = iter(jedi_matches)
1963 1962 if _timeout:
1964 1963 for jm in iter_jm:
1965 1964 try:
1966 1965 type_ = jm.type
1967 1966 except Exception:
1968 1967 if self.debug:
1969 1968 print("Error in Jedi getting type of ", jm)
1970 1969 type_ = None
1971 1970 delta = len(jm.name_with_symbols) - len(jm.complete)
1972 1971 if type_ == 'function':
1973 1972 signature = _make_signature(jm)
1974 1973 else:
1975 1974 signature = ''
1976 1975 yield Completion(start=offset - delta,
1977 1976 end=offset,
1978 1977 text=jm.name_with_symbols,
1979 1978 type=type_,
1980 1979 signature=signature,
1981 1980 _origin='jedi')
1982 1981
1983 1982 if time.monotonic() > deadline:
1984 1983 break
1985 1984
1986 1985 for jm in iter_jm:
1987 1986 delta = len(jm.name_with_symbols) - len(jm.complete)
1988 1987 yield Completion(start=offset - delta,
1989 1988 end=offset,
1990 1989 text=jm.name_with_symbols,
1991 1990 type='<unknown>', # don't compute type for speed
1992 1991 _origin='jedi',
1993 1992 signature='')
1994 1993
1995 1994
1996 1995 start_offset = before.rfind(matched_text)
1997 1996
1998 1997 # TODO:
1999 1998 # Suppress this, right now just for debug.
2000 1999 if jedi_matches and matches and self.debug:
2001 2000 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
2002 2001 _origin='debug', type='none', signature='')
2003 2002
2004 2003 # I'm unsure if this is always true, so let's assert and see if it
2005 2004 # crash
2006 2005 assert before.endswith(matched_text)
2007 2006 for m, t in zip(matches, matches_origin):
2008 2007 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
2009 2008
2010 2009
2011 2010 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2012 2011 """Find completions for the given text and line context.
2013 2012
2014 2013 Note that both the text and the line_buffer are optional, but at least
2015 2014 one of them must be given.
2016 2015
2017 2016 Parameters
2018 2017 ----------
2019 2018 text : string, optional
2020 2019 Text to perform the completion on. If not given, the line buffer
2021 2020 is split using the instance's CompletionSplitter object.
2022 2021 line_buffer : string, optional
2023 2022 If not given, the completer attempts to obtain the current line
2024 2023 buffer via readline. This keyword allows clients which are
2025 2024 requesting for text completions in non-readline contexts to inform
2026 2025 the completer of the entire text.
2027 2026 cursor_pos : int, optional
2028 2027 Index of the cursor in the full line buffer. Should be provided by
2029 2028 remote frontends where kernel has no access to frontend state.
2030 2029
2031 2030 Returns
2032 2031 -------
2033 2032 Tuple of two items:
2034 2033 text : str
2035 2034 Text that was actually used in the completion.
2036 2035 matches : list
2037 2036 A list of completion matches.
2038 2037
2039 2038 Notes
2040 2039 -----
2041 2040 This API is likely to be deprecated and replaced by
2042 2041 :any:`IPCompleter.completions` in the future.
2043 2042
2044 2043 """
2045 2044 warnings.warn('`Completer.complete` is pending deprecation since '
2046 2045 'IPython 6.0 and will be replaced by `Completer.completions`.',
2047 2046 PendingDeprecationWarning)
2048 2047 # potential todo, FOLD the 3rd throw away argument of _complete
2049 2048 # into the first 2 one.
2050 2049 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
2051 2050
2052 2051 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2053 2052 full_text=None) -> _CompleteResult:
2054 2053 """
2055 2054 Like complete but can also returns raw jedi completions as well as the
2056 2055 origin of the completion text. This could (and should) be made much
2057 2056 cleaner but that will be simpler once we drop the old (and stateful)
2058 2057 :any:`complete` API.
2059 2058
2060 2059 With current provisional API, cursor_pos act both (depending on the
2061 2060 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2062 2061 ``column`` when passing multiline strings this could/should be renamed
2063 2062 but would add extra noise.
2064 2063
2065 2064 Parameters
2066 2065 ----------
2067 2066 cursor_line
2068 2067 Index of the line the cursor is on. 0 indexed.
2069 2068 cursor_pos
2070 2069 Position of the cursor in the current line/line_buffer/text. 0
2071 2070 indexed.
2072 2071 line_buffer : optional, str
2073 2072 The current line the cursor is in, this is mostly due to legacy
2074 2073 reason that readline coudl only give a us the single current line.
2075 2074 Prefer `full_text`.
2076 2075 text : str
2077 2076 The current "token" the cursor is in, mostly also for historical
2078 2077 reasons. as the completer would trigger only after the current line
2079 2078 was parsed.
2080 2079 full_text : str
2081 2080 Full text of the current cell.
2082 2081
2083 2082 Returns
2084 2083 -------
2085 2084 A tuple of N elements which are (likely):
2086 2085 matched_text: ? the text that the complete matched
2087 2086 matches: list of completions ?
2088 2087 matches_origin: ? list same length as matches, and where each completion came from
2089 2088 jedi_matches: list of Jedi matches, have it's own structure.
2090 2089 """
2091 2090
2092 2091
2093 2092 # if the cursor position isn't given, the only sane assumption we can
2094 2093 # make is that it's at the end of the line (the common case)
2095 2094 if cursor_pos is None:
2096 2095 cursor_pos = len(line_buffer) if text is None else len(text)
2097 2096
2098 2097 if self.use_main_ns:
2099 2098 self.namespace = __main__.__dict__
2100 2099
2101 2100 # if text is either None or an empty string, rely on the line buffer
2102 2101 if (not line_buffer) and full_text:
2103 2102 line_buffer = full_text.split('\n')[cursor_line]
2104 2103 if not text: # issue #11508: check line_buffer before calling split_line
2105 2104 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2106 2105
2107 2106 if self.backslash_combining_completions:
2108 2107 # allow deactivation of these on windows.
2109 2108 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2110 2109
2111 2110 for meth in (self.latex_matches,
2112 2111 self.unicode_name_matches,
2113 2112 back_latex_name_matches,
2114 2113 back_unicode_name_matches,
2115 2114 self.fwd_unicode_match):
2116 2115 name_text, name_matches = meth(base_text)
2117 2116 if name_text:
2118 2117 return _CompleteResult(name_text, name_matches[:MATCHES_LIMIT], \
2119 2118 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ())
2120 2119
2121 2120
2122 2121 # If no line buffer is given, assume the input text is all there was
2123 2122 if line_buffer is None:
2124 2123 line_buffer = text
2125 2124
2126 2125 self.line_buffer = line_buffer
2127 2126 self.text_until_cursor = self.line_buffer[:cursor_pos]
2128 2127
2129 2128 # Do magic arg matches
2130 2129 for matcher in self.magic_arg_matchers:
2131 2130 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2132 2131 if matches:
2133 2132 origins = [matcher.__qualname__] * len(matches)
2134 2133 return _CompleteResult(text, matches, origins, ())
2135 2134
2136 2135 # Start with a clean slate of completions
2137 2136 matches = []
2138 2137
2139 2138 # FIXME: we should extend our api to return a dict with completions for
2140 2139 # different types of objects. The rlcomplete() method could then
2141 2140 # simply collapse the dict into a list for readline, but we'd have
2142 2141 # richer completion semantics in other environments.
2143 2142 completions:Iterable[Any] = []
2144 2143 if self.use_jedi:
2145 2144 if not full_text:
2146 2145 full_text = line_buffer
2147 2146 completions = self._jedi_matches(
2148 2147 cursor_pos, cursor_line, full_text)
2149 2148
2150 2149 if self.merge_completions:
2151 2150 matches = []
2152 2151 for matcher in self.matchers:
2153 2152 try:
2154 2153 matches.extend([(m, matcher.__qualname__)
2155 2154 for m in matcher(text)])
2156 2155 except:
2157 2156 # Show the ugly traceback if the matcher causes an
2158 2157 # exception, but do NOT crash the kernel!
2159 2158 sys.excepthook(*sys.exc_info())
2160 2159 else:
2161 2160 for matcher in self.matchers:
2162 2161 matches = [(m, matcher.__qualname__)
2163 2162 for m in matcher(text)]
2164 2163 if matches:
2165 2164 break
2166 2165
2167 2166 seen = set()
2168 2167 filtered_matches = set()
2169 2168 for m in matches:
2170 2169 t, c = m
2171 2170 if t not in seen:
2172 2171 filtered_matches.add(m)
2173 2172 seen.add(t)
2174 2173
2175 2174 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2176 2175
2177 2176 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2178 2177
2179 2178 _filtered_matches = custom_res or _filtered_matches
2180 2179
2181 2180 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2182 2181 _matches = [m[0] for m in _filtered_matches]
2183 2182 origins = [m[1] for m in _filtered_matches]
2184 2183
2185 2184 self.matches = _matches
2186 2185
2187 2186 return _CompleteResult(text, _matches, origins, completions)
2188 2187
2189 2188 def fwd_unicode_match(self, text:str) -> Tuple[str, Sequence[str]]:
2190 2189 """
2191 2190 Forward match a string starting with a backslash with a list of
2192 2191 potential Unicode completions.
2193 2192
2194 2193 Will compute list list of Unicode character names on first call and cache it.
2195 2194
2196 2195 Returns
2197 2196 -------
2198 2197 At tuple with:
2199 2198 - matched text (empty if no matches)
2200 2199 - list of potential completions, empty tuple otherwise)
2201 2200 """
2202 2201 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2203 2202 # We could do a faster match using a Trie.
2204 2203
2205 2204 # Using pygtrie the following seem to work:
2206 2205
2207 2206 # s = PrefixSet()
2208 2207
2209 2208 # for c in range(0,0x10FFFF + 1):
2210 2209 # try:
2211 2210 # s.add(unicodedata.name(chr(c)))
2212 2211 # except ValueError:
2213 2212 # pass
2214 2213 # [''.join(k) for k in s.iter(prefix)]
2215 2214
2216 2215 # But need to be timed and adds an extra dependency.
2217 2216
2218 2217 slashpos = text.rfind('\\')
2219 2218 # if text starts with slash
2220 2219 if slashpos > -1:
2221 2220 # PERF: It's important that we don't access self._unicode_names
2222 2221 # until we're inside this if-block. _unicode_names is lazily
2223 2222 # initialized, and it takes a user-noticeable amount of time to
2224 2223 # initialize it, so we don't want to initialize it unless we're
2225 2224 # actually going to use it.
2226 2225 s = text[slashpos+1:]
2227 2226 candidates = [x for x in self.unicode_names if x.startswith(s)]
2228 2227 if candidates:
2229 2228 return s, candidates
2230 2229 else:
2231 2230 return '', ()
2232 2231
2233 2232 # if text does not start with slash
2234 2233 else:
2235 2234 return '', ()
2236 2235
2237 2236 @property
2238 2237 def unicode_names(self) -> List[str]:
2239 2238 """List of names of unicode code points that can be completed.
2240 2239
2241 2240 The list is lazily initialized on first access.
2242 2241 """
2243 2242 if self._unicode_names is None:
2244 2243 names = []
2245 2244 for c in range(0,0x10FFFF + 1):
2246 2245 try:
2247 2246 names.append(unicodedata.name(chr(c)))
2248 2247 except ValueError:
2249 2248 pass
2250 2249 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2251 2250
2252 2251 return self._unicode_names
2253 2252
2254 2253 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2255 2254 names = []
2256 2255 for start,stop in ranges:
2257 2256 for c in range(start, stop) :
2258 2257 try:
2259 2258 names.append(unicodedata.name(chr(c)))
2260 2259 except ValueError:
2261 2260 pass
2262 2261 return names
@@ -1,703 +1,707 b''
1 1 """Implementation of namespace-related magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import gc
17 17 import re
18 18 import sys
19 19
20 20 # Our own packages
21 21 from IPython.core import page
22 22 from IPython.core.error import StdinNotImplementedError, UsageError
23 23 from IPython.core.magic import Magics, magics_class, line_magic
24 24 from IPython.testing.skipdoctest import skip_doctest
25 25 from IPython.utils.encoding import DEFAULT_ENCODING
26 26 from IPython.utils.openpy import read_py_file
27 27 from IPython.utils.path import get_py_filename
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Magic implementation classes
31 31 #-----------------------------------------------------------------------------
32 32
33 33 @magics_class
34 34 class NamespaceMagics(Magics):
35 35 """Magics to manage various aspects of the user's namespace.
36 36
37 37 These include listing variables, introspecting into them, etc.
38 38 """
39 39
40 40 @line_magic
41 41 def pinfo(self, parameter_s='', namespaces=None):
42 42 """Provide detailed information about an object.
43 43
44 44 '%pinfo object' is just a synonym for object? or ?object."""
45 45
46 46 #print 'pinfo par: <%s>' % parameter_s # dbg
47 47 # detail_level: 0 -> obj? , 1 -> obj??
48 48 detail_level = 0
49 49 # We need to detect if we got called as 'pinfo pinfo foo', which can
50 50 # happen if the user types 'pinfo foo?' at the cmd line.
51 51 pinfo,qmark1,oname,qmark2 = \
52 52 re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
53 53 if pinfo or qmark1 or qmark2:
54 54 detail_level = 1
55 55 if "*" in oname:
56 56 self.psearch(oname)
57 57 else:
58 58 self.shell._inspect('pinfo', oname, detail_level=detail_level,
59 59 namespaces=namespaces)
60 60
61 61 @line_magic
62 62 def pinfo2(self, parameter_s='', namespaces=None):
63 63 """Provide extra detailed information about an object.
64 64
65 65 '%pinfo2 object' is just a synonym for object?? or ??object."""
66 66 self.shell._inspect('pinfo', parameter_s, detail_level=1,
67 67 namespaces=namespaces)
68 68
69 69 @skip_doctest
70 70 @line_magic
71 71 def pdef(self, parameter_s='', namespaces=None):
72 72 """Print the call signature for any callable object.
73 73
74 74 If the object is a class, print the constructor information.
75 75
76 76 Examples
77 77 --------
78 78 ::
79 79
80 80 In [3]: %pdef urllib.urlopen
81 81 urllib.urlopen(url, data=None, proxies=None)
82 82 """
83 83 self.shell._inspect('pdef',parameter_s, namespaces)
84 84
85 85 @line_magic
86 86 def pdoc(self, parameter_s='', namespaces=None):
87 87 """Print the docstring for an object.
88 88
89 89 If the given object is a class, it will print both the class and the
90 90 constructor docstrings."""
91 91 self.shell._inspect('pdoc',parameter_s, namespaces)
92 92
93 93 @line_magic
94 94 def psource(self, parameter_s='', namespaces=None):
95 95 """Print (or run through pager) the source code for an object."""
96 96 if not parameter_s:
97 97 raise UsageError('Missing object name.')
98 98 self.shell._inspect('psource',parameter_s, namespaces)
99 99
100 100 @line_magic
101 101 def pfile(self, parameter_s='', namespaces=None):
102 102 """Print (or run through pager) the file where an object is defined.
103 103
104 104 The file opens at the line where the object definition begins. IPython
105 105 will honor the environment variable PAGER if set, and otherwise will
106 106 do its best to print the file in a convenient form.
107 107
108 108 If the given argument is not an object currently defined, IPython will
109 109 try to interpret it as a filename (automatically adding a .py extension
110 110 if needed). You can thus use %pfile as a syntax highlighting code
111 111 viewer."""
112 112
113 113 # first interpret argument as an object name
114 114 out = self.shell._inspect('pfile',parameter_s, namespaces)
115 115 # if not, try the input as a filename
116 116 if out == 'not found':
117 117 try:
118 118 filename = get_py_filename(parameter_s)
119 119 except IOError as msg:
120 120 print(msg)
121 121 return
122 122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123 123
124 124 @line_magic
125 125 def psearch(self, parameter_s=''):
126 126 """Search for object in namespaces by wildcard.
127 127
128 128 %psearch [options] PATTERN [OBJECT TYPE]
129 129
130 130 Note: ? can be used as a synonym for %psearch, at the beginning or at
131 131 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
132 132 rest of the command line must be unchanged (options come first), so
133 133 for example the following forms are equivalent
134 134
135 135 %psearch -i a* function
136 136 -i a* function?
137 137 ?-i a* function
138 138
139 139 Arguments:
140 140
141 141 PATTERN
142 142
143 143 where PATTERN is a string containing * as a wildcard similar to its
144 144 use in a shell. The pattern is matched in all namespaces on the
145 145 search path. By default objects starting with a single _ are not
146 146 matched, many IPython generated objects have a single
147 147 underscore. The default is case insensitive matching. Matching is
148 148 also done on the attributes of objects and not only on the objects
149 149 in a module.
150 150
151 151 [OBJECT TYPE]
152 152
153 153 Is the name of a python type from the types module. The name is
154 154 given in lowercase without the ending type, ex. StringType is
155 155 written string. By adding a type here only objects matching the
156 156 given type are matched. Using all here makes the pattern match all
157 157 types (this is the default).
158 158
159 159 Options:
160 160
161 161 -a: makes the pattern match even objects whose names start with a
162 162 single underscore. These names are normally omitted from the
163 163 search.
164 164
165 165 -i/-c: make the pattern case insensitive/sensitive. If neither of
166 166 these options are given, the default is read from your configuration
167 167 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
168 168 If this option is not specified in your configuration file, IPython's
169 169 internal default is to do a case sensitive search.
170 170
171 171 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
172 172 specify can be searched in any of the following namespaces:
173 173 'builtin', 'user', 'user_global','internal', 'alias', where
174 174 'builtin' and 'user' are the search defaults. Note that you should
175 175 not use quotes when specifying namespaces.
176 176
177 177 -l: List all available object types for object matching. This function
178 178 can be used without arguments.
179 179
180 180 'Builtin' contains the python module builtin, 'user' contains all
181 181 user data, 'alias' only contain the shell aliases and no python
182 182 objects, 'internal' contains objects used by IPython. The
183 183 'user_global' namespace is only used by embedded IPython instances,
184 184 and it contains module-level globals. You can add namespaces to the
185 185 search with -s or exclude them with -e (these options can be given
186 186 more than once).
187 187
188 188 Examples
189 189 --------
190 190 ::
191 191
192 192 %psearch a* -> objects beginning with an a
193 193 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
194 194 %psearch a* function -> all functions beginning with an a
195 195 %psearch re.e* -> objects beginning with an e in module re
196 196 %psearch r*.e* -> objects that start with e in modules starting in r
197 197 %psearch r*.* string -> all strings in modules beginning with r
198 198
199 199 Case sensitive search::
200 200
201 201 %psearch -c a* list all object beginning with lower case a
202 202
203 203 Show objects beginning with a single _::
204 204
205 205 %psearch -a _* list objects beginning with a single underscore
206 206
207 207 List available objects::
208 208
209 209 %psearch -l list all available object types
210 210 """
211 211 # default namespaces to be searched
212 212 def_search = ['user_local', 'user_global', 'builtin']
213 213
214 214 # Process options/args
215 215 opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True)
216 216 opt = opts.get
217 217 shell = self.shell
218 218 psearch = shell.inspector.psearch
219 219
220 220 # select list object types
221 221 list_types = False
222 222 if 'l' in opts:
223 223 list_types = True
224 224
225 225 # select case options
226 226 if 'i' in opts:
227 227 ignore_case = True
228 228 elif 'c' in opts:
229 229 ignore_case = False
230 230 else:
231 231 ignore_case = not shell.wildcards_case_sensitive
232 232
233 233 # Build list of namespaces to search from user options
234 234 def_search.extend(opt('s',[]))
235 235 ns_exclude = ns_exclude=opt('e',[])
236 236 ns_search = [nm for nm in def_search if nm not in ns_exclude]
237 237
238 238 # Call the actual search
239 239 try:
240 240 psearch(args,shell.ns_table,ns_search,
241 241 show_all=opt('a'),ignore_case=ignore_case, list_types=list_types)
242 242 except:
243 243 shell.showtraceback()
244 244
245 245 @skip_doctest
246 246 @line_magic
247 247 def who_ls(self, parameter_s=''):
248 248 """Return a sorted list of all interactive variables.
249 249
250 250 If arguments are given, only variables of types matching these
251 251 arguments are returned.
252 252
253 253 Examples
254 254 --------
255 255 Define two variables and list them with who_ls::
256 256
257 257 In [1]: alpha = 123
258 258
259 259 In [2]: beta = 'test'
260 260
261 261 In [3]: %who_ls
262 262 Out[3]: ['alpha', 'beta']
263 263
264 264 In [4]: %who_ls int
265 265 Out[4]: ['alpha']
266 266
267 267 In [5]: %who_ls str
268 268 Out[5]: ['beta']
269 269 """
270 270
271 271 user_ns = self.shell.user_ns
272 272 user_ns_hidden = self.shell.user_ns_hidden
273 273 nonmatching = object() # This can never be in user_ns
274 274 out = [ i for i in user_ns
275 275 if not i.startswith('_') \
276 276 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
277 277
278 278 typelist = parameter_s.split()
279 279 if typelist:
280 280 typeset = set(typelist)
281 281 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
282 282
283 283 out.sort()
284 284 return out
285 285
286 286 @skip_doctest
287 287 @line_magic
288 288 def who(self, parameter_s=''):
289 289 """Print all interactive variables, with some minimal formatting.
290 290
291 291 If any arguments are given, only variables whose type matches one of
292 292 these are printed. For example::
293 293
294 294 %who function str
295 295
296 296 will only list functions and strings, excluding all other types of
297 297 variables. To find the proper type names, simply use type(var) at a
298 298 command line to see how python prints type names. For example:
299 299
300 300 ::
301 301
302 302 In [1]: type('hello')\\
303 303 Out[1]: <type 'str'>
304 304
305 305 indicates that the type name for strings is 'str'.
306 306
307 307 ``%who`` always excludes executed names loaded through your configuration
308 308 file and things which are internal to IPython.
309 309
310 310 This is deliberate, as typically you may load many modules and the
311 311 purpose of %who is to show you only what you've manually defined.
312 312
313 313 Examples
314 314 --------
315 315
316 316 Define two variables and list them with who::
317 317
318 318 In [1]: alpha = 123
319 319
320 320 In [2]: beta = 'test'
321 321
322 322 In [3]: %who
323 323 alpha beta
324 324
325 325 In [4]: %who int
326 326 alpha
327 327
328 328 In [5]: %who str
329 329 beta
330 330 """
331 331
332 332 varlist = self.who_ls(parameter_s)
333 333 if not varlist:
334 334 if parameter_s:
335 335 print('No variables match your requested type.')
336 336 else:
337 337 print('Interactive namespace is empty.')
338 338 return
339 339
340 340 # if we have variables, move on...
341 341 count = 0
342 342 for i in varlist:
343 343 print(i+'\t', end=' ')
344 344 count += 1
345 345 if count > 8:
346 346 count = 0
347 347 print()
348 348 print()
349 349
350 350 @skip_doctest
351 351 @line_magic
352 352 def whos(self, parameter_s=''):
353 353 """Like %who, but gives some extra information about each variable.
354 354
355 355 The same type filtering of %who can be applied here.
356 356
357 357 For all variables, the type is printed. Additionally it prints:
358 358
359 359 - For {},[],(): their length.
360 360
361 361 - For numpy arrays, a summary with shape, number of
362 362 elements, typecode and size in memory.
363 363
364 364 - Everything else: a string representation, snipping their middle if
365 365 too long.
366 366
367 367 Examples
368 368 --------
369 369 Define two variables and list them with whos::
370 370
371 371 In [1]: alpha = 123
372 372
373 373 In [2]: beta = 'test'
374 374
375 375 In [3]: %whos
376 376 Variable Type Data/Info
377 377 --------------------------------
378 378 alpha int 123
379 379 beta str test
380 380 """
381 381
382 382 varnames = self.who_ls(parameter_s)
383 383 if not varnames:
384 384 if parameter_s:
385 385 print('No variables match your requested type.')
386 386 else:
387 387 print('Interactive namespace is empty.')
388 388 return
389 389
390 390 # if we have variables, move on...
391 391
392 392 # for these types, show len() instead of data:
393 393 seq_types = ['dict', 'list', 'tuple']
394 394
395 395 # for numpy arrays, display summary info
396 396 ndarray_type = None
397 397 if 'numpy' in sys.modules:
398 398 try:
399 399 from numpy import ndarray
400 400 except ImportError:
401 401 pass
402 402 else:
403 403 ndarray_type = ndarray.__name__
404 404
405 405 # Find all variable names and types so we can figure out column sizes
406 406
407 407 # some types are well known and can be shorter
408 408 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
409 409 def type_name(v):
410 410 tn = type(v).__name__
411 411 return abbrevs.get(tn,tn)
412 412
413 413 varlist = [self.shell.user_ns[n] for n in varnames]
414 414
415 415 typelist = []
416 416 for vv in varlist:
417 417 tt = type_name(vv)
418 418
419 419 if tt=='instance':
420 420 typelist.append( abbrevs.get(str(vv.__class__),
421 421 str(vv.__class__)))
422 422 else:
423 423 typelist.append(tt)
424 424
425 425 # column labels and # of spaces as separator
426 426 varlabel = 'Variable'
427 427 typelabel = 'Type'
428 428 datalabel = 'Data/Info'
429 429 colsep = 3
430 430 # variable format strings
431 431 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
432 432 aformat = "%s: %s elems, type `%s`, %s bytes"
433 433 # find the size of the columns to format the output nicely
434 434 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
435 435 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
436 436 # table header
437 437 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
438 438 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
439 439 # and the table itself
440 440 kb = 1024
441 441 Mb = 1048576 # kb**2
442 442 for vname,var,vtype in zip(varnames,varlist,typelist):
443 443 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
444 444 if vtype in seq_types:
445 445 print("n="+str(len(var)))
446 446 elif vtype == ndarray_type:
447 447 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
448 448 if vtype==ndarray_type:
449 449 # numpy
450 450 vsize = var.size
451 451 vbytes = vsize*var.itemsize
452 452 vdtype = var.dtype
453 453
454 454 if vbytes < 100000:
455 455 print(aformat % (vshape, vsize, vdtype, vbytes))
456 456 else:
457 457 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
458 458 if vbytes < Mb:
459 459 print('(%s kb)' % (vbytes/kb,))
460 460 else:
461 461 print('(%s Mb)' % (vbytes/Mb,))
462 462 else:
463 463 try:
464 464 vstr = str(var)
465 465 except UnicodeEncodeError:
466 466 vstr = var.encode(DEFAULT_ENCODING,
467 467 'backslashreplace')
468 468 except:
469 469 vstr = "<object with id %d (str() failed)>" % id(var)
470 470 vstr = vstr.replace('\n', '\\n')
471 471 if len(vstr) < 50:
472 472 print(vstr)
473 473 else:
474 474 print(vstr[:25] + "<...>" + vstr[-25:])
475 475
476 476 @line_magic
477 477 def reset(self, parameter_s=''):
478 478 """Resets the namespace by removing all names defined by the user, if
479 479 called without arguments, or by removing some types of objects, such
480 480 as everything currently in IPython's In[] and Out[] containers (see
481 481 the parameters for details).
482 482
483 483 Parameters
484 484 ----------
485 -f : force reset without asking for confirmation.
486 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
485 -f
486 force reset without asking for confirmation.
487 -s
488 'Soft' reset: Only clears your namespace, leaving history intact.
487 489 References to objects may be kept. By default (without this option),
488 490 we do a 'hard' reset, giving you a new session and removing all
489 491 references to objects from the current session.
490 --aggressive : Try to aggressively remove modules from sys.modules ; this
492 --aggressive
493 Try to aggressively remove modules from sys.modules ; this
491 494 may allow you to reimport Python modules that have been updated and
492 495 pick up changes, but can have unattended consequences.
496
493 497 in : reset input history
494 498 out : reset output history
495 499 dhist : reset directory history
496 500 array : reset only variables that are NumPy arrays
497 501
498 502 See Also
499 503 --------
500 504 reset_selective : invoked as ``%reset_selective``
501 505
502 506 Examples
503 507 --------
504 508 ::
505 509
506 510 In [6]: a = 1
507 511
508 512 In [7]: a
509 513 Out[7]: 1
510 514
511 515 In [8]: 'a' in get_ipython().user_ns
512 516 Out[8]: True
513 517
514 518 In [9]: %reset -f
515 519
516 520 In [1]: 'a' in get_ipython().user_ns
517 521 Out[1]: False
518 522
519 523 In [2]: %reset -f in
520 524 Flushing input history
521 525
522 526 In [3]: %reset -f dhist in
523 527 Flushing directory history
524 528 Flushing input history
525 529
526 530 Notes
527 531 -----
528 532 Calling this magic from clients that do not implement standard input,
529 533 such as the ipython notebook interface, will reset the namespace
530 534 without confirmation.
531 535 """
532 536 opts, args = self.parse_options(parameter_s, "sf", "aggressive", mode="list")
533 537 if "f" in opts:
534 538 ans = True
535 539 else:
536 540 try:
537 541 ans = self.shell.ask_yes_no(
538 542 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
539 543 default='n')
540 544 except StdinNotImplementedError:
541 545 ans = True
542 546 if not ans:
543 547 print('Nothing done.')
544 548 return
545 549
546 550 if 's' in opts: # Soft reset
547 551 user_ns = self.shell.user_ns
548 552 for i in self.who_ls():
549 553 del(user_ns[i])
550 554 elif len(args) == 0: # Hard reset
551 555 self.shell.reset(new_session=False, aggressive=("aggressive" in opts))
552 556
553 557 # reset in/out/dhist/array: previously extensinions/clearcmd.py
554 558 ip = self.shell
555 559 user_ns = self.shell.user_ns # local lookup, heavily used
556 560
557 561 for target in args:
558 562 target = target.lower() # make matches case insensitive
559 563 if target == 'out':
560 564 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
561 565 self.shell.displayhook.flush()
562 566
563 567 elif target == 'in':
564 568 print("Flushing input history")
565 569 pc = self.shell.displayhook.prompt_count + 1
566 570 for n in range(1, pc):
567 571 key = '_i'+repr(n)
568 572 user_ns.pop(key,None)
569 573 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
570 574 hm = ip.history_manager
571 575 # don't delete these, as %save and %macro depending on the
572 576 # length of these lists to be preserved
573 577 hm.input_hist_parsed[:] = [''] * pc
574 578 hm.input_hist_raw[:] = [''] * pc
575 579 # hm has internal machinery for _i,_ii,_iii, clear it out
576 580 hm._i = hm._ii = hm._iii = hm._i00 = u''
577 581
578 582 elif target == 'array':
579 583 # Support cleaning up numpy arrays
580 584 try:
581 585 from numpy import ndarray
582 586 # This must be done with items and not iteritems because
583 587 # we're going to modify the dict in-place.
584 588 for x,val in list(user_ns.items()):
585 589 if isinstance(val,ndarray):
586 590 del user_ns[x]
587 591 except ImportError:
588 592 print("reset array only works if Numpy is available.")
589 593
590 594 elif target == 'dhist':
591 595 print("Flushing directory history")
592 596 del user_ns['_dh'][:]
593 597
594 598 else:
595 599 print("Don't know how to reset ", end=' ')
596 600 print(target + ", please run `%reset?` for details")
597 601
598 602 gc.collect()
599 603
600 604 @line_magic
601 605 def reset_selective(self, parameter_s=''):
602 606 """Resets the namespace by removing names defined by the user.
603 607
604 608 Input/Output history are left around in case you need them.
605 609
606 610 %reset_selective [-f] regex
607 611
608 612 No action is taken if regex is not included
609 613
610 614 Options
611 615 -f : force reset without asking for confirmation.
612 616
613 617 See Also
614 618 --------
615 619 reset : invoked as ``%reset``
616 620
617 621 Examples
618 622 --------
619 623 We first fully reset the namespace so your output looks identical to
620 624 this example for pedagogical reasons; in practice you do not need a
621 625 full reset::
622 626
623 627 In [1]: %reset -f
624 628
625 629 Now, with a clean namespace we can make a few variables and use
626 630 ``%reset_selective`` to only delete names that match our regexp::
627 631
628 632 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
629 633
630 634 In [3]: who_ls
631 635 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
632 636
633 637 In [4]: %reset_selective -f b[2-3]m
634 638
635 639 In [5]: who_ls
636 640 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
637 641
638 642 In [6]: %reset_selective -f d
639 643
640 644 In [7]: who_ls
641 645 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
642 646
643 647 In [8]: %reset_selective -f c
644 648
645 649 In [9]: who_ls
646 650 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
647 651
648 652 In [10]: %reset_selective -f b
649 653
650 654 In [11]: who_ls
651 655 Out[11]: ['a']
652 656
653 657 Notes
654 658 -----
655 659 Calling this magic from clients that do not implement standard input,
656 660 such as the ipython notebook interface, will reset the namespace
657 661 without confirmation.
658 662 """
659 663
660 664 opts, regex = self.parse_options(parameter_s,'f')
661 665
662 666 if 'f' in opts:
663 667 ans = True
664 668 else:
665 669 try:
666 670 ans = self.shell.ask_yes_no(
667 671 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
668 672 default='n')
669 673 except StdinNotImplementedError:
670 674 ans = True
671 675 if not ans:
672 676 print('Nothing done.')
673 677 return
674 678 user_ns = self.shell.user_ns
675 679 if not regex:
676 680 print('No regex pattern specified. Nothing done.')
677 681 return
678 682 else:
679 683 try:
680 684 m = re.compile(regex)
681 685 except TypeError as e:
682 686 raise TypeError('regex must be a string or compiled pattern') from e
683 687 for i in self.who_ls():
684 688 if m.search(i):
685 689 del(user_ns[i])
686 690
687 691 @line_magic
688 692 def xdel(self, parameter_s=''):
689 693 """Delete a variable, trying to clear it from anywhere that
690 694 IPython's machinery has references to it. By default, this uses
691 695 the identity of the named object in the user namespace to remove
692 696 references held under other names. The object is also removed
693 697 from the output history.
694 698
695 699 Options
696 700 -n : Delete the specified name from all namespaces, without
697 701 checking their identity.
698 702 """
699 703 opts, varname = self.parse_options(parameter_s,'n')
700 704 try:
701 705 self.shell.del_var(varname, ('n' in opts))
702 706 except (NameError, ValueError) as e:
703 707 print(type(e).__name__ +": "+ str(e))
General Comments 0
You need to be logged in to leave comments. Login now