##// END OF EJS Templates
Merge pull request #13827 from krassowski/improve-completer-docs...
Matthias Bussonnier -
r27882:fb2642c5 merge
parent child Browse files
Show More
@@ -1,2970 +1,2977 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 Matchers
105 105 ========
106 106
107 107 All completions routines are implemented using unified *Matchers* API.
108 108 The matchers API is provisional and subject to change without notice.
109 109
110 110 The built-in matchers include:
111 111
112 112 - :any:`IPCompleter.dict_key_matcher`: dictionary key completions,
113 113 - :any:`IPCompleter.magic_matcher`: completions for magics,
114 114 - :any:`IPCompleter.unicode_name_matcher`,
115 115 :any:`IPCompleter.fwd_unicode_matcher`
116 116 and :any:`IPCompleter.latex_name_matcher`: see `Forward latex/unicode completion`_,
117 117 - :any:`back_unicode_name_matcher` and :any:`back_latex_name_matcher`: see `Backward latex completion`_,
118 118 - :any:`IPCompleter.file_matcher`: paths to files and directories,
119 119 - :any:`IPCompleter.python_func_kw_matcher` - function keywords,
120 120 - :any:`IPCompleter.python_matches` - globals and attributes (v1 API),
121 121 - ``IPCompleter.jedi_matcher`` - static analysis with Jedi,
122 122 - :any:`IPCompleter.custom_completer_matcher` - pluggable completer with a default
123 123 implementation in :any:`InteractiveShell` which uses IPython hooks system
124 124 (`complete_command`) with string dispatch (including regular expressions).
125 125 Differently to other matchers, ``custom_completer_matcher`` will not suppress
126 126 Jedi results to match behaviour in earlier IPython versions.
127 127
128 128 Custom matchers can be added by appending to ``IPCompleter.custom_matchers`` list.
129 129
130 130 Matcher API
131 131 -----------
132 132
133 133 Simplifying some details, the ``Matcher`` interface can described as
134 134
135 135 .. code-block::
136 136
137 137 MatcherAPIv1 = Callable[[str], list[str]]
138 138 MatcherAPIv2 = Callable[[CompletionContext], SimpleMatcherResult]
139 139
140 140 Matcher = MatcherAPIv1 | MatcherAPIv2
141 141
142 142 The ``MatcherAPIv1`` reflects the matcher API as available prior to IPython 8.6.0
143 143 and remains supported as a simplest way for generating completions. This is also
144 144 currently the only API supported by the IPython hooks system `complete_command`.
145 145
146 146 To distinguish between matcher versions ``matcher_api_version`` attribute is used.
147 147 More precisely, the API allows to omit ``matcher_api_version`` for v1 Matchers,
148 148 and requires a literal ``2`` for v2 Matchers.
149 149
150 150 Once the API stabilises future versions may relax the requirement for specifying
151 151 ``matcher_api_version`` by switching to :any:`functools.singledispatch`, therefore
152 152 please do not rely on the presence of ``matcher_api_version`` for any purposes.
153 153
154 154 Suppression of competing matchers
155 155 ---------------------------------
156 156
157 157 By default results from all matchers are combined, in the order determined by
158 158 their priority. Matchers can request to suppress results from subsequent
159 159 matchers by setting ``suppress`` to ``True`` in the ``MatcherResult``.
160 160
161 161 When multiple matchers simultaneously request surpression, the results from of
162 162 the matcher with higher priority will be returned.
163 163
164 164 Sometimes it is desirable to suppress most but not all other matchers;
165 165 this can be achieved by adding a list of identifiers of matchers which
166 166 should not be suppressed to ``MatcherResult`` under ``do_not_suppress`` key.
167 167
168 168 The suppression behaviour can is user-configurable via
169 169 :any:`IPCompleter.suppress_competing_matchers`.
170 170 """
171 171
172 172
173 173 # Copyright (c) IPython Development Team.
174 174 # Distributed under the terms of the Modified BSD License.
175 175 #
176 176 # Some of this code originated from rlcompleter in the Python standard library
177 177 # Copyright (C) 2001 Python Software Foundation, www.python.org
178 178
179 179 from __future__ import annotations
180 180 import builtins as builtin_mod
181 181 import glob
182 182 import inspect
183 183 import itertools
184 184 import keyword
185 185 import os
186 186 import re
187 187 import string
188 188 import sys
189 189 import time
190 190 import unicodedata
191 191 import uuid
192 192 import warnings
193 193 from contextlib import contextmanager
194 194 from dataclasses import dataclass
195 195 from functools import cached_property, partial
196 196 from importlib import import_module
197 197 from types import SimpleNamespace
198 198 from typing import (
199 199 Iterable,
200 200 Iterator,
201 201 List,
202 202 Tuple,
203 203 Union,
204 204 Any,
205 205 Sequence,
206 206 Dict,
207 207 NamedTuple,
208 208 Pattern,
209 209 Optional,
210 210 TYPE_CHECKING,
211 211 Set,
212 212 Literal,
213 213 )
214 214
215 215 from IPython.core.error import TryNext
216 216 from IPython.core.inputtransformer2 import ESC_MAGIC
217 217 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
218 218 from IPython.core.oinspect import InspectColors
219 219 from IPython.testing.skipdoctest import skip_doctest
220 220 from IPython.utils import generics
221 221 from IPython.utils.decorators import sphinx_options
222 222 from IPython.utils.dir2 import dir2, get_real_method
223 223 from IPython.utils.docs import GENERATING_DOCUMENTATION
224 224 from IPython.utils.path import ensure_dir_exists
225 225 from IPython.utils.process import arg_split
226 226 from traitlets import (
227 227 Bool,
228 228 Enum,
229 229 Int,
230 230 List as ListTrait,
231 231 Unicode,
232 232 Dict as DictTrait,
233 233 Union as UnionTrait,
234 234 default,
235 235 observe,
236 236 )
237 237 from traitlets.config.configurable import Configurable
238 238
239 239 import __main__
240 240
241 241 # skip module docstests
242 242 __skip_doctest__ = True
243 243
244 244
245 245 try:
246 246 import jedi
247 247 jedi.settings.case_insensitive_completion = False
248 248 import jedi.api.helpers
249 249 import jedi.api.classes
250 250 JEDI_INSTALLED = True
251 251 except ImportError:
252 252 JEDI_INSTALLED = False
253 253
254 254
255 255 if TYPE_CHECKING or GENERATING_DOCUMENTATION:
256 256 from typing import cast
257 257 from typing_extensions import TypedDict, NotRequired, Protocol, TypeAlias
258 258 else:
259 259
260 260 def cast(obj, type_):
261 261 """Workaround for `TypeError: MatcherAPIv2() takes no arguments`"""
262 262 return obj
263 263
264 264 # do not require on runtime
265 265 NotRequired = Tuple # requires Python >=3.11
266 266 TypedDict = Dict # by extension of `NotRequired` requires 3.11 too
267 267 Protocol = object # requires Python >=3.8
268 268 TypeAlias = Any # requires Python >=3.10
269 269 if GENERATING_DOCUMENTATION:
270 270 from typing import TypedDict
271 271
272 272 # -----------------------------------------------------------------------------
273 273 # Globals
274 274 #-----------------------------------------------------------------------------
275 275
276 276 # ranges where we have most of the valid unicode names. We could be more finer
277 277 # grained but is it worth it for performance While unicode have character in the
278 278 # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
279 279 # write this). With below range we cover them all, with a density of ~67%
280 280 # biggest next gap we consider only adds up about 1% density and there are 600
281 281 # gaps that would need hard coding.
282 282 _UNICODE_RANGES = [(32, 0x3134b), (0xe0001, 0xe01f0)]
283 283
284 284 # Public API
285 285 __all__ = ["Completer", "IPCompleter"]
286 286
287 287 if sys.platform == 'win32':
288 288 PROTECTABLES = ' '
289 289 else:
290 290 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
291 291
292 292 # Protect against returning an enormous number of completions which the frontend
293 293 # may have trouble processing.
294 294 MATCHES_LIMIT = 500
295 295
296 296 # Completion type reported when no type can be inferred.
297 297 _UNKNOWN_TYPE = "<unknown>"
298 298
299 299 class ProvisionalCompleterWarning(FutureWarning):
300 300 """
301 301 Exception raise by an experimental feature in this module.
302 302
303 303 Wrap code in :any:`provisionalcompleter` context manager if you
304 304 are certain you want to use an unstable feature.
305 305 """
306 306 pass
307 307
308 308 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
309 309
310 310
311 311 @skip_doctest
312 312 @contextmanager
313 313 def provisionalcompleter(action='ignore'):
314 314 """
315 315 This context manager has to be used in any place where unstable completer
316 316 behavior and API may be called.
317 317
318 318 >>> with provisionalcompleter():
319 319 ... completer.do_experimental_things() # works
320 320
321 321 >>> completer.do_experimental_things() # raises.
322 322
323 323 .. note::
324 324
325 325 Unstable
326 326
327 327 By using this context manager you agree that the API in use may change
328 328 without warning, and that you won't complain if they do so.
329 329
330 330 You also understand that, if the API is not to your liking, you should report
331 331 a bug to explain your use case upstream.
332 332
333 333 We'll be happy to get your feedback, feature requests, and improvements on
334 334 any of the unstable APIs!
335 335 """
336 336 with warnings.catch_warnings():
337 337 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
338 338 yield
339 339
340 340
341 341 def has_open_quotes(s):
342 342 """Return whether a string has open quotes.
343 343
344 344 This simply counts whether the number of quote characters of either type in
345 345 the string is odd.
346 346
347 347 Returns
348 348 -------
349 349 If there is an open quote, the quote character is returned. Else, return
350 350 False.
351 351 """
352 352 # We check " first, then ', so complex cases with nested quotes will get
353 353 # the " to take precedence.
354 354 if s.count('"') % 2:
355 355 return '"'
356 356 elif s.count("'") % 2:
357 357 return "'"
358 358 else:
359 359 return False
360 360
361 361
362 362 def protect_filename(s, protectables=PROTECTABLES):
363 363 """Escape a string to protect certain characters."""
364 364 if set(s) & set(protectables):
365 365 if sys.platform == "win32":
366 366 return '"' + s + '"'
367 367 else:
368 368 return "".join(("\\" + c if c in protectables else c) for c in s)
369 369 else:
370 370 return s
371 371
372 372
373 373 def expand_user(path:str) -> Tuple[str, bool, str]:
374 374 """Expand ``~``-style usernames in strings.
375 375
376 376 This is similar to :func:`os.path.expanduser`, but it computes and returns
377 377 extra information that will be useful if the input was being used in
378 378 computing completions, and you wish to return the completions with the
379 379 original '~' instead of its expanded value.
380 380
381 381 Parameters
382 382 ----------
383 383 path : str
384 384 String to be expanded. If no ~ is present, the output is the same as the
385 385 input.
386 386
387 387 Returns
388 388 -------
389 389 newpath : str
390 390 Result of ~ expansion in the input path.
391 391 tilde_expand : bool
392 392 Whether any expansion was performed or not.
393 393 tilde_val : str
394 394 The value that ~ was replaced with.
395 395 """
396 396 # Default values
397 397 tilde_expand = False
398 398 tilde_val = ''
399 399 newpath = path
400 400
401 401 if path.startswith('~'):
402 402 tilde_expand = True
403 403 rest = len(path)-1
404 404 newpath = os.path.expanduser(path)
405 405 if rest:
406 406 tilde_val = newpath[:-rest]
407 407 else:
408 408 tilde_val = newpath
409 409
410 410 return newpath, tilde_expand, tilde_val
411 411
412 412
413 413 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
414 414 """Does the opposite of expand_user, with its outputs.
415 415 """
416 416 if tilde_expand:
417 417 return path.replace(tilde_val, '~')
418 418 else:
419 419 return path
420 420
421 421
422 422 def completions_sorting_key(word):
423 423 """key for sorting completions
424 424
425 425 This does several things:
426 426
427 427 - Demote any completions starting with underscores to the end
428 428 - Insert any %magic and %%cellmagic completions in the alphabetical order
429 429 by their name
430 430 """
431 431 prio1, prio2 = 0, 0
432 432
433 433 if word.startswith('__'):
434 434 prio1 = 2
435 435 elif word.startswith('_'):
436 436 prio1 = 1
437 437
438 438 if word.endswith('='):
439 439 prio1 = -1
440 440
441 441 if word.startswith('%%'):
442 442 # If there's another % in there, this is something else, so leave it alone
443 443 if not "%" in word[2:]:
444 444 word = word[2:]
445 445 prio2 = 2
446 446 elif word.startswith('%'):
447 447 if not "%" in word[1:]:
448 448 word = word[1:]
449 449 prio2 = 1
450 450
451 451 return prio1, word, prio2
452 452
453 453
454 454 class _FakeJediCompletion:
455 455 """
456 456 This is a workaround to communicate to the UI that Jedi has crashed and to
457 457 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
458 458
459 459 Added in IPython 6.0 so should likely be removed for 7.0
460 460
461 461 """
462 462
463 463 def __init__(self, name):
464 464
465 465 self.name = name
466 466 self.complete = name
467 467 self.type = 'crashed'
468 468 self.name_with_symbols = name
469 469 self.signature = ''
470 470 self._origin = 'fake'
471 471
472 472 def __repr__(self):
473 473 return '<Fake completion object jedi has crashed>'
474 474
475 475
476 476 _JediCompletionLike = Union[jedi.api.Completion, _FakeJediCompletion]
477 477
478 478
479 479 class Completion:
480 480 """
481 481 Completion object used and returned by IPython completers.
482 482
483 483 .. warning::
484 484
485 485 Unstable
486 486
487 487 This function is unstable, API may change without warning.
488 488 It will also raise unless use in proper context manager.
489 489
490 490 This act as a middle ground :any:`Completion` object between the
491 491 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
492 492 object. While Jedi need a lot of information about evaluator and how the
493 493 code should be ran/inspected, PromptToolkit (and other frontend) mostly
494 494 need user facing information.
495 495
496 496 - Which range should be replaced replaced by what.
497 497 - Some metadata (like completion type), or meta information to displayed to
498 498 the use user.
499 499
500 500 For debugging purpose we can also store the origin of the completion (``jedi``,
501 501 ``IPython.python_matches``, ``IPython.magics_matches``...).
502 502 """
503 503
504 504 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
505 505
506 506 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
507 507 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
508 508 "It may change without warnings. "
509 509 "Use in corresponding context manager.",
510 510 category=ProvisionalCompleterWarning, stacklevel=2)
511 511
512 512 self.start = start
513 513 self.end = end
514 514 self.text = text
515 515 self.type = type
516 516 self.signature = signature
517 517 self._origin = _origin
518 518
519 519 def __repr__(self):
520 520 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
521 521 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
522 522
523 523 def __eq__(self, other)->Bool:
524 524 """
525 525 Equality and hash do not hash the type (as some completer may not be
526 526 able to infer the type), but are use to (partially) de-duplicate
527 527 completion.
528 528
529 529 Completely de-duplicating completion is a bit tricker that just
530 530 comparing as it depends on surrounding text, which Completions are not
531 531 aware of.
532 532 """
533 533 return self.start == other.start and \
534 534 self.end == other.end and \
535 535 self.text == other.text
536 536
537 537 def __hash__(self):
538 538 return hash((self.start, self.end, self.text))
539 539
540 540
541 541 class SimpleCompletion:
542 542 """Completion item to be included in the dictionary returned by new-style Matcher (API v2).
543 543
544 544 .. warning::
545 545
546 546 Provisional
547 547
548 548 This class is used to describe the currently supported attributes of
549 549 simple completion items, and any additional implementation details
550 550 should not be relied on. Additional attributes may be included in
551 551 future versions, and meaning of text disambiguated from the current
552 552 dual meaning of "text to insert" and "text to used as a label".
553 553 """
554 554
555 555 __slots__ = ["text", "type"]
556 556
557 557 def __init__(self, text: str, *, type: str = None):
558 558 self.text = text
559 559 self.type = type
560 560
561 561 def __repr__(self):
562 562 return f"<SimpleCompletion text={self.text!r} type={self.type!r}>"
563 563
564 564
565 565 class _MatcherResultBase(TypedDict):
566 566 """Definition of dictionary to be returned by new-style Matcher (API v2)."""
567 567
568 568 #: Suffix of the provided ``CompletionContext.token``, if not given defaults to full token.
569 569 matched_fragment: NotRequired[str]
570 570
571 571 #: Whether to suppress results from all other matchers (True), some
572 572 #: matchers (set of identifiers) or none (False); default is False.
573 573 suppress: NotRequired[Union[bool, Set[str]]]
574 574
575 575 #: Identifiers of matchers which should NOT be suppressed when this matcher
576 576 #: requests to suppress all other matchers; defaults to an empty set.
577 577 do_not_suppress: NotRequired[Set[str]]
578 578
579 579 #: Are completions already ordered and should be left as-is? default is False.
580 580 ordered: NotRequired[bool]
581 581
582 582
583 583 @sphinx_options(show_inherited_members=True, exclude_inherited_from=["dict"])
584 584 class SimpleMatcherResult(_MatcherResultBase, TypedDict):
585 585 """Result of new-style completion matcher."""
586 586
587 587 # note: TypedDict is added again to the inheritance chain
588 588 # in order to get __orig_bases__ for documentation
589 589
590 590 #: List of candidate completions
591 591 completions: Sequence[SimpleCompletion]
592 592
593 593
594 594 class _JediMatcherResult(_MatcherResultBase):
595 595 """Matching result returned by Jedi (will be processed differently)"""
596 596
597 597 #: list of candidate completions
598 598 completions: Iterable[_JediCompletionLike]
599 599
600 600
601 601 @dataclass
602 602 class CompletionContext:
603 603 """Completion context provided as an argument to matchers in the Matcher API v2."""
604 604
605 605 # rationale: many legacy matchers relied on completer state (`self.text_until_cursor`)
606 606 # which was not explicitly visible as an argument of the matcher, making any refactor
607 607 # prone to errors; by explicitly passing `cursor_position` we can decouple the matchers
608 608 # from the completer, and make substituting them in sub-classes easier.
609 609
610 610 #: Relevant fragment of code directly preceding the cursor.
611 611 #: The extraction of token is implemented via splitter heuristic
612 612 #: (following readline behaviour for legacy reasons), which is user configurable
613 613 #: (by switching the greedy mode).
614 614 token: str
615 615
616 616 #: The full available content of the editor or buffer
617 617 full_text: str
618 618
619 619 #: Cursor position in the line (the same for ``full_text`` and ``text``).
620 620 cursor_position: int
621 621
622 622 #: Cursor line in ``full_text``.
623 623 cursor_line: int
624 624
625 625 #: The maximum number of completions that will be used downstream.
626 626 #: Matchers can use this information to abort early.
627 627 #: The built-in Jedi matcher is currently excepted from this limit.
628 628 # If not given, return all possible completions.
629 629 limit: Optional[int]
630 630
631 631 @cached_property
632 632 def text_until_cursor(self) -> str:
633 633 return self.line_with_cursor[: self.cursor_position]
634 634
635 635 @cached_property
636 636 def line_with_cursor(self) -> str:
637 637 return self.full_text.split("\n")[self.cursor_line]
638 638
639 639
640 640 #: Matcher results for API v2.
641 641 MatcherResult = Union[SimpleMatcherResult, _JediMatcherResult]
642 642
643 643
644 644 class _MatcherAPIv1Base(Protocol):
645 645 def __call__(self, text: str) -> list[str]:
646 646 """Call signature."""
647 647
648 648
649 649 class _MatcherAPIv1Total(_MatcherAPIv1Base, Protocol):
650 650 #: API version
651 651 matcher_api_version: Optional[Literal[1]]
652 652
653 653 def __call__(self, text: str) -> list[str]:
654 654 """Call signature."""
655 655
656 656
657 657 #: Protocol describing Matcher API v1.
658 658 MatcherAPIv1: TypeAlias = Union[_MatcherAPIv1Base, _MatcherAPIv1Total]
659 659
660 660
661 661 class MatcherAPIv2(Protocol):
662 662 """Protocol describing Matcher API v2."""
663 663
664 664 #: API version
665 665 matcher_api_version: Literal[2] = 2
666 666
667 667 def __call__(self, context: CompletionContext) -> MatcherResult:
668 668 """Call signature."""
669 669
670 670
671 671 Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2]
672 672
673 673
674 674 def has_any_completions(result: MatcherResult) -> bool:
675 675 """Check if any result includes any completions."""
676 676 if hasattr(result["completions"], "__len__"):
677 677 return len(result["completions"]) != 0
678 678 try:
679 679 old_iterator = result["completions"]
680 680 first = next(old_iterator)
681 681 result["completions"] = itertools.chain([first], old_iterator)
682 682 return True
683 683 except StopIteration:
684 684 return False
685 685
686 686
687 687 def completion_matcher(
688 688 *, priority: float = None, identifier: str = None, api_version: int = 1
689 689 ):
690 690 """Adds attributes describing the matcher.
691 691
692 692 Parameters
693 693 ----------
694 694 priority : Optional[float]
695 695 The priority of the matcher, determines the order of execution of matchers.
696 696 Higher priority means that the matcher will be executed first. Defaults to 0.
697 697 identifier : Optional[str]
698 698 identifier of the matcher allowing users to modify the behaviour via traitlets,
699 699 and also used to for debugging (will be passed as ``origin`` with the completions).
700 Defaults to matcher function ``__qualname__``.
700
701 Defaults to matcher function's ``__qualname__`` (for example,
702 ``IPCompleter.file_matcher`` for the built-in matched defined
703 as a ``file_matcher`` method of the ``IPCompleter`` class).
701 704 api_version: Optional[int]
702 705 version of the Matcher API used by this matcher.
703 706 Currently supported values are 1 and 2.
704 707 Defaults to 1.
705 708 """
706 709
707 710 def wrapper(func: Matcher):
708 711 func.matcher_priority = priority or 0
709 712 func.matcher_identifier = identifier or func.__qualname__
710 713 func.matcher_api_version = api_version
711 714 if TYPE_CHECKING:
712 715 if api_version == 1:
713 716 func = cast(func, MatcherAPIv1)
714 717 elif api_version == 2:
715 718 func = cast(func, MatcherAPIv2)
716 719 return func
717 720
718 721 return wrapper
719 722
720 723
721 724 def _get_matcher_priority(matcher: Matcher):
722 725 return getattr(matcher, "matcher_priority", 0)
723 726
724 727
725 728 def _get_matcher_id(matcher: Matcher):
726 729 return getattr(matcher, "matcher_identifier", matcher.__qualname__)
727 730
728 731
729 732 def _get_matcher_api_version(matcher):
730 733 return getattr(matcher, "matcher_api_version", 1)
731 734
732 735
733 736 context_matcher = partial(completion_matcher, api_version=2)
734 737
735 738
736 739 _IC = Iterable[Completion]
737 740
738 741
739 742 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
740 743 """
741 744 Deduplicate a set of completions.
742 745
743 746 .. warning::
744 747
745 748 Unstable
746 749
747 750 This function is unstable, API may change without warning.
748 751
749 752 Parameters
750 753 ----------
751 754 text : str
752 755 text that should be completed.
753 756 completions : Iterator[Completion]
754 757 iterator over the completions to deduplicate
755 758
756 759 Yields
757 760 ------
758 761 `Completions` objects
759 762 Completions coming from multiple sources, may be different but end up having
760 763 the same effect when applied to ``text``. If this is the case, this will
761 764 consider completions as equal and only emit the first encountered.
762 765 Not folded in `completions()` yet for debugging purpose, and to detect when
763 766 the IPython completer does return things that Jedi does not, but should be
764 767 at some point.
765 768 """
766 769 completions = list(completions)
767 770 if not completions:
768 771 return
769 772
770 773 new_start = min(c.start for c in completions)
771 774 new_end = max(c.end for c in completions)
772 775
773 776 seen = set()
774 777 for c in completions:
775 778 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
776 779 if new_text not in seen:
777 780 yield c
778 781 seen.add(new_text)
779 782
780 783
781 784 def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
782 785 """
783 786 Rectify a set of completions to all have the same ``start`` and ``end``
784 787
785 788 .. warning::
786 789
787 790 Unstable
788 791
789 792 This function is unstable, API may change without warning.
790 793 It will also raise unless use in proper context manager.
791 794
792 795 Parameters
793 796 ----------
794 797 text : str
795 798 text that should be completed.
796 799 completions : Iterator[Completion]
797 800 iterator over the completions to rectify
798 801 _debug : bool
799 802 Log failed completion
800 803
801 804 Notes
802 805 -----
803 806 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
804 807 the Jupyter Protocol requires them to behave like so. This will readjust
805 808 the completion to have the same ``start`` and ``end`` by padding both
806 809 extremities with surrounding text.
807 810
808 811 During stabilisation should support a ``_debug`` option to log which
809 812 completion are return by the IPython completer and not found in Jedi in
810 813 order to make upstream bug report.
811 814 """
812 815 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
813 816 "It may change without warnings. "
814 817 "Use in corresponding context manager.",
815 818 category=ProvisionalCompleterWarning, stacklevel=2)
816 819
817 820 completions = list(completions)
818 821 if not completions:
819 822 return
820 823 starts = (c.start for c in completions)
821 824 ends = (c.end for c in completions)
822 825
823 826 new_start = min(starts)
824 827 new_end = max(ends)
825 828
826 829 seen_jedi = set()
827 830 seen_python_matches = set()
828 831 for c in completions:
829 832 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
830 833 if c._origin == 'jedi':
831 834 seen_jedi.add(new_text)
832 835 elif c._origin == 'IPCompleter.python_matches':
833 836 seen_python_matches.add(new_text)
834 837 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
835 838 diff = seen_python_matches.difference(seen_jedi)
836 839 if diff and _debug:
837 840 print('IPython.python matches have extras:', diff)
838 841
839 842
840 843 if sys.platform == 'win32':
841 844 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
842 845 else:
843 846 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
844 847
845 848 GREEDY_DELIMS = ' =\r\n'
846 849
847 850
848 851 class CompletionSplitter(object):
849 852 """An object to split an input line in a manner similar to readline.
850 853
851 854 By having our own implementation, we can expose readline-like completion in
852 855 a uniform manner to all frontends. This object only needs to be given the
853 856 line of text to be split and the cursor position on said line, and it
854 857 returns the 'word' to be completed on at the cursor after splitting the
855 858 entire line.
856 859
857 860 What characters are used as splitting delimiters can be controlled by
858 861 setting the ``delims`` attribute (this is a property that internally
859 862 automatically builds the necessary regular expression)"""
860 863
861 864 # Private interface
862 865
863 866 # A string of delimiter characters. The default value makes sense for
864 867 # IPython's most typical usage patterns.
865 868 _delims = DELIMS
866 869
867 870 # The expression (a normal string) to be compiled into a regular expression
868 871 # for actual splitting. We store it as an attribute mostly for ease of
869 872 # debugging, since this type of code can be so tricky to debug.
870 873 _delim_expr = None
871 874
872 875 # The regular expression that does the actual splitting
873 876 _delim_re = None
874 877
875 878 def __init__(self, delims=None):
876 879 delims = CompletionSplitter._delims if delims is None else delims
877 880 self.delims = delims
878 881
879 882 @property
880 883 def delims(self):
881 884 """Return the string of delimiter characters."""
882 885 return self._delims
883 886
884 887 @delims.setter
885 888 def delims(self, delims):
886 889 """Set the delimiters for line splitting."""
887 890 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
888 891 self._delim_re = re.compile(expr)
889 892 self._delims = delims
890 893 self._delim_expr = expr
891 894
892 895 def split_line(self, line, cursor_pos=None):
893 896 """Split a line of text with a cursor at the given position.
894 897 """
895 898 l = line if cursor_pos is None else line[:cursor_pos]
896 899 return self._delim_re.split(l)[-1]
897 900
898 901
899 902
900 903 class Completer(Configurable):
901 904
902 905 greedy = Bool(False,
903 906 help="""Activate greedy completion
904 907 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
905 908
906 909 This will enable completion on elements of lists, results of function calls, etc.,
907 910 but can be unsafe because the code is actually evaluated on TAB.
908 911 """,
909 912 ).tag(config=True)
910 913
911 914 use_jedi = Bool(default_value=JEDI_INSTALLED,
912 915 help="Experimental: Use Jedi to generate autocompletions. "
913 916 "Default to True if jedi is installed.").tag(config=True)
914 917
915 918 jedi_compute_type_timeout = Int(default_value=400,
916 919 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
917 920 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
918 921 performance by preventing jedi to build its cache.
919 922 """).tag(config=True)
920 923
921 924 debug = Bool(default_value=False,
922 925 help='Enable debug for the Completer. Mostly print extra '
923 926 'information for experimental jedi integration.')\
924 927 .tag(config=True)
925 928
926 929 backslash_combining_completions = Bool(True,
927 930 help="Enable unicode completions, e.g. \\alpha<tab> . "
928 931 "Includes completion of latex commands, unicode names, and expanding "
929 932 "unicode characters back to latex commands.").tag(config=True)
930 933
931 934 def __init__(self, namespace=None, global_namespace=None, **kwargs):
932 935 """Create a new completer for the command line.
933 936
934 937 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
935 938
936 939 If unspecified, the default namespace where completions are performed
937 940 is __main__ (technically, __main__.__dict__). Namespaces should be
938 941 given as dictionaries.
939 942
940 943 An optional second namespace can be given. This allows the completer
941 944 to handle cases where both the local and global scopes need to be
942 945 distinguished.
943 946 """
944 947
945 948 # Don't bind to namespace quite yet, but flag whether the user wants a
946 949 # specific namespace or to use __main__.__dict__. This will allow us
947 950 # to bind to __main__.__dict__ at completion time, not now.
948 951 if namespace is None:
949 952 self.use_main_ns = True
950 953 else:
951 954 self.use_main_ns = False
952 955 self.namespace = namespace
953 956
954 957 # The global namespace, if given, can be bound directly
955 958 if global_namespace is None:
956 959 self.global_namespace = {}
957 960 else:
958 961 self.global_namespace = global_namespace
959 962
960 963 self.custom_matchers = []
961 964
962 965 super(Completer, self).__init__(**kwargs)
963 966
964 967 def complete(self, text, state):
965 968 """Return the next possible completion for 'text'.
966 969
967 970 This is called successively with state == 0, 1, 2, ... until it
968 971 returns None. The completion should begin with 'text'.
969 972
970 973 """
971 974 if self.use_main_ns:
972 975 self.namespace = __main__.__dict__
973 976
974 977 if state == 0:
975 978 if "." in text:
976 979 self.matches = self.attr_matches(text)
977 980 else:
978 981 self.matches = self.global_matches(text)
979 982 try:
980 983 return self.matches[state]
981 984 except IndexError:
982 985 return None
983 986
984 987 def global_matches(self, text):
985 988 """Compute matches when text is a simple name.
986 989
987 990 Return a list of all keywords, built-in functions and names currently
988 991 defined in self.namespace or self.global_namespace that match.
989 992
990 993 """
991 994 matches = []
992 995 match_append = matches.append
993 996 n = len(text)
994 997 for lst in [
995 998 keyword.kwlist,
996 999 builtin_mod.__dict__.keys(),
997 1000 list(self.namespace.keys()),
998 1001 list(self.global_namespace.keys()),
999 1002 ]:
1000 1003 for word in lst:
1001 1004 if word[:n] == text and word != "__builtins__":
1002 1005 match_append(word)
1003 1006
1004 1007 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
1005 1008 for lst in [list(self.namespace.keys()), list(self.global_namespace.keys())]:
1006 1009 shortened = {
1007 1010 "_".join([sub[0] for sub in word.split("_")]): word
1008 1011 for word in lst
1009 1012 if snake_case_re.match(word)
1010 1013 }
1011 1014 for word in shortened.keys():
1012 1015 if word[:n] == text and word != "__builtins__":
1013 1016 match_append(shortened[word])
1014 1017 return matches
1015 1018
1016 1019 def attr_matches(self, text):
1017 1020 """Compute matches when text contains a dot.
1018 1021
1019 1022 Assuming the text is of the form NAME.NAME....[NAME], and is
1020 1023 evaluatable in self.namespace or self.global_namespace, it will be
1021 1024 evaluated and its attributes (as revealed by dir()) are used as
1022 1025 possible completions. (For class instances, class members are
1023 1026 also considered.)
1024 1027
1025 1028 WARNING: this can still invoke arbitrary C code, if an object
1026 1029 with a __getattr__ hook is evaluated.
1027 1030
1028 1031 """
1029 1032
1030 1033 # Another option, seems to work great. Catches things like ''.<tab>
1031 1034 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
1032 1035
1033 1036 if m:
1034 1037 expr, attr = m.group(1, 3)
1035 1038 elif self.greedy:
1036 1039 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
1037 1040 if not m2:
1038 1041 return []
1039 1042 expr, attr = m2.group(1,2)
1040 1043 else:
1041 1044 return []
1042 1045
1043 1046 try:
1044 1047 obj = eval(expr, self.namespace)
1045 1048 except:
1046 1049 try:
1047 1050 obj = eval(expr, self.global_namespace)
1048 1051 except:
1049 1052 return []
1050 1053
1051 1054 if self.limit_to__all__ and hasattr(obj, '__all__'):
1052 1055 words = get__all__entries(obj)
1053 1056 else:
1054 1057 words = dir2(obj)
1055 1058
1056 1059 try:
1057 1060 words = generics.complete_object(obj, words)
1058 1061 except TryNext:
1059 1062 pass
1060 1063 except AssertionError:
1061 1064 raise
1062 1065 except Exception:
1063 1066 # Silence errors from completion function
1064 1067 #raise # dbg
1065 1068 pass
1066 1069 # Build match list to return
1067 1070 n = len(attr)
1068 1071 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
1069 1072
1070 1073
1071 1074 def get__all__entries(obj):
1072 1075 """returns the strings in the __all__ attribute"""
1073 1076 try:
1074 1077 words = getattr(obj, '__all__')
1075 1078 except:
1076 1079 return []
1077 1080
1078 1081 return [w for w in words if isinstance(w, str)]
1079 1082
1080 1083
1081 1084 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
1082 1085 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
1083 1086 """Used by dict_key_matches, matching the prefix to a list of keys
1084 1087
1085 1088 Parameters
1086 1089 ----------
1087 1090 keys
1088 1091 list of keys in dictionary currently being completed.
1089 1092 prefix
1090 1093 Part of the text already typed by the user. E.g. `mydict[b'fo`
1091 1094 delims
1092 1095 String of delimiters to consider when finding the current key.
1093 1096 extra_prefix : optional
1094 1097 Part of the text already typed in multi-key index cases. E.g. for
1095 1098 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
1096 1099
1097 1100 Returns
1098 1101 -------
1099 1102 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
1100 1103 ``quote`` being the quote that need to be used to close current string.
1101 1104 ``token_start`` the position where the replacement should start occurring,
1102 1105 ``matches`` a list of replacement/completion
1103 1106
1104 1107 """
1105 1108 prefix_tuple = extra_prefix if extra_prefix else ()
1106 1109 Nprefix = len(prefix_tuple)
1107 1110 def filter_prefix_tuple(key):
1108 1111 # Reject too short keys
1109 1112 if len(key) <= Nprefix:
1110 1113 return False
1111 1114 # Reject keys with non str/bytes in it
1112 1115 for k in key:
1113 1116 if not isinstance(k, (str, bytes)):
1114 1117 return False
1115 1118 # Reject keys that do not match the prefix
1116 1119 for k, pt in zip(key, prefix_tuple):
1117 1120 if k != pt:
1118 1121 return False
1119 1122 # All checks passed!
1120 1123 return True
1121 1124
1122 1125 filtered_keys:List[Union[str,bytes]] = []
1123 1126 def _add_to_filtered_keys(key):
1124 1127 if isinstance(key, (str, bytes)):
1125 1128 filtered_keys.append(key)
1126 1129
1127 1130 for k in keys:
1128 1131 if isinstance(k, tuple):
1129 1132 if filter_prefix_tuple(k):
1130 1133 _add_to_filtered_keys(k[Nprefix])
1131 1134 else:
1132 1135 _add_to_filtered_keys(k)
1133 1136
1134 1137 if not prefix:
1135 1138 return '', 0, [repr(k) for k in filtered_keys]
1136 1139 quote_match = re.search('["\']', prefix)
1137 1140 assert quote_match is not None # silence mypy
1138 1141 quote = quote_match.group()
1139 1142 try:
1140 1143 prefix_str = eval(prefix + quote, {})
1141 1144 except Exception:
1142 1145 return '', 0, []
1143 1146
1144 1147 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
1145 1148 token_match = re.search(pattern, prefix, re.UNICODE)
1146 1149 assert token_match is not None # silence mypy
1147 1150 token_start = token_match.start()
1148 1151 token_prefix = token_match.group()
1149 1152
1150 1153 matched:List[str] = []
1151 1154 for key in filtered_keys:
1152 1155 try:
1153 1156 if not key.startswith(prefix_str):
1154 1157 continue
1155 1158 except (AttributeError, TypeError, UnicodeError):
1156 1159 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
1157 1160 continue
1158 1161
1159 1162 # reformat remainder of key to begin with prefix
1160 1163 rem = key[len(prefix_str):]
1161 1164 # force repr wrapped in '
1162 1165 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
1163 1166 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
1164 1167 if quote == '"':
1165 1168 # The entered prefix is quoted with ",
1166 1169 # but the match is quoted with '.
1167 1170 # A contained " hence needs escaping for comparison:
1168 1171 rem_repr = rem_repr.replace('"', '\\"')
1169 1172
1170 1173 # then reinsert prefix from start of token
1171 1174 matched.append('%s%s' % (token_prefix, rem_repr))
1172 1175 return quote, token_start, matched
1173 1176
1174 1177
1175 1178 def cursor_to_position(text:str, line:int, column:int)->int:
1176 1179 """
1177 1180 Convert the (line,column) position of the cursor in text to an offset in a
1178 1181 string.
1179 1182
1180 1183 Parameters
1181 1184 ----------
1182 1185 text : str
1183 1186 The text in which to calculate the cursor offset
1184 1187 line : int
1185 1188 Line of the cursor; 0-indexed
1186 1189 column : int
1187 1190 Column of the cursor 0-indexed
1188 1191
1189 1192 Returns
1190 1193 -------
1191 1194 Position of the cursor in ``text``, 0-indexed.
1192 1195
1193 1196 See Also
1194 1197 --------
1195 1198 position_to_cursor : reciprocal of this function
1196 1199
1197 1200 """
1198 1201 lines = text.split('\n')
1199 1202 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
1200 1203
1201 1204 return sum(len(l) + 1 for l in lines[:line]) + column
1202 1205
1203 1206 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
1204 1207 """
1205 1208 Convert the position of the cursor in text (0 indexed) to a line
1206 1209 number(0-indexed) and a column number (0-indexed) pair
1207 1210
1208 1211 Position should be a valid position in ``text``.
1209 1212
1210 1213 Parameters
1211 1214 ----------
1212 1215 text : str
1213 1216 The text in which to calculate the cursor offset
1214 1217 offset : int
1215 1218 Position of the cursor in ``text``, 0-indexed.
1216 1219
1217 1220 Returns
1218 1221 -------
1219 1222 (line, column) : (int, int)
1220 1223 Line of the cursor; 0-indexed, column of the cursor 0-indexed
1221 1224
1222 1225 See Also
1223 1226 --------
1224 1227 cursor_to_position : reciprocal of this function
1225 1228
1226 1229 """
1227 1230
1228 1231 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
1229 1232
1230 1233 before = text[:offset]
1231 1234 blines = before.split('\n') # ! splitnes trim trailing \n
1232 1235 line = before.count('\n')
1233 1236 col = len(blines[-1])
1234 1237 return line, col
1235 1238
1236 1239
1237 1240 def _safe_isinstance(obj, module, class_name):
1238 1241 """Checks if obj is an instance of module.class_name if loaded
1239 1242 """
1240 1243 return (module in sys.modules and
1241 1244 isinstance(obj, getattr(import_module(module), class_name)))
1242 1245
1243 1246
1244 1247 @context_matcher()
1245 1248 def back_unicode_name_matcher(context: CompletionContext):
1246 1249 """Match Unicode characters back to Unicode name
1247 1250
1248 1251 Same as :any:`back_unicode_name_matches`, but adopted to new Matcher API.
1249 1252 """
1250 1253 fragment, matches = back_unicode_name_matches(context.text_until_cursor)
1251 1254 return _convert_matcher_v1_result_to_v2(
1252 1255 matches, type="unicode", fragment=fragment, suppress_if_matches=True
1253 1256 )
1254 1257
1255 1258
1256 1259 def back_unicode_name_matches(text: str) -> Tuple[str, Sequence[str]]:
1257 1260 """Match Unicode characters back to Unicode name
1258 1261
1259 1262 This does ``β˜ƒ`` -> ``\\snowman``
1260 1263
1261 1264 Note that snowman is not a valid python3 combining character but will be expanded.
1262 1265 Though it will not recombine back to the snowman character by the completion machinery.
1263 1266
1264 1267 This will not either back-complete standard sequences like \\n, \\b ...
1265 1268
1266 1269 .. deprecated:: 8.6
1267 1270 You can use :meth:`back_unicode_name_matcher` instead.
1268 1271
1269 1272 Returns
1270 1273 =======
1271 1274
1272 1275 Return a tuple with two elements:
1273 1276
1274 1277 - The Unicode character that was matched (preceded with a backslash), or
1275 1278 empty string,
1276 1279 - a sequence (of 1), name for the match Unicode character, preceded by
1277 1280 backslash, or empty if no match.
1278 1281 """
1279 1282 if len(text)<2:
1280 1283 return '', ()
1281 1284 maybe_slash = text[-2]
1282 1285 if maybe_slash != '\\':
1283 1286 return '', ()
1284 1287
1285 1288 char = text[-1]
1286 1289 # no expand on quote for completion in strings.
1287 1290 # nor backcomplete standard ascii keys
1288 1291 if char in string.ascii_letters or char in ('"',"'"):
1289 1292 return '', ()
1290 1293 try :
1291 1294 unic = unicodedata.name(char)
1292 1295 return '\\'+char,('\\'+unic,)
1293 1296 except KeyError:
1294 1297 pass
1295 1298 return '', ()
1296 1299
1297 1300
1298 1301 @context_matcher()
1299 1302 def back_latex_name_matcher(context: CompletionContext):
1300 1303 """Match latex characters back to unicode name
1301 1304
1302 1305 Same as :any:`back_latex_name_matches`, but adopted to new Matcher API.
1303 1306 """
1304 1307 fragment, matches = back_latex_name_matches(context.text_until_cursor)
1305 1308 return _convert_matcher_v1_result_to_v2(
1306 1309 matches, type="latex", fragment=fragment, suppress_if_matches=True
1307 1310 )
1308 1311
1309 1312
1310 1313 def back_latex_name_matches(text: str) -> Tuple[str, Sequence[str]]:
1311 1314 """Match latex characters back to unicode name
1312 1315
1313 1316 This does ``\\β„΅`` -> ``\\aleph``
1314 1317
1315 1318 .. deprecated:: 8.6
1316 1319 You can use :meth:`back_latex_name_matcher` instead.
1317 1320 """
1318 1321 if len(text)<2:
1319 1322 return '', ()
1320 1323 maybe_slash = text[-2]
1321 1324 if maybe_slash != '\\':
1322 1325 return '', ()
1323 1326
1324 1327
1325 1328 char = text[-1]
1326 1329 # no expand on quote for completion in strings.
1327 1330 # nor backcomplete standard ascii keys
1328 1331 if char in string.ascii_letters or char in ('"',"'"):
1329 1332 return '', ()
1330 1333 try :
1331 1334 latex = reverse_latex_symbol[char]
1332 1335 # '\\' replace the \ as well
1333 1336 return '\\'+char,[latex]
1334 1337 except KeyError:
1335 1338 pass
1336 1339 return '', ()
1337 1340
1338 1341
1339 1342 def _formatparamchildren(parameter) -> str:
1340 1343 """
1341 1344 Get parameter name and value from Jedi Private API
1342 1345
1343 1346 Jedi does not expose a simple way to get `param=value` from its API.
1344 1347
1345 1348 Parameters
1346 1349 ----------
1347 1350 parameter
1348 1351 Jedi's function `Param`
1349 1352
1350 1353 Returns
1351 1354 -------
1352 1355 A string like 'a', 'b=1', '*args', '**kwargs'
1353 1356
1354 1357 """
1355 1358 description = parameter.description
1356 1359 if not description.startswith('param '):
1357 1360 raise ValueError('Jedi function parameter description have change format.'
1358 1361 'Expected "param ...", found %r".' % description)
1359 1362 return description[6:]
1360 1363
1361 1364 def _make_signature(completion)-> str:
1362 1365 """
1363 1366 Make the signature from a jedi completion
1364 1367
1365 1368 Parameters
1366 1369 ----------
1367 1370 completion : jedi.Completion
1368 1371 object does not complete a function type
1369 1372
1370 1373 Returns
1371 1374 -------
1372 1375 a string consisting of the function signature, with the parenthesis but
1373 1376 without the function name. example:
1374 1377 `(a, *args, b=1, **kwargs)`
1375 1378
1376 1379 """
1377 1380
1378 1381 # it looks like this might work on jedi 0.17
1379 1382 if hasattr(completion, 'get_signatures'):
1380 1383 signatures = completion.get_signatures()
1381 1384 if not signatures:
1382 1385 return '(?)'
1383 1386
1384 1387 c0 = completion.get_signatures()[0]
1385 1388 return '('+c0.to_string().split('(', maxsplit=1)[1]
1386 1389
1387 1390 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1388 1391 for p in signature.defined_names()) if f])
1389 1392
1390 1393
1391 1394 _CompleteResult = Dict[str, MatcherResult]
1392 1395
1393 1396
1394 1397 def _convert_matcher_v1_result_to_v2(
1395 1398 matches: Sequence[str],
1396 1399 type: str,
1397 1400 fragment: str = None,
1398 1401 suppress_if_matches: bool = False,
1399 1402 ) -> SimpleMatcherResult:
1400 1403 """Utility to help with transition"""
1401 1404 result = {
1402 1405 "completions": [SimpleCompletion(text=match, type=type) for match in matches],
1403 1406 "suppress": (True if matches else False) if suppress_if_matches else False,
1404 1407 }
1405 1408 if fragment is not None:
1406 1409 result["matched_fragment"] = fragment
1407 1410 return result
1408 1411
1409 1412
1410 1413 class IPCompleter(Completer):
1411 1414 """Extension of the completer class with IPython-specific features"""
1412 1415
1413 1416 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1414 1417
1415 1418 @observe('greedy')
1416 1419 def _greedy_changed(self, change):
1417 1420 """update the splitter and readline delims when greedy is changed"""
1418 1421 if change['new']:
1419 1422 self.splitter.delims = GREEDY_DELIMS
1420 1423 else:
1421 1424 self.splitter.delims = DELIMS
1422 1425
1423 1426 dict_keys_only = Bool(
1424 1427 False,
1425 1428 help="""
1426 1429 Whether to show dict key matches only.
1427 1430
1428 1431 (disables all matchers except for `IPCompleter.dict_key_matcher`).
1429 1432 """,
1430 1433 )
1431 1434
1432 1435 suppress_competing_matchers = UnionTrait(
1433 1436 [Bool(allow_none=True), DictTrait(Bool(None, allow_none=True))],
1434 1437 default_value=None,
1435 1438 help="""
1436 1439 Whether to suppress completions from other *Matchers*.
1437 1440
1438 1441 When set to ``None`` (default) the matchers will attempt to auto-detect
1439 1442 whether suppression of other matchers is desirable. For example, at
1440 1443 the beginning of a line followed by `%` we expect a magic completion
1441 1444 to be the only applicable option, and after ``my_dict['`` we usually
1442 1445 expect a completion with an existing dictionary key.
1443 1446
1444 1447 If you want to disable this heuristic and see completions from all matchers,
1445 1448 set ``IPCompleter.suppress_competing_matchers = False``.
1446 1449 To disable the heuristic for specific matchers provide a dictionary mapping:
1447 1450 ``IPCompleter.suppress_competing_matchers = {'IPCompleter.dict_key_matcher': False}``.
1448 1451
1449 1452 Set ``IPCompleter.suppress_competing_matchers = True`` to limit
1450 1453 completions to the set of matchers with the highest priority;
1451 1454 this is equivalent to ``IPCompleter.merge_completions`` and
1452 1455 can be beneficial for performance, but will sometimes omit relevant
1453 1456 candidates from matchers further down the priority list.
1454 1457 """,
1455 1458 ).tag(config=True)
1456 1459
1457 1460 merge_completions = Bool(
1458 1461 True,
1459 1462 help="""Whether to merge completion results into a single list
1460 1463
1461 1464 If False, only the completion results from the first non-empty
1462 1465 completer will be returned.
1463
1466
1464 1467 As of version 8.6.0, setting the value to ``False`` is an alias for:
1465 1468 ``IPCompleter.suppress_competing_matchers = True.``.
1466 1469 """,
1467 1470 ).tag(config=True)
1468 1471
1469 1472 disable_matchers = ListTrait(
1470 Unicode(), help="""List of matchers to disable."""
1473 Unicode(),
1474 help="""List of matchers to disable.
1475
1476 The list should contain matcher identifiers (see :any:`completion_matcher`).
1477 """,
1471 1478 ).tag(config=True)
1472 1479
1473 1480 omit__names = Enum(
1474 1481 (0, 1, 2),
1475 1482 default_value=2,
1476 1483 help="""Instruct the completer to omit private method names
1477 1484
1478 1485 Specifically, when completing on ``object.<tab>``.
1479 1486
1480 1487 When 2 [default]: all names that start with '_' will be excluded.
1481 1488
1482 1489 When 1: all 'magic' names (``__foo__``) will be excluded.
1483 1490
1484 1491 When 0: nothing will be excluded.
1485 1492 """
1486 1493 ).tag(config=True)
1487 1494 limit_to__all__ = Bool(False,
1488 1495 help="""
1489 1496 DEPRECATED as of version 5.0.
1490 1497
1491 1498 Instruct the completer to use __all__ for the completion
1492 1499
1493 1500 Specifically, when completing on ``object.<tab>``.
1494 1501
1495 1502 When True: only those names in obj.__all__ will be included.
1496 1503
1497 1504 When False [default]: the __all__ attribute is ignored
1498 1505 """,
1499 1506 ).tag(config=True)
1500 1507
1501 1508 profile_completions = Bool(
1502 1509 default_value=False,
1503 1510 help="If True, emit profiling data for completion subsystem using cProfile."
1504 1511 ).tag(config=True)
1505 1512
1506 1513 profiler_output_dir = Unicode(
1507 1514 default_value=".completion_profiles",
1508 1515 help="Template for path at which to output profile data for completions."
1509 1516 ).tag(config=True)
1510 1517
1511 1518 @observe('limit_to__all__')
1512 1519 def _limit_to_all_changed(self, change):
1513 1520 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1514 1521 'value has been deprecated since IPython 5.0, will be made to have '
1515 1522 'no effects and then removed in future version of IPython.',
1516 1523 UserWarning)
1517 1524
1518 1525 def __init__(
1519 1526 self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
1520 1527 ):
1521 1528 """IPCompleter() -> completer
1522 1529
1523 1530 Return a completer object.
1524 1531
1525 1532 Parameters
1526 1533 ----------
1527 1534 shell
1528 1535 a pointer to the ipython shell itself. This is needed
1529 1536 because this completer knows about magic functions, and those can
1530 1537 only be accessed via the ipython instance.
1531 1538 namespace : dict, optional
1532 1539 an optional dict where completions are performed.
1533 1540 global_namespace : dict, optional
1534 1541 secondary optional dict for completions, to
1535 1542 handle cases (such as IPython embedded inside functions) where
1536 1543 both Python scopes are visible.
1537 1544 config : Config
1538 1545 traitlet's config object
1539 1546 **kwargs
1540 1547 passed to super class unmodified.
1541 1548 """
1542 1549
1543 1550 self.magic_escape = ESC_MAGIC
1544 1551 self.splitter = CompletionSplitter()
1545 1552
1546 1553 # _greedy_changed() depends on splitter and readline being defined:
1547 1554 super().__init__(
1548 1555 namespace=namespace,
1549 1556 global_namespace=global_namespace,
1550 1557 config=config,
1551 1558 **kwargs,
1552 1559 )
1553 1560
1554 1561 # List where completion matches will be stored
1555 1562 self.matches = []
1556 1563 self.shell = shell
1557 1564 # Regexp to split filenames with spaces in them
1558 1565 self.space_name_re = re.compile(r'([^\\] )')
1559 1566 # Hold a local ref. to glob.glob for speed
1560 1567 self.glob = glob.glob
1561 1568
1562 1569 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1563 1570 # buffers, to avoid completion problems.
1564 1571 term = os.environ.get('TERM','xterm')
1565 1572 self.dumb_terminal = term in ['dumb','emacs']
1566 1573
1567 1574 # Special handling of backslashes needed in win32 platforms
1568 1575 if sys.platform == "win32":
1569 1576 self.clean_glob = self._clean_glob_win32
1570 1577 else:
1571 1578 self.clean_glob = self._clean_glob
1572 1579
1573 1580 #regexp to parse docstring for function signature
1574 1581 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1575 1582 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1576 1583 #use this if positional argument name is also needed
1577 1584 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1578 1585
1579 1586 self.magic_arg_matchers = [
1580 1587 self.magic_config_matcher,
1581 1588 self.magic_color_matcher,
1582 1589 ]
1583 1590
1584 1591 # This is set externally by InteractiveShell
1585 1592 self.custom_completers = None
1586 1593
1587 1594 # This is a list of names of unicode characters that can be completed
1588 1595 # into their corresponding unicode value. The list is large, so we
1589 1596 # lazily initialize it on first use. Consuming code should access this
1590 1597 # attribute through the `@unicode_names` property.
1591 1598 self._unicode_names = None
1592 1599
1593 1600 self._backslash_combining_matchers = [
1594 1601 self.latex_name_matcher,
1595 1602 self.unicode_name_matcher,
1596 1603 back_latex_name_matcher,
1597 1604 back_unicode_name_matcher,
1598 1605 self.fwd_unicode_matcher,
1599 1606 ]
1600 1607
1601 1608 if not self.backslash_combining_completions:
1602 1609 for matcher in self._backslash_combining_matchers:
1603 1610 self.disable_matchers.append(matcher.matcher_identifier)
1604 1611
1605 1612 if not self.merge_completions:
1606 1613 self.suppress_competing_matchers = True
1607 1614
1608 1615 @property
1609 1616 def matchers(self) -> List[Matcher]:
1610 1617 """All active matcher routines for completion"""
1611 1618 if self.dict_keys_only:
1612 1619 return [self.dict_key_matcher]
1613 1620
1614 1621 if self.use_jedi:
1615 1622 return [
1616 1623 *self.custom_matchers,
1617 1624 *self._backslash_combining_matchers,
1618 1625 *self.magic_arg_matchers,
1619 1626 self.custom_completer_matcher,
1620 1627 self.magic_matcher,
1621 1628 self._jedi_matcher,
1622 1629 self.dict_key_matcher,
1623 1630 self.file_matcher,
1624 1631 ]
1625 1632 else:
1626 1633 return [
1627 1634 *self.custom_matchers,
1628 1635 *self._backslash_combining_matchers,
1629 1636 *self.magic_arg_matchers,
1630 1637 self.custom_completer_matcher,
1631 1638 self.dict_key_matcher,
1632 1639 # TODO: convert python_matches to v2 API
1633 1640 self.magic_matcher,
1634 1641 self.python_matches,
1635 1642 self.file_matcher,
1636 1643 self.python_func_kw_matcher,
1637 1644 ]
1638 1645
1639 1646 def all_completions(self, text:str) -> List[str]:
1640 1647 """
1641 1648 Wrapper around the completion methods for the benefit of emacs.
1642 1649 """
1643 1650 prefix = text.rpartition('.')[0]
1644 1651 with provisionalcompleter():
1645 1652 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1646 1653 for c in self.completions(text, len(text))]
1647 1654
1648 1655 return self.complete(text)[1]
1649 1656
1650 1657 def _clean_glob(self, text:str):
1651 1658 return self.glob("%s*" % text)
1652 1659
1653 1660 def _clean_glob_win32(self, text:str):
1654 1661 return [f.replace("\\","/")
1655 1662 for f in self.glob("%s*" % text)]
1656 1663
1657 1664 @context_matcher()
1658 1665 def file_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
1659 1666 """Same as :any:`file_matches`, but adopted to new Matcher API."""
1660 1667 matches = self.file_matches(context.token)
1661 1668 # TODO: add a heuristic for suppressing (e.g. if it has OS-specific delimiter,
1662 1669 # starts with `/home/`, `C:\`, etc)
1663 1670 return _convert_matcher_v1_result_to_v2(matches, type="path")
1664 1671
1665 1672 def file_matches(self, text: str) -> List[str]:
1666 1673 """Match filenames, expanding ~USER type strings.
1667 1674
1668 1675 Most of the seemingly convoluted logic in this completer is an
1669 1676 attempt to handle filenames with spaces in them. And yet it's not
1670 1677 quite perfect, because Python's readline doesn't expose all of the
1671 1678 GNU readline details needed for this to be done correctly.
1672 1679
1673 1680 For a filename with a space in it, the printed completions will be
1674 1681 only the parts after what's already been typed (instead of the
1675 1682 full completions, as is normally done). I don't think with the
1676 1683 current (as of Python 2.3) Python readline it's possible to do
1677 1684 better.
1678 1685
1679 1686 .. deprecated:: 8.6
1680 1687 You can use :meth:`file_matcher` instead.
1681 1688 """
1682 1689
1683 1690 # chars that require escaping with backslash - i.e. chars
1684 1691 # that readline treats incorrectly as delimiters, but we
1685 1692 # don't want to treat as delimiters in filename matching
1686 1693 # when escaped with backslash
1687 1694 if text.startswith('!'):
1688 1695 text = text[1:]
1689 1696 text_prefix = u'!'
1690 1697 else:
1691 1698 text_prefix = u''
1692 1699
1693 1700 text_until_cursor = self.text_until_cursor
1694 1701 # track strings with open quotes
1695 1702 open_quotes = has_open_quotes(text_until_cursor)
1696 1703
1697 1704 if '(' in text_until_cursor or '[' in text_until_cursor:
1698 1705 lsplit = text
1699 1706 else:
1700 1707 try:
1701 1708 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1702 1709 lsplit = arg_split(text_until_cursor)[-1]
1703 1710 except ValueError:
1704 1711 # typically an unmatched ", or backslash without escaped char.
1705 1712 if open_quotes:
1706 1713 lsplit = text_until_cursor.split(open_quotes)[-1]
1707 1714 else:
1708 1715 return []
1709 1716 except IndexError:
1710 1717 # tab pressed on empty line
1711 1718 lsplit = ""
1712 1719
1713 1720 if not open_quotes and lsplit != protect_filename(lsplit):
1714 1721 # if protectables are found, do matching on the whole escaped name
1715 1722 has_protectables = True
1716 1723 text0,text = text,lsplit
1717 1724 else:
1718 1725 has_protectables = False
1719 1726 text = os.path.expanduser(text)
1720 1727
1721 1728 if text == "":
1722 1729 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1723 1730
1724 1731 # Compute the matches from the filesystem
1725 1732 if sys.platform == 'win32':
1726 1733 m0 = self.clean_glob(text)
1727 1734 else:
1728 1735 m0 = self.clean_glob(text.replace('\\', ''))
1729 1736
1730 1737 if has_protectables:
1731 1738 # If we had protectables, we need to revert our changes to the
1732 1739 # beginning of filename so that we don't double-write the part
1733 1740 # of the filename we have so far
1734 1741 len_lsplit = len(lsplit)
1735 1742 matches = [text_prefix + text0 +
1736 1743 protect_filename(f[len_lsplit:]) for f in m0]
1737 1744 else:
1738 1745 if open_quotes:
1739 1746 # if we have a string with an open quote, we don't need to
1740 1747 # protect the names beyond the quote (and we _shouldn't_, as
1741 1748 # it would cause bugs when the filesystem call is made).
1742 1749 matches = m0 if sys.platform == "win32" else\
1743 1750 [protect_filename(f, open_quotes) for f in m0]
1744 1751 else:
1745 1752 matches = [text_prefix +
1746 1753 protect_filename(f) for f in m0]
1747 1754
1748 1755 # Mark directories in input list by appending '/' to their names.
1749 1756 return [x+'/' if os.path.isdir(x) else x for x in matches]
1750 1757
1751 1758 @context_matcher()
1752 1759 def magic_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
1753 1760 """Match magics."""
1754 1761 text = context.token
1755 1762 matches = self.magic_matches(text)
1756 1763 result = _convert_matcher_v1_result_to_v2(matches, type="magic")
1757 1764 is_magic_prefix = len(text) > 0 and text[0] == "%"
1758 1765 result["suppress"] = is_magic_prefix and bool(result["completions"])
1759 1766 return result
1760 1767
1761 1768 def magic_matches(self, text: str):
1762 1769 """Match magics.
1763 1770
1764 1771 .. deprecated:: 8.6
1765 1772 You can use :meth:`magic_matcher` instead.
1766 1773 """
1767 1774 # Get all shell magics now rather than statically, so magics loaded at
1768 1775 # runtime show up too.
1769 1776 lsm = self.shell.magics_manager.lsmagic()
1770 1777 line_magics = lsm['line']
1771 1778 cell_magics = lsm['cell']
1772 1779 pre = self.magic_escape
1773 1780 pre2 = pre+pre
1774 1781
1775 1782 explicit_magic = text.startswith(pre)
1776 1783
1777 1784 # Completion logic:
1778 1785 # - user gives %%: only do cell magics
1779 1786 # - user gives %: do both line and cell magics
1780 1787 # - no prefix: do both
1781 1788 # In other words, line magics are skipped if the user gives %% explicitly
1782 1789 #
1783 1790 # We also exclude magics that match any currently visible names:
1784 1791 # https://github.com/ipython/ipython/issues/4877, unless the user has
1785 1792 # typed a %:
1786 1793 # https://github.com/ipython/ipython/issues/10754
1787 1794 bare_text = text.lstrip(pre)
1788 1795 global_matches = self.global_matches(bare_text)
1789 1796 if not explicit_magic:
1790 1797 def matches(magic):
1791 1798 """
1792 1799 Filter magics, in particular remove magics that match
1793 1800 a name present in global namespace.
1794 1801 """
1795 1802 return ( magic.startswith(bare_text) and
1796 1803 magic not in global_matches )
1797 1804 else:
1798 1805 def matches(magic):
1799 1806 return magic.startswith(bare_text)
1800 1807
1801 1808 comp = [ pre2+m for m in cell_magics if matches(m)]
1802 1809 if not text.startswith(pre2):
1803 1810 comp += [ pre+m for m in line_magics if matches(m)]
1804 1811
1805 1812 return comp
1806 1813
1807 1814 @context_matcher()
1808 1815 def magic_config_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
1809 1816 """Match class names and attributes for %config magic."""
1810 1817 # NOTE: uses `line_buffer` equivalent for compatibility
1811 1818 matches = self.magic_config_matches(context.line_with_cursor)
1812 1819 return _convert_matcher_v1_result_to_v2(matches, type="param")
1813 1820
1814 1821 def magic_config_matches(self, text: str) -> List[str]:
1815 1822 """Match class names and attributes for %config magic.
1816 1823
1817 1824 .. deprecated:: 8.6
1818 1825 You can use :meth:`magic_config_matcher` instead.
1819 1826 """
1820 1827 texts = text.strip().split()
1821 1828
1822 1829 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1823 1830 # get all configuration classes
1824 1831 classes = sorted(set([ c for c in self.shell.configurables
1825 1832 if c.__class__.class_traits(config=True)
1826 1833 ]), key=lambda x: x.__class__.__name__)
1827 1834 classnames = [ c.__class__.__name__ for c in classes ]
1828 1835
1829 1836 # return all classnames if config or %config is given
1830 1837 if len(texts) == 1:
1831 1838 return classnames
1832 1839
1833 1840 # match classname
1834 1841 classname_texts = texts[1].split('.')
1835 1842 classname = classname_texts[0]
1836 1843 classname_matches = [ c for c in classnames
1837 1844 if c.startswith(classname) ]
1838 1845
1839 1846 # return matched classes or the matched class with attributes
1840 1847 if texts[1].find('.') < 0:
1841 1848 return classname_matches
1842 1849 elif len(classname_matches) == 1 and \
1843 1850 classname_matches[0] == classname:
1844 1851 cls = classes[classnames.index(classname)].__class__
1845 1852 help = cls.class_get_help()
1846 1853 # strip leading '--' from cl-args:
1847 1854 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1848 1855 return [ attr.split('=')[0]
1849 1856 for attr in help.strip().splitlines()
1850 1857 if attr.startswith(texts[1]) ]
1851 1858 return []
1852 1859
1853 1860 @context_matcher()
1854 1861 def magic_color_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
1855 1862 """Match color schemes for %colors magic."""
1856 1863 # NOTE: uses `line_buffer` equivalent for compatibility
1857 1864 matches = self.magic_color_matches(context.line_with_cursor)
1858 1865 return _convert_matcher_v1_result_to_v2(matches, type="param")
1859 1866
1860 1867 def magic_color_matches(self, text: str) -> List[str]:
1861 1868 """Match color schemes for %colors magic.
1862 1869
1863 1870 .. deprecated:: 8.6
1864 1871 You can use :meth:`magic_color_matcher` instead.
1865 1872 """
1866 1873 texts = text.split()
1867 1874 if text.endswith(' '):
1868 1875 # .split() strips off the trailing whitespace. Add '' back
1869 1876 # so that: '%colors ' -> ['%colors', '']
1870 1877 texts.append('')
1871 1878
1872 1879 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1873 1880 prefix = texts[1]
1874 1881 return [ color for color in InspectColors.keys()
1875 1882 if color.startswith(prefix) ]
1876 1883 return []
1877 1884
1878 1885 @context_matcher(identifier="IPCompleter.jedi_matcher")
1879 1886 def _jedi_matcher(self, context: CompletionContext) -> _JediMatcherResult:
1880 1887 matches = self._jedi_matches(
1881 1888 cursor_column=context.cursor_position,
1882 1889 cursor_line=context.cursor_line,
1883 1890 text=context.full_text,
1884 1891 )
1885 1892 return {
1886 1893 "completions": matches,
1887 1894 # static analysis should not suppress other matchers
1888 1895 "suppress": False,
1889 1896 }
1890 1897
1891 1898 def _jedi_matches(
1892 1899 self, cursor_column: int, cursor_line: int, text: str
1893 1900 ) -> Iterable[_JediCompletionLike]:
1894 1901 """
1895 1902 Return a list of :any:`jedi.api.Completion`s object from a ``text`` and
1896 1903 cursor position.
1897 1904
1898 1905 Parameters
1899 1906 ----------
1900 1907 cursor_column : int
1901 1908 column position of the cursor in ``text``, 0-indexed.
1902 1909 cursor_line : int
1903 1910 line position of the cursor in ``text``, 0-indexed
1904 1911 text : str
1905 1912 text to complete
1906 1913
1907 1914 Notes
1908 1915 -----
1909 1916 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1910 1917 object containing a string with the Jedi debug information attached.
1911 1918
1912 1919 .. deprecated:: 8.6
1913 1920 You can use :meth:`_jedi_matcher` instead.
1914 1921 """
1915 1922 namespaces = [self.namespace]
1916 1923 if self.global_namespace is not None:
1917 1924 namespaces.append(self.global_namespace)
1918 1925
1919 1926 completion_filter = lambda x:x
1920 1927 offset = cursor_to_position(text, cursor_line, cursor_column)
1921 1928 # filter output if we are completing for object members
1922 1929 if offset:
1923 1930 pre = text[offset-1]
1924 1931 if pre == '.':
1925 1932 if self.omit__names == 2:
1926 1933 completion_filter = lambda c:not c.name.startswith('_')
1927 1934 elif self.omit__names == 1:
1928 1935 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1929 1936 elif self.omit__names == 0:
1930 1937 completion_filter = lambda x:x
1931 1938 else:
1932 1939 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1933 1940
1934 1941 interpreter = jedi.Interpreter(text[:offset], namespaces)
1935 1942 try_jedi = True
1936 1943
1937 1944 try:
1938 1945 # find the first token in the current tree -- if it is a ' or " then we are in a string
1939 1946 completing_string = False
1940 1947 try:
1941 1948 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1942 1949 except StopIteration:
1943 1950 pass
1944 1951 else:
1945 1952 # note the value may be ', ", or it may also be ''' or """, or
1946 1953 # in some cases, """what/you/typed..., but all of these are
1947 1954 # strings.
1948 1955 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1949 1956
1950 1957 # if we are in a string jedi is likely not the right candidate for
1951 1958 # now. Skip it.
1952 1959 try_jedi = not completing_string
1953 1960 except Exception as e:
1954 1961 # many of things can go wrong, we are using private API just don't crash.
1955 1962 if self.debug:
1956 1963 print("Error detecting if completing a non-finished string :", e, '|')
1957 1964
1958 1965 if not try_jedi:
1959 1966 return []
1960 1967 try:
1961 1968 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1962 1969 except Exception as e:
1963 1970 if self.debug:
1964 1971 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1965 1972 else:
1966 1973 return []
1967 1974
1968 1975 def python_matches(self, text: str) -> Iterable[str]:
1969 1976 """Match attributes or global python names"""
1970 1977 if "." in text:
1971 1978 try:
1972 1979 matches = self.attr_matches(text)
1973 1980 if text.endswith('.') and self.omit__names:
1974 1981 if self.omit__names == 1:
1975 1982 # true if txt is _not_ a __ name, false otherwise:
1976 1983 no__name = (lambda txt:
1977 1984 re.match(r'.*\.__.*?__',txt) is None)
1978 1985 else:
1979 1986 # true if txt is _not_ a _ name, false otherwise:
1980 1987 no__name = (lambda txt:
1981 1988 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1982 1989 matches = filter(no__name, matches)
1983 1990 except NameError:
1984 1991 # catches <undefined attributes>.<tab>
1985 1992 matches = []
1986 1993 else:
1987 1994 matches = self.global_matches(text)
1988 1995 return matches
1989 1996
1990 1997 def _default_arguments_from_docstring(self, doc):
1991 1998 """Parse the first line of docstring for call signature.
1992 1999
1993 2000 Docstring should be of the form 'min(iterable[, key=func])\n'.
1994 2001 It can also parse cython docstring of the form
1995 2002 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1996 2003 """
1997 2004 if doc is None:
1998 2005 return []
1999 2006
2000 2007 #care only the firstline
2001 2008 line = doc.lstrip().splitlines()[0]
2002 2009
2003 2010 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
2004 2011 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
2005 2012 sig = self.docstring_sig_re.search(line)
2006 2013 if sig is None:
2007 2014 return []
2008 2015 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
2009 2016 sig = sig.groups()[0].split(',')
2010 2017 ret = []
2011 2018 for s in sig:
2012 2019 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
2013 2020 ret += self.docstring_kwd_re.findall(s)
2014 2021 return ret
2015 2022
2016 2023 def _default_arguments(self, obj):
2017 2024 """Return the list of default arguments of obj if it is callable,
2018 2025 or empty list otherwise."""
2019 2026 call_obj = obj
2020 2027 ret = []
2021 2028 if inspect.isbuiltin(obj):
2022 2029 pass
2023 2030 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
2024 2031 if inspect.isclass(obj):
2025 2032 #for cython embedsignature=True the constructor docstring
2026 2033 #belongs to the object itself not __init__
2027 2034 ret += self._default_arguments_from_docstring(
2028 2035 getattr(obj, '__doc__', ''))
2029 2036 # for classes, check for __init__,__new__
2030 2037 call_obj = (getattr(obj, '__init__', None) or
2031 2038 getattr(obj, '__new__', None))
2032 2039 # for all others, check if they are __call__able
2033 2040 elif hasattr(obj, '__call__'):
2034 2041 call_obj = obj.__call__
2035 2042 ret += self._default_arguments_from_docstring(
2036 2043 getattr(call_obj, '__doc__', ''))
2037 2044
2038 2045 _keeps = (inspect.Parameter.KEYWORD_ONLY,
2039 2046 inspect.Parameter.POSITIONAL_OR_KEYWORD)
2040 2047
2041 2048 try:
2042 2049 sig = inspect.signature(obj)
2043 2050 ret.extend(k for k, v in sig.parameters.items() if
2044 2051 v.kind in _keeps)
2045 2052 except ValueError:
2046 2053 pass
2047 2054
2048 2055 return list(set(ret))
2049 2056
2050 2057 @context_matcher()
2051 2058 def python_func_kw_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2052 2059 """Match named parameters (kwargs) of the last open function."""
2053 2060 matches = self.python_func_kw_matches(context.token)
2054 2061 return _convert_matcher_v1_result_to_v2(matches, type="param")
2055 2062
2056 2063 def python_func_kw_matches(self, text):
2057 2064 """Match named parameters (kwargs) of the last open function.
2058 2065
2059 2066 .. deprecated:: 8.6
2060 2067 You can use :meth:`python_func_kw_matcher` instead.
2061 2068 """
2062 2069
2063 2070 if "." in text: # a parameter cannot be dotted
2064 2071 return []
2065 2072 try: regexp = self.__funcParamsRegex
2066 2073 except AttributeError:
2067 2074 regexp = self.__funcParamsRegex = re.compile(r'''
2068 2075 '.*?(?<!\\)' | # single quoted strings or
2069 2076 ".*?(?<!\\)" | # double quoted strings or
2070 2077 \w+ | # identifier
2071 2078 \S # other characters
2072 2079 ''', re.VERBOSE | re.DOTALL)
2073 2080 # 1. find the nearest identifier that comes before an unclosed
2074 2081 # parenthesis before the cursor
2075 2082 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
2076 2083 tokens = regexp.findall(self.text_until_cursor)
2077 2084 iterTokens = reversed(tokens); openPar = 0
2078 2085
2079 2086 for token in iterTokens:
2080 2087 if token == ')':
2081 2088 openPar -= 1
2082 2089 elif token == '(':
2083 2090 openPar += 1
2084 2091 if openPar > 0:
2085 2092 # found the last unclosed parenthesis
2086 2093 break
2087 2094 else:
2088 2095 return []
2089 2096 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
2090 2097 ids = []
2091 2098 isId = re.compile(r'\w+$').match
2092 2099
2093 2100 while True:
2094 2101 try:
2095 2102 ids.append(next(iterTokens))
2096 2103 if not isId(ids[-1]):
2097 2104 ids.pop(); break
2098 2105 if not next(iterTokens) == '.':
2099 2106 break
2100 2107 except StopIteration:
2101 2108 break
2102 2109
2103 2110 # Find all named arguments already assigned to, as to avoid suggesting
2104 2111 # them again
2105 2112 usedNamedArgs = set()
2106 2113 par_level = -1
2107 2114 for token, next_token in zip(tokens, tokens[1:]):
2108 2115 if token == '(':
2109 2116 par_level += 1
2110 2117 elif token == ')':
2111 2118 par_level -= 1
2112 2119
2113 2120 if par_level != 0:
2114 2121 continue
2115 2122
2116 2123 if next_token != '=':
2117 2124 continue
2118 2125
2119 2126 usedNamedArgs.add(token)
2120 2127
2121 2128 argMatches = []
2122 2129 try:
2123 2130 callableObj = '.'.join(ids[::-1])
2124 2131 namedArgs = self._default_arguments(eval(callableObj,
2125 2132 self.namespace))
2126 2133
2127 2134 # Remove used named arguments from the list, no need to show twice
2128 2135 for namedArg in set(namedArgs) - usedNamedArgs:
2129 2136 if namedArg.startswith(text):
2130 2137 argMatches.append("%s=" %namedArg)
2131 2138 except:
2132 2139 pass
2133 2140
2134 2141 return argMatches
2135 2142
2136 2143 @staticmethod
2137 2144 def _get_keys(obj: Any) -> List[Any]:
2138 2145 # Objects can define their own completions by defining an
2139 2146 # _ipy_key_completions_() method.
2140 2147 method = get_real_method(obj, '_ipython_key_completions_')
2141 2148 if method is not None:
2142 2149 return method()
2143 2150
2144 2151 # Special case some common in-memory dict-like types
2145 2152 if isinstance(obj, dict) or\
2146 2153 _safe_isinstance(obj, 'pandas', 'DataFrame'):
2147 2154 try:
2148 2155 return list(obj.keys())
2149 2156 except Exception:
2150 2157 return []
2151 2158 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
2152 2159 _safe_isinstance(obj, 'numpy', 'void'):
2153 2160 return obj.dtype.names or []
2154 2161 return []
2155 2162
2156 2163 @context_matcher()
2157 2164 def dict_key_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2158 2165 """Match string keys in a dictionary, after e.g. ``foo[``."""
2159 2166 matches = self.dict_key_matches(context.token)
2160 2167 return _convert_matcher_v1_result_to_v2(
2161 2168 matches, type="dict key", suppress_if_matches=True
2162 2169 )
2163 2170
2164 2171 def dict_key_matches(self, text: str) -> List[str]:
2165 2172 """Match string keys in a dictionary, after e.g. ``foo[``.
2166 2173
2167 2174 .. deprecated:: 8.6
2168 2175 You can use :meth:`dict_key_matcher` instead.
2169 2176 """
2170 2177
2171 2178 if self.__dict_key_regexps is not None:
2172 2179 regexps = self.__dict_key_regexps
2173 2180 else:
2174 2181 dict_key_re_fmt = r'''(?x)
2175 2182 ( # match dict-referring expression wrt greedy setting
2176 2183 %s
2177 2184 )
2178 2185 \[ # open bracket
2179 2186 \s* # and optional whitespace
2180 2187 # Capture any number of str-like objects (e.g. "a", "b", 'c')
2181 2188 ((?:[uUbB]? # string prefix (r not handled)
2182 2189 (?:
2183 2190 '(?:[^']|(?<!\\)\\')*'
2184 2191 |
2185 2192 "(?:[^"]|(?<!\\)\\")*"
2186 2193 )
2187 2194 \s*,\s*
2188 2195 )*)
2189 2196 ([uUbB]? # string prefix (r not handled)
2190 2197 (?: # unclosed string
2191 2198 '(?:[^']|(?<!\\)\\')*
2192 2199 |
2193 2200 "(?:[^"]|(?<!\\)\\")*
2194 2201 )
2195 2202 )?
2196 2203 $
2197 2204 '''
2198 2205 regexps = self.__dict_key_regexps = {
2199 2206 False: re.compile(dict_key_re_fmt % r'''
2200 2207 # identifiers separated by .
2201 2208 (?!\d)\w+
2202 2209 (?:\.(?!\d)\w+)*
2203 2210 '''),
2204 2211 True: re.compile(dict_key_re_fmt % '''
2205 2212 .+
2206 2213 ''')
2207 2214 }
2208 2215
2209 2216 match = regexps[self.greedy].search(self.text_until_cursor)
2210 2217
2211 2218 if match is None:
2212 2219 return []
2213 2220
2214 2221 expr, prefix0, prefix = match.groups()
2215 2222 try:
2216 2223 obj = eval(expr, self.namespace)
2217 2224 except Exception:
2218 2225 try:
2219 2226 obj = eval(expr, self.global_namespace)
2220 2227 except Exception:
2221 2228 return []
2222 2229
2223 2230 keys = self._get_keys(obj)
2224 2231 if not keys:
2225 2232 return keys
2226 2233
2227 2234 extra_prefix = eval(prefix0) if prefix0 != '' else None
2228 2235
2229 2236 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
2230 2237 if not matches:
2231 2238 return matches
2232 2239
2233 2240 # get the cursor position of
2234 2241 # - the text being completed
2235 2242 # - the start of the key text
2236 2243 # - the start of the completion
2237 2244 text_start = len(self.text_until_cursor) - len(text)
2238 2245 if prefix:
2239 2246 key_start = match.start(3)
2240 2247 completion_start = key_start + token_offset
2241 2248 else:
2242 2249 key_start = completion_start = match.end()
2243 2250
2244 2251 # grab the leading prefix, to make sure all completions start with `text`
2245 2252 if text_start > key_start:
2246 2253 leading = ''
2247 2254 else:
2248 2255 leading = text[text_start:completion_start]
2249 2256
2250 2257 # the index of the `[` character
2251 2258 bracket_idx = match.end(1)
2252 2259
2253 2260 # append closing quote and bracket as appropriate
2254 2261 # this is *not* appropriate if the opening quote or bracket is outside
2255 2262 # the text given to this method
2256 2263 suf = ''
2257 2264 continuation = self.line_buffer[len(self.text_until_cursor):]
2258 2265 if key_start > text_start and closing_quote:
2259 2266 # quotes were opened inside text, maybe close them
2260 2267 if continuation.startswith(closing_quote):
2261 2268 continuation = continuation[len(closing_quote):]
2262 2269 else:
2263 2270 suf += closing_quote
2264 2271 if bracket_idx > text_start:
2265 2272 # brackets were opened inside text, maybe close them
2266 2273 if not continuation.startswith(']'):
2267 2274 suf += ']'
2268 2275
2269 2276 return [leading + k + suf for k in matches]
2270 2277
2271 2278 @context_matcher()
2272 2279 def unicode_name_matcher(self, context: CompletionContext):
2273 2280 """Same as :any:`unicode_name_matches`, but adopted to new Matcher API."""
2274 2281 fragment, matches = self.unicode_name_matches(context.text_until_cursor)
2275 2282 return _convert_matcher_v1_result_to_v2(
2276 2283 matches, type="unicode", fragment=fragment, suppress_if_matches=True
2277 2284 )
2278 2285
2279 2286 @staticmethod
2280 2287 def unicode_name_matches(text: str) -> Tuple[str, List[str]]:
2281 2288 """Match Latex-like syntax for unicode characters base
2282 2289 on the name of the character.
2283 2290
2284 2291 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
2285 2292
2286 2293 Works only on valid python 3 identifier, or on combining characters that
2287 2294 will combine to form a valid identifier.
2288 2295 """
2289 2296 slashpos = text.rfind('\\')
2290 2297 if slashpos > -1:
2291 2298 s = text[slashpos+1:]
2292 2299 try :
2293 2300 unic = unicodedata.lookup(s)
2294 2301 # allow combining chars
2295 2302 if ('a'+unic).isidentifier():
2296 2303 return '\\'+s,[unic]
2297 2304 except KeyError:
2298 2305 pass
2299 2306 return '', []
2300 2307
2301 2308 @context_matcher()
2302 2309 def latex_name_matcher(self, context: CompletionContext):
2303 2310 """Match Latex syntax for unicode characters.
2304 2311
2305 2312 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
2306 2313 """
2307 2314 fragment, matches = self.latex_matches(context.text_until_cursor)
2308 2315 return _convert_matcher_v1_result_to_v2(
2309 2316 matches, type="latex", fragment=fragment, suppress_if_matches=True
2310 2317 )
2311 2318
2312 2319 def latex_matches(self, text: str) -> Tuple[str, Sequence[str]]:
2313 2320 """Match Latex syntax for unicode characters.
2314 2321
2315 2322 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
2316 2323
2317 2324 .. deprecated:: 8.6
2318 2325 You can use :meth:`latex_name_matcher` instead.
2319 2326 """
2320 2327 slashpos = text.rfind('\\')
2321 2328 if slashpos > -1:
2322 2329 s = text[slashpos:]
2323 2330 if s in latex_symbols:
2324 2331 # Try to complete a full latex symbol to unicode
2325 2332 # \\alpha -> Ξ±
2326 2333 return s, [latex_symbols[s]]
2327 2334 else:
2328 2335 # If a user has partially typed a latex symbol, give them
2329 2336 # a full list of options \al -> [\aleph, \alpha]
2330 2337 matches = [k for k in latex_symbols if k.startswith(s)]
2331 2338 if matches:
2332 2339 return s, matches
2333 2340 return '', ()
2334 2341
2335 2342 @context_matcher()
2336 2343 def custom_completer_matcher(self, context):
2337 2344 """Dispatch custom completer.
2338 2345
2339 2346 If a match is found, suppresses all other matchers except for Jedi.
2340 2347 """
2341 2348 matches = self.dispatch_custom_completer(context.token) or []
2342 2349 result = _convert_matcher_v1_result_to_v2(
2343 2350 matches, type=_UNKNOWN_TYPE, suppress_if_matches=True
2344 2351 )
2345 2352 result["ordered"] = True
2346 2353 result["do_not_suppress"] = {_get_matcher_id(self._jedi_matcher)}
2347 2354 return result
2348 2355
2349 2356 def dispatch_custom_completer(self, text):
2350 2357 """
2351 2358 .. deprecated:: 8.6
2352 2359 You can use :meth:`custom_completer_matcher` instead.
2353 2360 """
2354 2361 if not self.custom_completers:
2355 2362 return
2356 2363
2357 2364 line = self.line_buffer
2358 2365 if not line.strip():
2359 2366 return None
2360 2367
2361 2368 # Create a little structure to pass all the relevant information about
2362 2369 # the current completion to any custom completer.
2363 2370 event = SimpleNamespace()
2364 2371 event.line = line
2365 2372 event.symbol = text
2366 2373 cmd = line.split(None,1)[0]
2367 2374 event.command = cmd
2368 2375 event.text_until_cursor = self.text_until_cursor
2369 2376
2370 2377 # for foo etc, try also to find completer for %foo
2371 2378 if not cmd.startswith(self.magic_escape):
2372 2379 try_magic = self.custom_completers.s_matches(
2373 2380 self.magic_escape + cmd)
2374 2381 else:
2375 2382 try_magic = []
2376 2383
2377 2384 for c in itertools.chain(self.custom_completers.s_matches(cmd),
2378 2385 try_magic,
2379 2386 self.custom_completers.flat_matches(self.text_until_cursor)):
2380 2387 try:
2381 2388 res = c(event)
2382 2389 if res:
2383 2390 # first, try case sensitive match
2384 2391 withcase = [r for r in res if r.startswith(text)]
2385 2392 if withcase:
2386 2393 return withcase
2387 2394 # if none, then case insensitive ones are ok too
2388 2395 text_low = text.lower()
2389 2396 return [r for r in res if r.lower().startswith(text_low)]
2390 2397 except TryNext:
2391 2398 pass
2392 2399 except KeyboardInterrupt:
2393 2400 """
2394 2401 If custom completer take too long,
2395 2402 let keyboard interrupt abort and return nothing.
2396 2403 """
2397 2404 break
2398 2405
2399 2406 return None
2400 2407
2401 2408 def completions(self, text: str, offset: int)->Iterator[Completion]:
2402 2409 """
2403 2410 Returns an iterator over the possible completions
2404 2411
2405 2412 .. warning::
2406 2413
2407 2414 Unstable
2408 2415
2409 2416 This function is unstable, API may change without warning.
2410 2417 It will also raise unless use in proper context manager.
2411 2418
2412 2419 Parameters
2413 2420 ----------
2414 2421 text : str
2415 2422 Full text of the current input, multi line string.
2416 2423 offset : int
2417 2424 Integer representing the position of the cursor in ``text``. Offset
2418 2425 is 0-based indexed.
2419 2426
2420 2427 Yields
2421 2428 ------
2422 2429 Completion
2423 2430
2424 2431 Notes
2425 2432 -----
2426 2433 The cursor on a text can either be seen as being "in between"
2427 2434 characters or "On" a character depending on the interface visible to
2428 2435 the user. For consistency the cursor being on "in between" characters X
2429 2436 and Y is equivalent to the cursor being "on" character Y, that is to say
2430 2437 the character the cursor is on is considered as being after the cursor.
2431 2438
2432 2439 Combining characters may span more that one position in the
2433 2440 text.
2434 2441
2435 2442 .. note::
2436 2443
2437 2444 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
2438 2445 fake Completion token to distinguish completion returned by Jedi
2439 2446 and usual IPython completion.
2440 2447
2441 2448 .. note::
2442 2449
2443 2450 Completions are not completely deduplicated yet. If identical
2444 2451 completions are coming from different sources this function does not
2445 2452 ensure that each completion object will only be present once.
2446 2453 """
2447 2454 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
2448 2455 "It may change without warnings. "
2449 2456 "Use in corresponding context manager.",
2450 2457 category=ProvisionalCompleterWarning, stacklevel=2)
2451 2458
2452 2459 seen = set()
2453 2460 profiler:Optional[cProfile.Profile]
2454 2461 try:
2455 2462 if self.profile_completions:
2456 2463 import cProfile
2457 2464 profiler = cProfile.Profile()
2458 2465 profiler.enable()
2459 2466 else:
2460 2467 profiler = None
2461 2468
2462 2469 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
2463 2470 if c and (c in seen):
2464 2471 continue
2465 2472 yield c
2466 2473 seen.add(c)
2467 2474 except KeyboardInterrupt:
2468 2475 """if completions take too long and users send keyboard interrupt,
2469 2476 do not crash and return ASAP. """
2470 2477 pass
2471 2478 finally:
2472 2479 if profiler is not None:
2473 2480 profiler.disable()
2474 2481 ensure_dir_exists(self.profiler_output_dir)
2475 2482 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
2476 2483 print("Writing profiler output to", output_path)
2477 2484 profiler.dump_stats(output_path)
2478 2485
2479 2486 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
2480 2487 """
2481 2488 Core completion module.Same signature as :any:`completions`, with the
2482 2489 extra `timeout` parameter (in seconds).
2483 2490
2484 2491 Computing jedi's completion ``.type`` can be quite expensive (it is a
2485 2492 lazy property) and can require some warm-up, more warm up than just
2486 2493 computing the ``name`` of a completion. The warm-up can be :
2487 2494
2488 2495 - Long warm-up the first time a module is encountered after
2489 2496 install/update: actually build parse/inference tree.
2490 2497
2491 2498 - first time the module is encountered in a session: load tree from
2492 2499 disk.
2493 2500
2494 2501 We don't want to block completions for tens of seconds so we give the
2495 2502 completer a "budget" of ``_timeout`` seconds per invocation to compute
2496 2503 completions types, the completions that have not yet been computed will
2497 2504 be marked as "unknown" an will have a chance to be computed next round
2498 2505 are things get cached.
2499 2506
2500 2507 Keep in mind that Jedi is not the only thing treating the completion so
2501 2508 keep the timeout short-ish as if we take more than 0.3 second we still
2502 2509 have lots of processing to do.
2503 2510
2504 2511 """
2505 2512 deadline = time.monotonic() + _timeout
2506 2513
2507 2514 before = full_text[:offset]
2508 2515 cursor_line, cursor_column = position_to_cursor(full_text, offset)
2509 2516
2510 2517 jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
2511 2518
2512 2519 results = self._complete(
2513 2520 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column
2514 2521 )
2515 2522 non_jedi_results: Dict[str, SimpleMatcherResult] = {
2516 2523 identifier: result
2517 2524 for identifier, result in results.items()
2518 2525 if identifier != jedi_matcher_id
2519 2526 }
2520 2527
2521 2528 jedi_matches = (
2522 2529 cast(results[jedi_matcher_id], _JediMatcherResult)["completions"]
2523 2530 if jedi_matcher_id in results
2524 2531 else ()
2525 2532 )
2526 2533
2527 2534 iter_jm = iter(jedi_matches)
2528 2535 if _timeout:
2529 2536 for jm in iter_jm:
2530 2537 try:
2531 2538 type_ = jm.type
2532 2539 except Exception:
2533 2540 if self.debug:
2534 2541 print("Error in Jedi getting type of ", jm)
2535 2542 type_ = None
2536 2543 delta = len(jm.name_with_symbols) - len(jm.complete)
2537 2544 if type_ == 'function':
2538 2545 signature = _make_signature(jm)
2539 2546 else:
2540 2547 signature = ''
2541 2548 yield Completion(start=offset - delta,
2542 2549 end=offset,
2543 2550 text=jm.name_with_symbols,
2544 2551 type=type_,
2545 2552 signature=signature,
2546 2553 _origin='jedi')
2547 2554
2548 2555 if time.monotonic() > deadline:
2549 2556 break
2550 2557
2551 2558 for jm in iter_jm:
2552 2559 delta = len(jm.name_with_symbols) - len(jm.complete)
2553 2560 yield Completion(
2554 2561 start=offset - delta,
2555 2562 end=offset,
2556 2563 text=jm.name_with_symbols,
2557 2564 type=_UNKNOWN_TYPE, # don't compute type for speed
2558 2565 _origin="jedi",
2559 2566 signature="",
2560 2567 )
2561 2568
2562 2569 # TODO:
2563 2570 # Suppress this, right now just for debug.
2564 2571 if jedi_matches and non_jedi_results and self.debug:
2565 2572 some_start_offset = before.rfind(
2566 2573 next(iter(non_jedi_results.values()))["matched_fragment"]
2567 2574 )
2568 2575 yield Completion(
2569 2576 start=some_start_offset,
2570 2577 end=offset,
2571 2578 text="--jedi/ipython--",
2572 2579 _origin="debug",
2573 2580 type="none",
2574 2581 signature="",
2575 2582 )
2576 2583
2577 2584 ordered = []
2578 2585 sortable = []
2579 2586
2580 2587 for origin, result in non_jedi_results.items():
2581 2588 matched_text = result["matched_fragment"]
2582 2589 start_offset = before.rfind(matched_text)
2583 2590 is_ordered = result.get("ordered", False)
2584 2591 container = ordered if is_ordered else sortable
2585 2592
2586 2593 # I'm unsure if this is always true, so let's assert and see if it
2587 2594 # crash
2588 2595 assert before.endswith(matched_text)
2589 2596
2590 2597 for simple_completion in result["completions"]:
2591 2598 completion = Completion(
2592 2599 start=start_offset,
2593 2600 end=offset,
2594 2601 text=simple_completion.text,
2595 2602 _origin=origin,
2596 2603 signature="",
2597 2604 type=simple_completion.type or _UNKNOWN_TYPE,
2598 2605 )
2599 2606 container.append(completion)
2600 2607
2601 2608 yield from list(self._deduplicate(ordered + self._sort(sortable)))[
2602 2609 :MATCHES_LIMIT
2603 2610 ]
2604 2611
2605 2612 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2606 2613 """Find completions for the given text and line context.
2607 2614
2608 2615 Note that both the text and the line_buffer are optional, but at least
2609 2616 one of them must be given.
2610 2617
2611 2618 Parameters
2612 2619 ----------
2613 2620 text : string, optional
2614 2621 Text to perform the completion on. If not given, the line buffer
2615 2622 is split using the instance's CompletionSplitter object.
2616 2623 line_buffer : string, optional
2617 2624 If not given, the completer attempts to obtain the current line
2618 2625 buffer via readline. This keyword allows clients which are
2619 2626 requesting for text completions in non-readline contexts to inform
2620 2627 the completer of the entire text.
2621 2628 cursor_pos : int, optional
2622 2629 Index of the cursor in the full line buffer. Should be provided by
2623 2630 remote frontends where kernel has no access to frontend state.
2624 2631
2625 2632 Returns
2626 2633 -------
2627 2634 Tuple of two items:
2628 2635 text : str
2629 2636 Text that was actually used in the completion.
2630 2637 matches : list
2631 2638 A list of completion matches.
2632 2639
2633 2640 Notes
2634 2641 -----
2635 2642 This API is likely to be deprecated and replaced by
2636 2643 :any:`IPCompleter.completions` in the future.
2637 2644
2638 2645 """
2639 2646 warnings.warn('`Completer.complete` is pending deprecation since '
2640 2647 'IPython 6.0 and will be replaced by `Completer.completions`.',
2641 2648 PendingDeprecationWarning)
2642 2649 # potential todo, FOLD the 3rd throw away argument of _complete
2643 2650 # into the first 2 one.
2644 2651 # TODO: Q: does the above refer to jedi completions (i.e. 0-indexed?)
2645 2652 # TODO: should we deprecate now, or does it stay?
2646 2653
2647 2654 results = self._complete(
2648 2655 line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0
2649 2656 )
2650 2657
2651 2658 jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
2652 2659
2653 2660 return self._arrange_and_extract(
2654 2661 results,
2655 2662 # TODO: can we confirm that excluding Jedi here was a deliberate choice in previous version?
2656 2663 skip_matchers={jedi_matcher_id},
2657 2664 # this API does not support different start/end positions (fragments of token).
2658 2665 abort_if_offset_changes=True,
2659 2666 )
2660 2667
2661 2668 def _arrange_and_extract(
2662 2669 self,
2663 2670 results: Dict[str, MatcherResult],
2664 2671 skip_matchers: Set[str],
2665 2672 abort_if_offset_changes: bool,
2666 2673 ):
2667 2674
2668 2675 sortable = []
2669 2676 ordered = []
2670 2677 most_recent_fragment = None
2671 2678 for identifier, result in results.items():
2672 2679 if identifier in skip_matchers:
2673 2680 continue
2674 2681 if not result["completions"]:
2675 2682 continue
2676 2683 if not most_recent_fragment:
2677 2684 most_recent_fragment = result["matched_fragment"]
2678 2685 if (
2679 2686 abort_if_offset_changes
2680 2687 and result["matched_fragment"] != most_recent_fragment
2681 2688 ):
2682 2689 break
2683 2690 if result.get("ordered", False):
2684 2691 ordered.extend(result["completions"])
2685 2692 else:
2686 2693 sortable.extend(result["completions"])
2687 2694
2688 2695 if not most_recent_fragment:
2689 2696 most_recent_fragment = "" # to satisfy typechecker (and just in case)
2690 2697
2691 2698 return most_recent_fragment, [
2692 2699 m.text for m in self._deduplicate(ordered + self._sort(sortable))
2693 2700 ]
2694 2701
2695 2702 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2696 2703 full_text=None) -> _CompleteResult:
2697 2704 """
2698 2705 Like complete but can also returns raw jedi completions as well as the
2699 2706 origin of the completion text. This could (and should) be made much
2700 2707 cleaner but that will be simpler once we drop the old (and stateful)
2701 2708 :any:`complete` API.
2702 2709
2703 2710 With current provisional API, cursor_pos act both (depending on the
2704 2711 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2705 2712 ``column`` when passing multiline strings this could/should be renamed
2706 2713 but would add extra noise.
2707 2714
2708 2715 Parameters
2709 2716 ----------
2710 2717 cursor_line
2711 2718 Index of the line the cursor is on. 0 indexed.
2712 2719 cursor_pos
2713 2720 Position of the cursor in the current line/line_buffer/text. 0
2714 2721 indexed.
2715 2722 line_buffer : optional, str
2716 2723 The current line the cursor is in, this is mostly due to legacy
2717 2724 reason that readline could only give a us the single current line.
2718 2725 Prefer `full_text`.
2719 2726 text : str
2720 2727 The current "token" the cursor is in, mostly also for historical
2721 2728 reasons. as the completer would trigger only after the current line
2722 2729 was parsed.
2723 2730 full_text : str
2724 2731 Full text of the current cell.
2725 2732
2726 2733 Returns
2727 2734 -------
2728 2735 An ordered dictionary where keys are identifiers of completion
2729 2736 matchers and values are ``MatcherResult``s.
2730 2737 """
2731 2738
2732 2739 # if the cursor position isn't given, the only sane assumption we can
2733 2740 # make is that it's at the end of the line (the common case)
2734 2741 if cursor_pos is None:
2735 2742 cursor_pos = len(line_buffer) if text is None else len(text)
2736 2743
2737 2744 if self.use_main_ns:
2738 2745 self.namespace = __main__.__dict__
2739 2746
2740 2747 # if text is either None or an empty string, rely on the line buffer
2741 2748 if (not line_buffer) and full_text:
2742 2749 line_buffer = full_text.split('\n')[cursor_line]
2743 2750 if not text: # issue #11508: check line_buffer before calling split_line
2744 2751 text = (
2745 2752 self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ""
2746 2753 )
2747 2754
2748 2755 # If no line buffer is given, assume the input text is all there was
2749 2756 if line_buffer is None:
2750 2757 line_buffer = text
2751 2758
2752 2759 # deprecated - do not use `line_buffer` in new code.
2753 2760 self.line_buffer = line_buffer
2754 2761 self.text_until_cursor = self.line_buffer[:cursor_pos]
2755 2762
2756 2763 if not full_text:
2757 2764 full_text = line_buffer
2758 2765
2759 2766 context = CompletionContext(
2760 2767 full_text=full_text,
2761 2768 cursor_position=cursor_pos,
2762 2769 cursor_line=cursor_line,
2763 2770 token=text,
2764 2771 limit=MATCHES_LIMIT,
2765 2772 )
2766 2773
2767 2774 # Start with a clean slate of completions
2768 2775 results = {}
2769 2776
2770 2777 jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
2771 2778
2772 2779 suppressed_matchers = set()
2773 2780
2774 2781 matchers = {
2775 2782 _get_matcher_id(matcher): matcher
2776 2783 for matcher in sorted(
2777 2784 self.matchers, key=_get_matcher_priority, reverse=True
2778 2785 )
2779 2786 }
2780 2787
2781 2788 for matcher_id, matcher in matchers.items():
2782 2789 api_version = _get_matcher_api_version(matcher)
2783 2790 matcher_id = _get_matcher_id(matcher)
2784 2791
2785 2792 if matcher_id in self.disable_matchers:
2786 2793 continue
2787 2794
2788 2795 if matcher_id in results:
2789 2796 warnings.warn(f"Duplicate matcher ID: {matcher_id}.")
2790 2797
2791 2798 if matcher_id in suppressed_matchers:
2792 2799 continue
2793 2800
2794 2801 try:
2795 2802 if api_version == 1:
2796 2803 result = _convert_matcher_v1_result_to_v2(
2797 2804 matcher(text), type=_UNKNOWN_TYPE
2798 2805 )
2799 2806 elif api_version == 2:
2800 2807 result = cast(matcher, MatcherAPIv2)(context)
2801 2808 else:
2802 2809 raise ValueError(f"Unsupported API version {api_version}")
2803 2810 except:
2804 2811 # Show the ugly traceback if the matcher causes an
2805 2812 # exception, but do NOT crash the kernel!
2806 2813 sys.excepthook(*sys.exc_info())
2807 2814 continue
2808 2815
2809 2816 # set default value for matched fragment if suffix was not selected.
2810 2817 result["matched_fragment"] = result.get("matched_fragment", context.token)
2811 2818
2812 2819 if not suppressed_matchers:
2813 2820 suppression_recommended = result.get("suppress", False)
2814 2821
2815 2822 suppression_config = (
2816 2823 self.suppress_competing_matchers.get(matcher_id, None)
2817 2824 if isinstance(self.suppress_competing_matchers, dict)
2818 2825 else self.suppress_competing_matchers
2819 2826 )
2820 2827 should_suppress = (
2821 2828 (suppression_config is True)
2822 2829 or (suppression_recommended and (suppression_config is not False))
2823 2830 ) and has_any_completions(result)
2824 2831
2825 2832 if should_suppress:
2826 2833 suppression_exceptions = result.get("do_not_suppress", set())
2827 2834 try:
2828 2835 to_suppress = set(suppression_recommended)
2829 2836 except TypeError:
2830 2837 to_suppress = set(matchers)
2831 2838 suppressed_matchers = to_suppress - suppression_exceptions
2832 2839
2833 2840 new_results = {}
2834 2841 for previous_matcher_id, previous_result in results.items():
2835 2842 if previous_matcher_id not in suppressed_matchers:
2836 2843 new_results[previous_matcher_id] = previous_result
2837 2844 results = new_results
2838 2845
2839 2846 results[matcher_id] = result
2840 2847
2841 2848 _, matches = self._arrange_and_extract(
2842 2849 results,
2843 2850 # TODO Jedi completions non included in legacy stateful API; was this deliberate or omission?
2844 2851 # if it was omission, we can remove the filtering step, otherwise remove this comment.
2845 2852 skip_matchers={jedi_matcher_id},
2846 2853 abort_if_offset_changes=False,
2847 2854 )
2848 2855
2849 2856 # populate legacy stateful API
2850 2857 self.matches = matches
2851 2858
2852 2859 return results
2853 2860
2854 2861 @staticmethod
2855 2862 def _deduplicate(
2856 2863 matches: Sequence[SimpleCompletion],
2857 2864 ) -> Iterable[SimpleCompletion]:
2858 2865 filtered_matches = {}
2859 2866 for match in matches:
2860 2867 text = match.text
2861 2868 if (
2862 2869 text not in filtered_matches
2863 2870 or filtered_matches[text].type == _UNKNOWN_TYPE
2864 2871 ):
2865 2872 filtered_matches[text] = match
2866 2873
2867 2874 return filtered_matches.values()
2868 2875
2869 2876 @staticmethod
2870 2877 def _sort(matches: Sequence[SimpleCompletion]):
2871 2878 return sorted(matches, key=lambda x: completions_sorting_key(x.text))
2872 2879
2873 2880 @context_matcher()
2874 2881 def fwd_unicode_matcher(self, context: CompletionContext):
2875 2882 """Same as :any:`fwd_unicode_match`, but adopted to new Matcher API."""
2876 2883 # TODO: use `context.limit` to terminate early once we matched the maximum
2877 2884 # number that will be used downstream; can be added as an optional to
2878 2885 # `fwd_unicode_match(text: str, limit: int = None)` or we could re-implement here.
2879 2886 fragment, matches = self.fwd_unicode_match(context.text_until_cursor)
2880 2887 return _convert_matcher_v1_result_to_v2(
2881 2888 matches, type="unicode", fragment=fragment, suppress_if_matches=True
2882 2889 )
2883 2890
2884 2891 def fwd_unicode_match(self, text: str) -> Tuple[str, Sequence[str]]:
2885 2892 """
2886 2893 Forward match a string starting with a backslash with a list of
2887 2894 potential Unicode completions.
2888 2895
2889 2896 Will compute list of Unicode character names on first call and cache it.
2890 2897
2891 2898 .. deprecated:: 8.6
2892 2899 You can use :meth:`fwd_unicode_matcher` instead.
2893 2900
2894 2901 Returns
2895 2902 -------
2896 2903 At tuple with:
2897 2904 - matched text (empty if no matches)
2898 2905 - list of potential completions, empty tuple otherwise)
2899 2906 """
2900 2907 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2901 2908 # We could do a faster match using a Trie.
2902 2909
2903 2910 # Using pygtrie the following seem to work:
2904 2911
2905 2912 # s = PrefixSet()
2906 2913
2907 2914 # for c in range(0,0x10FFFF + 1):
2908 2915 # try:
2909 2916 # s.add(unicodedata.name(chr(c)))
2910 2917 # except ValueError:
2911 2918 # pass
2912 2919 # [''.join(k) for k in s.iter(prefix)]
2913 2920
2914 2921 # But need to be timed and adds an extra dependency.
2915 2922
2916 2923 slashpos = text.rfind('\\')
2917 2924 # if text starts with slash
2918 2925 if slashpos > -1:
2919 2926 # PERF: It's important that we don't access self._unicode_names
2920 2927 # until we're inside this if-block. _unicode_names is lazily
2921 2928 # initialized, and it takes a user-noticeable amount of time to
2922 2929 # initialize it, so we don't want to initialize it unless we're
2923 2930 # actually going to use it.
2924 2931 s = text[slashpos + 1 :]
2925 2932 sup = s.upper()
2926 2933 candidates = [x for x in self.unicode_names if x.startswith(sup)]
2927 2934 if candidates:
2928 2935 return s, candidates
2929 2936 candidates = [x for x in self.unicode_names if sup in x]
2930 2937 if candidates:
2931 2938 return s, candidates
2932 2939 splitsup = sup.split(" ")
2933 2940 candidates = [
2934 2941 x for x in self.unicode_names if all(u in x for u in splitsup)
2935 2942 ]
2936 2943 if candidates:
2937 2944 return s, candidates
2938 2945
2939 2946 return "", ()
2940 2947
2941 2948 # if text does not start with slash
2942 2949 else:
2943 2950 return '', ()
2944 2951
2945 2952 @property
2946 2953 def unicode_names(self) -> List[str]:
2947 2954 """List of names of unicode code points that can be completed.
2948 2955
2949 2956 The list is lazily initialized on first access.
2950 2957 """
2951 2958 if self._unicode_names is None:
2952 2959 names = []
2953 2960 for c in range(0,0x10FFFF + 1):
2954 2961 try:
2955 2962 names.append(unicodedata.name(chr(c)))
2956 2963 except ValueError:
2957 2964 pass
2958 2965 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2959 2966
2960 2967 return self._unicode_names
2961 2968
2962 2969 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2963 2970 names = []
2964 2971 for start,stop in ranges:
2965 2972 for c in range(start, stop) :
2966 2973 try:
2967 2974 names.append(unicodedata.name(chr(c)))
2968 2975 except ValueError:
2969 2976 pass
2970 2977 return names
@@ -1,210 +1,212 b''
1 1 """Implementation of configuration-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 re
17 17
18 18 # Our own packages
19 19 from IPython.core.error import UsageError
20 20 from IPython.core.magic import Magics, magics_class, line_magic
21 21 from logging import error
22 22
23 23 #-----------------------------------------------------------------------------
24 24 # Magic implementation classes
25 25 #-----------------------------------------------------------------------------
26 26
27 27 reg = re.compile(r'^\w+\.\w+$')
28 28 @magics_class
29 29 class ConfigMagics(Magics):
30 30
31 31 def __init__(self, shell):
32 32 super(ConfigMagics, self).__init__(shell)
33 33 self.configurables = []
34 34
35 35 @line_magic
36 36 def config(self, s):
37 37 """configure IPython
38 38
39 39 %config Class[.trait=value]
40 40
41 41 This magic exposes most of the IPython config system. Any
42 42 Configurable class should be able to be configured with the simple
43 43 line::
44 44
45 45 %config Class.trait=value
46 46
47 47 Where `value` will be resolved in the user's namespace, if it is an
48 48 expression or variable name.
49 49
50 50 Examples
51 51 --------
52 52
53 53 To see what classes are available for config, pass no arguments::
54 54
55 55 In [1]: %config
56 56 Available objects for config:
57 57 AliasManager
58 58 DisplayFormatter
59 59 HistoryManager
60 60 IPCompleter
61 61 LoggingMagics
62 62 MagicsManager
63 63 OSMagics
64 64 PrefilterManager
65 65 ScriptMagics
66 66 TerminalInteractiveShell
67 67
68 68 To view what is configurable on a given class, just pass the class
69 69 name::
70 70
71 71 In [2]: %config IPCompleter
72 72 IPCompleter(Completer) options
73 73 ----------------------------
74 74 IPCompleter.backslash_combining_completions=<Bool>
75 75 Enable unicode completions, e.g. \\alpha<tab> . Includes completion of latex
76 76 commands, unicode names, and expanding unicode characters back to latex
77 77 commands.
78 78 Current: True
79 79 IPCompleter.debug=<Bool>
80 80 Enable debug for the Completer. Mostly print extra information for
81 81 experimental jedi integration.
82 82 Current: False
83 83 IPCompleter.disable_matchers=<list-item-1>...
84 84 List of matchers to disable.
85 The list should contain matcher identifiers (see
86 :any:`completion_matcher`).
85 87 Current: []
86 88 IPCompleter.greedy=<Bool>
87 89 Activate greedy completion
88 90 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
89 91 This will enable completion on elements of lists, results of function calls, etc.,
90 92 but can be unsafe because the code is actually evaluated on TAB.
91 93 Current: False
92 94 IPCompleter.jedi_compute_type_timeout=<Int>
93 95 Experimental: restrict time (in milliseconds) during which Jedi can compute types.
94 96 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
95 97 performance by preventing jedi to build its cache.
96 98 Current: 400
97 99 IPCompleter.limit_to__all__=<Bool>
98 100 DEPRECATED as of version 5.0.
99 101 Instruct the completer to use __all__ for the completion
100 102 Specifically, when completing on ``object.<tab>``.
101 103 When True: only those names in obj.__all__ will be included.
102 104 When False [default]: the __all__ attribute is ignored
103 105 Current: False
104 106 IPCompleter.merge_completions=<Bool>
105 107 Whether to merge completion results into a single list
106 108 If False, only the completion results from the first non-empty
107 109 completer will be returned.
108 110 As of version 8.6.0, setting the value to ``False`` is an alias for:
109 111 ``IPCompleter.suppress_competing_matchers = True.``.
110 112 Current: True
111 113 IPCompleter.omit__names=<Enum>
112 114 Instruct the completer to omit private method names
113 115 Specifically, when completing on ``object.<tab>``.
114 116 When 2 [default]: all names that start with '_' will be excluded.
115 117 When 1: all 'magic' names (``__foo__``) will be excluded.
116 118 When 0: nothing will be excluded.
117 119 Choices: any of [0, 1, 2]
118 120 Current: 2
119 121 IPCompleter.profile_completions=<Bool>
120 122 If True, emit profiling data for completion subsystem using cProfile.
121 123 Current: False
122 124 IPCompleter.profiler_output_dir=<Unicode>
123 125 Template for path at which to output profile data for completions.
124 126 Current: '.completion_profiles'
125 127 IPCompleter.suppress_competing_matchers=<Union>
126 128 Whether to suppress completions from other *Matchers*.
127 129 When set to ``None`` (default) the matchers will attempt to auto-detect
128 130 whether suppression of other matchers is desirable. For example, at the
129 131 beginning of a line followed by `%` we expect a magic completion to be the
130 132 only applicable option, and after ``my_dict['`` we usually expect a
131 133 completion with an existing dictionary key.
132 134 If you want to disable this heuristic and see completions from all matchers,
133 135 set ``IPCompleter.suppress_competing_matchers = False``. To disable the
134 136 heuristic for specific matchers provide a dictionary mapping:
135 137 ``IPCompleter.suppress_competing_matchers = {'IPCompleter.dict_key_matcher':
136 138 False}``.
137 139 Set ``IPCompleter.suppress_competing_matchers = True`` to limit completions
138 140 to the set of matchers with the highest priority; this is equivalent to
139 141 ``IPCompleter.merge_completions`` and can be beneficial for performance, but
140 142 will sometimes omit relevant candidates from matchers further down the
141 143 priority list.
142 144 Current: None
143 145 IPCompleter.use_jedi=<Bool>
144 146 Experimental: Use Jedi to generate autocompletions. Default to True if jedi
145 147 is installed.
146 148 Current: True
147 149
148 150 but the real use is in setting values::
149 151
150 152 In [3]: %config IPCompleter.greedy = True
151 153
152 154 and these values are read from the user_ns if they are variables::
153 155
154 156 In [4]: feeling_greedy=False
155 157
156 158 In [5]: %config IPCompleter.greedy = feeling_greedy
157 159
158 160 """
159 161 from traitlets.config.loader import Config
160 162 # some IPython objects are Configurable, but do not yet have
161 163 # any configurable traits. Exclude them from the effects of
162 164 # this magic, as their presence is just noise:
163 165 configurables = sorted(set([ c for c in self.shell.configurables
164 166 if c.__class__.class_traits(config=True)
165 167 ]), key=lambda x: x.__class__.__name__)
166 168 classnames = [ c.__class__.__name__ for c in configurables ]
167 169
168 170 line = s.strip()
169 171 if not line:
170 172 # print available configurable names
171 173 print("Available objects for config:")
172 174 for name in classnames:
173 175 print(" ", name)
174 176 return
175 177 elif line in classnames:
176 178 # `%config TerminalInteractiveShell` will print trait info for
177 179 # TerminalInteractiveShell
178 180 c = configurables[classnames.index(line)]
179 181 cls = c.__class__
180 182 help = cls.class_get_help(c)
181 183 # strip leading '--' from cl-args:
182 184 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
183 185 print(help)
184 186 return
185 187 elif reg.match(line):
186 188 cls, attr = line.split('.')
187 189 return getattr(configurables[classnames.index(cls)],attr)
188 190 elif '=' not in line:
189 191 msg = "Invalid config statement: %r, "\
190 192 "should be `Class.trait = value`."
191 193
192 194 ll = line.lower()
193 195 for classname in classnames:
194 196 if ll == classname.lower():
195 197 msg = msg + '\nDid you mean %s (note the case)?' % classname
196 198 break
197 199
198 200 raise UsageError( msg % line)
199 201
200 202 # otherwise, assume we are setting configurables.
201 203 # leave quotes on args when splitting, because we want
202 204 # unquoted args to eval in user_ns
203 205 cfg = Config()
204 206 exec("cfg."+line, self.shell.user_ns, locals())
205 207
206 208 for configurable in configurables:
207 209 try:
208 210 configurable.update_config(cfg)
209 211 except Exception as e:
210 212 error(e)
General Comments 0
You need to be logged in to leave comments. Login now