Debian Codegraph @

IPython/core/completer.py

raw
1 """Completion for IPython.
2
3 This module started as fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3,
6
7 This module now support a wide variety of completion mechanism both available
8 for normal classic Python code, as well as completer for IPython specific
9 Syntax like magics.
10
11 Latex and Unicode completion
12 ============================
13
14 IPython and compatible frontends not only can complete your code, but can help
15 you to input a wide range of characters. In particular we allow you to insert
16 a unicode character using the tab completion mechanism.
17
18 Forward latex/unicode completion
19 --------------------------------
20
21 Forward completion allows you to easily type a unicode character using its latex
22 name, or unicode long description. To do so type a backslash follow by the
23 relevant name and press tab:
24
25
26 Using latex completion:
27
28 .. code::
29
30 \\alpha<tab>
31 α
32
33 or using unicode completion:
34
35
36 .. code::
37
38 \\GREEK SMALL LETTER ALPHA<tab>
39 α
40
41
42 Only valid Python identifiers will complete. Combining characters (like arrow or
43 dots) are also available, unlike latex they need to be put after the their
44 counterpart that is to say, ``F\\\\vec<tab>`` is correct, not ``\\\\vec<tab>F``.
45
46 Some browsers are known to display combining characters incorrectly.
47
48 Backward latex completion
49 -------------------------
50
51 It is sometime challenging to know how to type a character, if you are using
52 IPython, or any compatible frontend you can prepend backslash to the character
53 and press :kbd:`Tab` to expand it to its latex form.
54
55 .. code::
56
57 \\α<tab>
58 \\alpha
59
60
61 Both forward and backward completions can be deactivated by setting the
62 :std:configtrait:`Completer.backslash_combining_completions` option to
63 ``False``.
64
65
66 Experimental
67 ============
68
69 Starting with IPython 6.0, this module can make use of the Jedi library to
70 generate completions both using static analysis of the code, and dynamically
71 inspecting multiple namespaces. Jedi is an autocompletion and static analysis
72 for Python. The APIs attached to this new mechanism is unstable and will
73 raise unless use in an :any:`provisionalcompleter` context manager.
74
75 You will find that the following are experimental:
76
77 - :any:`provisionalcompleter`
78 - :any:`IPCompleter.completions`
79 - :any:`Completion`
80 - :any:`rectify_completions`
81
82 .. note::
83
84 better name for :any:`rectify_completions` ?
85
86 We welcome any feedback on these new API, and we also encourage you to try this
87 module in debug mode (start IPython with ``--Completer.debug=True``) in order
88 to have extra logging information if :mod:`jedi` is crashing, or if current
89 IPython completer pending deprecations are returning results not yet handled
90 by :mod:`jedi`
91
92 Using Jedi for tab completion allow snippets like the following to work without
93 having to execute any code:
94
95 >>> myvar = ['hello', 42]
96 ... myvar[1].bi<tab>
97
98 Tab completion will be able to infer that ``myvar[1]`` is a real number without
99 executing almost any code unlike the deprecated :any:`IPCompleter.greedy`
100 option.
101
102 Be sure to update :mod:`jedi` to the latest stable version or to try the
103 current development version to get better completions.
104
105 Matchers
106 ========
107
108 All completions routines are implemented using unified *Matchers* API.
109 The matchers API is provisional and subject to change without notice.
110
111 The built-in matchers include:
112
113 - :any:`IPCompleter.dict_key_matcher`: dictionary key completions,
114 - :any:`IPCompleter.magic_matcher`: completions for magics,
115 - :any:`IPCompleter.unicode_name_matcher`,
116 :any:`IPCompleter.fwd_unicode_matcher`
117 and :any:`IPCompleter.latex_name_matcher`: see `Forward latex/unicode completion`_,
118 - :any:`back_unicode_name_matcher` and :any:`back_latex_name_matcher`: see `Backward latex completion`_,
119 - :any:`IPCompleter.file_matcher`: paths to files and directories,
120 - :any:`IPCompleter.python_func_kw_matcher` - function keywords,
121 - :any:`IPCompleter.python_matches` - globals and attributes (v1 API),
122 - ``IPCompleter.jedi_matcher`` - static analysis with Jedi,
123 - :any:`IPCompleter.custom_completer_matcher` - pluggable completer with a default
124 implementation in :any:`InteractiveShell` which uses IPython hooks system
125 (`complete_command`) with string dispatch (including regular expressions).
126 Differently to other matchers, ``custom_completer_matcher`` will not suppress
127 Jedi results to match behaviour in earlier IPython versions.
128
129 Custom matchers can be added by appending to ``IPCompleter.custom_matchers`` list.
130
131 Matcher API
132 -----------
133
134 Simplifying some details, the ``Matcher`` interface can described as
135
136 .. code-block::
137
138 MatcherAPIv1 = Callable[[str], list[str]]
139 MatcherAPIv2 = Callable[[CompletionContext], SimpleMatcherResult]
140
141 Matcher = MatcherAPIv1 | MatcherAPIv2
142
143 The ``MatcherAPIv1`` reflects the matcher API as available prior to IPython 8.6.0
144 and remains supported as a simplest way for generating completions. This is also
145 currently the only API supported by the IPython hooks system `complete_command`.
146
147 To distinguish between matcher versions ``matcher_api_version`` attribute is used.
148 More precisely, the API allows to omit ``matcher_api_version`` for v1 Matchers,
149 and requires a literal ``2`` for v2 Matchers.
150
151 Once the API stabilises future versions may relax the requirement for specifying
152 ``matcher_api_version`` by switching to :func:`functools.singledispatch`, therefore
153 please do not rely on the presence of ``matcher_api_version`` for any purposes.
154
155 Suppression of competing matchers
156 ---------------------------------
157
158 By default results from all matchers are combined, in the order determined by
159 their priority. Matchers can request to suppress results from subsequent
160 matchers by setting ``suppress`` to ``True`` in the ``MatcherResult``.
161
162 When multiple matchers simultaneously request suppression, the results from of
163 the matcher with higher priority will be returned.
164
165 Sometimes it is desirable to suppress most but not all other matchers;
166 this can be achieved by adding a set of identifiers of matchers which
167 should not be suppressed to ``MatcherResult`` under ``do_not_suppress`` key.
168
169 The suppression behaviour can is user-configurable via
170 :std:configtrait:`IPCompleter.suppress_competing_matchers`.
171 """
172
173
174 # Copyright (c) IPython Development Team.
175 # Distributed under the terms of the Modified BSD License.
176 #
177 # Some of this code originated from rlcompleter in the Python standard library
178 # Copyright (C) 2001 Python Software Foundation, www.python.org
179
180 from __future__ import annotations
181 import builtins as builtin_mod
182 import enum
183 import glob
184 import inspect
185 import itertools
186 import keyword
187 import ast
188 import os
189 import re
190 import string
191 import sys
192 import tokenize
193 import time
194 import unicodedata
195 import uuid
196 import warnings
197 from ast import literal_eval
198 from collections import defaultdict
199 from contextlib import contextmanager
200 from dataclasses import dataclass
201 from functools import cached_property, partial
202 from types import SimpleNamespace
203 from typing import (
204 Union,
205 Any,
206 Optional,
207 TYPE_CHECKING,
208 TypeVar,
209 Literal,
210 )
211 from collections.abc import Iterable, Iterator, Sequence, Sized
212
213 from IPython.core.guarded_eval import (
214 guarded_eval,
215 EvaluationContext,
216 _validate_policy_overrides,
217 )
218 from IPython.core.error import TryNext, UsageError
219 from IPython.core.inputtransformer2 import ESC_MAGIC
220 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
221 from IPython.testing.skipdoctest import skip_doctest
222 from IPython.utils import generics
223 from IPython.utils.PyColorize import theme_table
224 from IPython.utils.decorators import sphinx_options
225 from IPython.utils.dir2 import dir2, get_real_method
226 from IPython.utils.path import ensure_dir_exists
227 from IPython.utils.process import arg_split
228 from traitlets import (
229 Bool,
230 Enum,
231 Int,
232 List as ListTrait,
233 Unicode,
234 Dict as DictTrait,
235 DottedObjectName,
236 Union as UnionTrait,
237 observe,
238 )
239 from traitlets.config.configurable import Configurable
240 from traitlets.utils.importstring import import_item
241
242 import __main__
243
244 from typing import cast
245
246 from typing import TypedDict, NotRequired, Protocol, TypeAlias, TypeGuard
247
248
249 # skip module docstests
250 __skip_doctest__ = True
251
252
253 try:
254 import jedi
255 jedi.settings.case_insensitive_completion = False
256 import jedi.api.helpers
257 import jedi.api.classes
258 JEDI_INSTALLED = True
259 except ImportError:
260 JEDI_INSTALLED = False
261
262
263 # -----------------------------------------------------------------------------
264 # Globals
265 #-----------------------------------------------------------------------------
266
267 # ranges where we have most of the valid unicode names. We could be more finer
268 # grained but is it worth it for performance While unicode have character in the
269 # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
270 # write this). With below range we cover them all, with a density of ~67%
271 # biggest next gap we consider only adds up about 1% density and there are 600
272 # gaps that would need hard coding.
273 _UNICODE_RANGES = [(32, 0x3347A), (0xE0001, 0xE01F0)]
274
275 # Public API
276 __all__ = ["Completer", "IPCompleter"]
277
278 if sys.platform == 'win32':
279 PROTECTABLES = ' '
280 else:
281 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
282
283 # Protect against returning an enormous number of completions which the frontend
284 # may have trouble processing.
285 MATCHES_LIMIT = 500
286
287 # Completion type reported when no type can be inferred.
288 _UNKNOWN_TYPE = "<unknown>"
289
290 # sentinel value to signal lack of a match
291 not_found = object()
292
293 class ProvisionalCompleterWarning(FutureWarning):
294 """
295 Exception raise by an experimental feature in this module.
296
297 Wrap code in :any:`provisionalcompleter` context manager if you
298 are certain you want to use an unstable feature.
299 """
300 pass
301
302 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
303
304
305 @skip_doctest
306 @contextmanager
307 def provisionalcompleter(action='ignore'):
308 """
309 This context manager has to be used in any place where unstable completer
310 behavior and API may be called.
311
312 >>> with provisionalcompleter():
313 ... completer.do_experimental_things() # works
314
315 >>> completer.do_experimental_things() # raises.
316
317 .. note::
318
319 Unstable
320
321 By using this context manager you agree that the API in use may change
322 without warning, and that you won't complain if they do so.
323
324 You also understand that, if the API is not to your liking, you should report
325 a bug to explain your use case upstream.
326
327 We'll be happy to get your feedback, feature requests, and improvements on
328 any of the unstable APIs!
329 """
330 with warnings.catch_warnings():
331 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
332 yield
333
334
335 def has_open_quotes(s: str) -> Union[str, bool]:
336 """Return whether a string has open quotes.
337
338 This simply counts whether the number of quote characters of either type in
339 the string is odd.
340
341 Returns
342 -------
343 If there is an open quote, the quote character is returned. Else, return
344 False.
345 """
346 # We check " first, then ', so complex cases with nested quotes will get
347 # the " to take precedence.
348 if s.count('"') % 2:
349 return '"'
350 elif s.count("'") % 2:
351 return "'"
352 else:
353 return False
354
355
356 def protect_filename(s: str, protectables: str = PROTECTABLES) -> str:
357 """Escape a string to protect certain characters."""
358 if set(s) & set(protectables):
359 if sys.platform == "win32":
360 return '"' + s + '"'
361 else:
362 return "".join(("\\" + c if c in protectables else c) for c in s)
363 else:
364 return s
365
366
367 def expand_user(path: str) -> tuple[str, bool, str]:
368 """Expand ``~``-style usernames in strings.
369
370 This is similar to :func:`os.path.expanduser`, but it computes and returns
371 extra information that will be useful if the input was being used in
372 computing completions, and you wish to return the completions with the
373 original '~' instead of its expanded value.
374
375 Parameters
376 ----------
377 path : str
378 String to be expanded. If no ~ is present, the output is the same as the
379 input.
380
381 Returns
382 -------
383 newpath : str
384 Result of ~ expansion in the input path.
385 tilde_expand : bool
386 Whether any expansion was performed or not.
387 tilde_val : str
388 The value that ~ was replaced with.
389 """
390 # Default values
391 tilde_expand = False
392 tilde_val = ''
393 newpath = path
394
395 if path.startswith('~'):
396 tilde_expand = True
397 rest = len(path)-1
398 newpath = os.path.expanduser(path)
399 if rest:
400 tilde_val = newpath[:-rest]
401 else:
402 tilde_val = newpath
403
404 return newpath, tilde_expand, tilde_val
405
406
407 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
408 """Does the opposite of expand_user, with its outputs.
409 """
410 if tilde_expand:
411 return path.replace(tilde_val, '~')
412 else:
413 return path
414
415
416 def completions_sorting_key(word):
417 """key for sorting completions
418
419 This does several things:
420
421 - Demote any completions starting with underscores to the end
422 - Insert any %magic and %%cellmagic completions in the alphabetical order
423 by their name
424 """
425 prio1, prio2 = 0, 0
426
427 if word.startswith('__'):
428 prio1 = 2
429 elif word.startswith('_'):
430 prio1 = 1
431
432 if word.endswith('='):
433 prio1 = -1
434
435 if word.startswith('%%'):
436 # If there's another % in there, this is something else, so leave it alone
437 if "%" not in word[2:]:
438 word = word[2:]
439 prio2 = 2
440 elif word.startswith('%'):
441 if "%" not in word[1:]:
442 word = word[1:]
443 prio2 = 1
444
445 return prio1, word, prio2
446
447
448 class _FakeJediCompletion:
449 """
450 This is a workaround to communicate to the UI that Jedi has crashed and to
451 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
452
453 Added in IPython 6.0 so should likely be removed for 7.0
454
455 """
456
457 def __init__(self, name):
458
459 self.name = name
460 self.complete = name
461 self.type = 'crashed'
462 self.name_with_symbols = name
463 self.signature = ""
464 self._origin = "fake"
465 self.text = "crashed"
466
467 def __repr__(self):
468 return '<Fake completion object jedi has crashed>'
469
470
471 _JediCompletionLike = Union["jedi.api.Completion", _FakeJediCompletion]
472
473
474 class Completion:
475 """
476 Completion object used and returned by IPython completers.
477
478 .. warning::
479
480 Unstable
481
482 This function is unstable, API may change without warning.
483 It will also raise unless use in proper context manager.
484
485 This act as a middle ground :any:`Completion` object between the
486 :class:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
487 object. While Jedi need a lot of information about evaluator and how the
488 code should be ran/inspected, PromptToolkit (and other frontend) mostly
489 need user facing information.
490
491 - Which range should be replaced replaced by what.
492 - Some metadata (like completion type), or meta information to displayed to
493 the use user.
494
495 For debugging purpose we can also store the origin of the completion (``jedi``,
496 ``IPython.python_matches``, ``IPython.magics_matches``...).
497 """
498
499 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
500
501 def __init__(
502 self,
503 start: int,
504 end: int,
505 text: str,
506 *,
507 type: Optional[str] = None,
508 _origin="",
509 signature="",
510 ) -> None:
511 warnings.warn(
512 "``Completion`` is a provisional API (as of IPython 6.0). "
513 "It may change without warnings. "
514 "Use in corresponding context manager.",
515 category=ProvisionalCompleterWarning,
516 stacklevel=2,
517 )
518
519 self.start = start
520 self.end = end
521 self.text = text
522 self.type = type
523 self.signature = signature
524 self._origin = _origin
525
526 def __repr__(self):
527 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
528 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
529
530 def __eq__(self, other) -> bool:
531 """
532 Equality and hash do not hash the type (as some completer may not be
533 able to infer the type), but are use to (partially) de-duplicate
534 completion.
535
536 Completely de-duplicating completion is a bit tricker that just
537 comparing as it depends on surrounding text, which Completions are not
538 aware of.
539 """
540 return self.start == other.start and \
541 self.end == other.end and \
542 self.text == other.text
543
544 def __hash__(self):
545 return hash((self.start, self.end, self.text))
546
547
548 class SimpleCompletion:
549 """Completion item to be included in the dictionary returned by new-style Matcher (API v2).
550
551 .. warning::
552
553 Provisional
554
555 This class is used to describe the currently supported attributes of
556 simple completion items, and any additional implementation details
557 should not be relied on. Additional attributes may be included in
558 future versions, and meaning of text disambiguated from the current
559 dual meaning of "text to insert" and "text to used as a label".
560 """
561
562 __slots__ = ["text", "type"]
563
564 def __init__(self, text: str, *, type: Optional[str] = None):
565 self.text = text
566 self.type = type
567
568 def __repr__(self):
569 return f"<SimpleCompletion text={self.text!r} type={self.type!r}>"
570
571
572 class _MatcherResultBase(TypedDict):
573 """Definition of dictionary to be returned by new-style Matcher (API v2)."""
574
575 #: Suffix of the provided ``CompletionContext.token``, if not given defaults to full token.
576 matched_fragment: NotRequired[str]
577
578 #: Whether to suppress results from all other matchers (True), some
579 #: matchers (set of identifiers) or none (False); default is False.
580 suppress: NotRequired[Union[bool, set[str]]]
581
582 #: Identifiers of matchers which should NOT be suppressed when this matcher
583 #: requests to suppress all other matchers; defaults to an empty set.
584 do_not_suppress: NotRequired[set[str]]
585
586 #: Are completions already ordered and should be left as-is? default is False.
587 ordered: NotRequired[bool]
588
589
590 @sphinx_options(show_inherited_members=True, exclude_inherited_from=["dict"])
591 class SimpleMatcherResult(_MatcherResultBase, TypedDict):
592 """Result of new-style completion matcher."""
593
594 # note: TypedDict is added again to the inheritance chain
595 # in order to get __orig_bases__ for documentation
596
597 #: List of candidate completions
598 completions: Sequence[SimpleCompletion] | Iterator[SimpleCompletion]
599
600
601 class _JediMatcherResult(_MatcherResultBase):
602 """Matching result returned by Jedi (will be processed differently)"""
603
604 #: list of candidate completions
605 completions: Iterator[_JediCompletionLike]
606
607
608 AnyMatcherCompletion = Union[_JediCompletionLike, SimpleCompletion]
609 AnyCompletion = TypeVar("AnyCompletion", AnyMatcherCompletion, Completion)
610
611
612 @dataclass
613 class CompletionContext:
614 """Completion context provided as an argument to matchers in the Matcher API v2."""
615
616 # rationale: many legacy matchers relied on completer state (`self.text_until_cursor`)
617 # which was not explicitly visible as an argument of the matcher, making any refactor
618 # prone to errors; by explicitly passing `cursor_position` we can decouple the matchers
619 # from the completer, and make substituting them in sub-classes easier.
620
621 #: Relevant fragment of code directly preceding the cursor.
622 #: The extraction of token is implemented via splitter heuristic
623 #: (following readline behaviour for legacy reasons), which is user configurable
624 #: (by switching the greedy mode).
625 token: str
626
627 #: The full available content of the editor or buffer
628 full_text: str
629
630 #: Cursor position in the line (the same for ``full_text`` and ``text``).
631 cursor_position: int
632
633 #: Cursor line in ``full_text``.
634 cursor_line: int
635
636 #: The maximum number of completions that will be used downstream.
637 #: Matchers can use this information to abort early.
638 #: The built-in Jedi matcher is currently excepted from this limit.
639 # If not given, return all possible completions.
640 limit: Optional[int]
641
642 @cached_property
643 def text_until_cursor(self) -> str:
644 return self.line_with_cursor[: self.cursor_position]
645
646 @cached_property
647 def line_with_cursor(self) -> str:
648 return self.full_text.split("\n")[self.cursor_line]
649
650
651 #: Matcher results for API v2.
652 MatcherResult = Union[SimpleMatcherResult, _JediMatcherResult]
653
654
655 class _MatcherAPIv1Base(Protocol):
656 def __call__(self, text: str) -> list[str]:
657 """Call signature."""
658 ...
659
660 #: Used to construct the default matcher identifier
661 __qualname__: str
662
663
664 class _MatcherAPIv1Total(_MatcherAPIv1Base, Protocol):
665 #: API version
666 matcher_api_version: Optional[Literal[1]]
667
668 def __call__(self, text: str) -> list[str]:
669 """Call signature."""
670 ...
671
672
673 #: Protocol describing Matcher API v1.
674 MatcherAPIv1: TypeAlias = Union[_MatcherAPIv1Base, _MatcherAPIv1Total]
675
676
677 class MatcherAPIv2(Protocol):
678 """Protocol describing Matcher API v2."""
679
680 #: API version
681 matcher_api_version: Literal[2] = 2
682
683 def __call__(self, context: CompletionContext) -> MatcherResult:
684 """Call signature."""
685 ...
686
687 #: Used to construct the default matcher identifier
688 __qualname__: str
689
690
691 Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2]
692
693
694 def _is_matcher_v1(matcher: Matcher) -> TypeGuard[MatcherAPIv1]:
695 api_version = _get_matcher_api_version(matcher)
696 return api_version == 1
697
698
699 def _is_matcher_v2(matcher: Matcher) -> TypeGuard[MatcherAPIv2]:
700 api_version = _get_matcher_api_version(matcher)
701 return api_version == 2
702
703
704 def _is_sizable(value: Any) -> TypeGuard[Sized]:
705 """Determines whether objects is sizable"""
706 return hasattr(value, "__len__")
707
708
709 def _is_iterator(value: Any) -> TypeGuard[Iterator]:
710 """Determines whether objects is sizable"""
711 return hasattr(value, "__next__")
712
713
714 def has_any_completions(result: MatcherResult) -> bool:
715 """Check if any result includes any completions."""
716 completions = result["completions"]
717 if _is_sizable(completions):
718 return len(completions) != 0
719 if _is_iterator(completions):
720 try:
721 old_iterator = completions
722 first = next(old_iterator)
723 result["completions"] = cast(
724 Iterator[SimpleCompletion],
725 itertools.chain([first], old_iterator),
726 )
727 return True
728 except StopIteration:
729 return False
730 raise ValueError(
731 "Completions returned by matcher need to be an Iterator or a Sizable"
732 )
733
734
735 def completion_matcher(
736 *,
737 priority: Optional[float] = None,
738 identifier: Optional[str] = None,
739 api_version: int = 1,
740 ) -> Callable[[Matcher], Matcher]:
741 """Adds attributes describing the matcher.
742
743 Parameters
744 ----------
745 priority : Optional[float]
746 The priority of the matcher, determines the order of execution of matchers.
747 Higher priority means that the matcher will be executed first. Defaults to 0.
748 identifier : Optional[str]
749 identifier of the matcher allowing users to modify the behaviour via traitlets,
750 and also used to for debugging (will be passed as ``origin`` with the completions).
751
752 Defaults to matcher function's ``__qualname__`` (for example,
753 ``IPCompleter.file_matcher`` for the built-in matched defined
754 as a ``file_matcher`` method of the ``IPCompleter`` class).
755 api_version: Optional[int]
756 version of the Matcher API used by this matcher.
757 Currently supported values are 1 and 2.
758 Defaults to 1.
759 """
760
761 def wrapper(func: Matcher):
762 func.matcher_priority = priority or 0 # type: ignore
763 func.matcher_identifier = identifier or func.__qualname__ # type: ignore
764 func.matcher_api_version = api_version # type: ignore
765 if TYPE_CHECKING:
766 if api_version == 1:
767 func = cast(MatcherAPIv1, func)
768 elif api_version == 2:
769 func = cast(MatcherAPIv2, func)
770 return func
771
772 return wrapper
773
774
775 def _get_matcher_priority(matcher: Matcher):
776 return getattr(matcher, "matcher_priority", 0)
777
778
779 def _get_matcher_id(matcher: Matcher):
780 return getattr(matcher, "matcher_identifier", matcher.__qualname__)
781
782
783 def _get_matcher_api_version(matcher):
784 return getattr(matcher, "matcher_api_version", 1)
785
786
787 context_matcher = partial(completion_matcher, api_version=2)
788
789
790 _IC = Iterable[Completion]
791
792
793 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
794 """
795 Deduplicate a set of completions.
796
797 .. warning::
798
799 Unstable
800
801 This function is unstable, API may change without warning.
802
803 Parameters
804 ----------
805 text : str
806 text that should be completed.
807 completions : Iterator[Completion]
808 iterator over the completions to deduplicate
809
810 Yields
811 ------
812 `Completions` objects
813 Completions coming from multiple sources, may be different but end up having
814 the same effect when applied to ``text``. If this is the case, this will
815 consider completions as equal and only emit the first encountered.
816 Not folded in `completions()` yet for debugging purpose, and to detect when
817 the IPython completer does return things that Jedi does not, but should be
818 at some point.
819 """
820 completions = list(completions)
821 if not completions:
822 return
823
824 new_start = min(c.start for c in completions)
825 new_end = max(c.end for c in completions)
826
827 seen = set()
828 for c in completions:
829 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
830 if new_text not in seen:
831 yield c
832 seen.add(new_text)
833
834
835 def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
836 """
837 Rectify a set of completions to all have the same ``start`` and ``end``
838
839 .. warning::
840
841 Unstable
842
843 This function is unstable, API may change without warning.
844 It will also raise unless use in proper context manager.
845
846 Parameters
847 ----------
848 text : str
849 text that should be completed.
850 completions : Iterator[Completion]
851 iterator over the completions to rectify
852 _debug : bool
853 Log failed completion
854
855 Notes
856 -----
857 :class:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
858 the Jupyter Protocol requires them to behave like so. This will readjust
859 the completion to have the same ``start`` and ``end`` by padding both
860 extremities with surrounding text.
861
862 During stabilisation should support a ``_debug`` option to log which
863 completion are return by the IPython completer and not found in Jedi in
864 order to make upstream bug report.
865 """
866 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
867 "It may change without warnings. "
868 "Use in corresponding context manager.",
869 category=ProvisionalCompleterWarning, stacklevel=2)
870
871 completions = list(completions)
872 if not completions:
873 return
874 starts = (c.start for c in completions)
875 ends = (c.end for c in completions)
876
877 new_start = min(starts)
878 new_end = max(ends)
879
880 seen_jedi = set()
881 seen_python_matches = set()
882 for c in completions:
883 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
884 if c._origin == 'jedi':
885 seen_jedi.add(new_text)
886 elif c._origin == "IPCompleter.python_matcher":
887 seen_python_matches.add(new_text)
888 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
889 diff = seen_python_matches.difference(seen_jedi)
890 if diff and _debug:
891 print('IPython.python matches have extras:', diff)
892
893
894 if sys.platform == 'win32':
895 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
896 else:
897 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
898
899 GREEDY_DELIMS = ' =\r\n'
900
901
902 class CompletionSplitter:
903 """An object to split an input line in a manner similar to readline.
904
905 By having our own implementation, we can expose readline-like completion in
906 a uniform manner to all frontends. This object only needs to be given the
907 line of text to be split and the cursor position on said line, and it
908 returns the 'word' to be completed on at the cursor after splitting the
909 entire line.
910
911 What characters are used as splitting delimiters can be controlled by
912 setting the ``delims`` attribute (this is a property that internally
913 automatically builds the necessary regular expression)"""
914
915 # Private interface
916
917 # A string of delimiter characters. The default value makes sense for
918 # IPython's most typical usage patterns.
919 _delims = DELIMS
920
921 # The expression (a normal string) to be compiled into a regular expression
922 # for actual splitting. We store it as an attribute mostly for ease of
923 # debugging, since this type of code can be so tricky to debug.
924 _delim_expr = None
925
926 # The regular expression that does the actual splitting
927 _delim_re = None
928
929 def __init__(self, delims=None):
930 delims = CompletionSplitter._delims if delims is None else delims
931 self.delims = delims
932
933 @property
934 def delims(self):
935 """Return the string of delimiter characters."""
936 return self._delims
937
938 @delims.setter
939 def delims(self, delims):
940 """Set the delimiters for line splitting."""
941 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
942 self._delim_re = re.compile(expr)
943 self._delims = delims
944 self._delim_expr = expr
945
946 def split_line(self, line, cursor_pos=None):
947 """Split a line of text with a cursor at the given position.
948 """
949 cut_line = line if cursor_pos is None else line[:cursor_pos]
950 return self._delim_re.split(cut_line)[-1]
951
952
953 class Completer(Configurable):
954
955 greedy = Bool(
956 False,
957 help="""Activate greedy completion.
958
959 .. deprecated:: 8.8
960 Use :std:configtrait:`Completer.evaluation` and :std:configtrait:`Completer.auto_close_dict_keys` instead.
961
962 When enabled in IPython 8.8 or newer, changes configuration as follows:
963
964 - ``Completer.evaluation = 'unsafe'``
965 - ``Completer.auto_close_dict_keys = True``
966 """,
967 ).tag(config=True)
968
969 evaluation = Enum(
970 ("forbidden", "minimal", "limited", "unsafe", "dangerous"),
971 default_value="limited",
972 help="""Policy for code evaluation under completion.
973
974 Successive options allow to enable more eager evaluation for better
975 completion suggestions, including for nested dictionaries, nested lists,
976 or even results of function calls.
977 Setting ``unsafe`` or higher can lead to evaluation of arbitrary user
978 code on :kbd:`Tab` with potentially unwanted or dangerous side effects.
979
980 Allowed values are:
981
982 - ``forbidden``: no evaluation of code is permitted,
983 - ``minimal``: evaluation of literals and access to built-in namespace;
984 no item/attribute evaluation, no access to locals/globals,
985 no evaluation of any operations or comparisons.
986 - ``limited``: access to all namespaces, evaluation of hard-coded methods
987 (for example: :py:meth:`dict.keys`, :py:meth:`object.__getattr__`,
988 :py:meth:`object.__getitem__`) on allow-listed objects (for example:
989 :py:class:`dict`, :py:class:`list`, :py:class:`tuple`, ``pandas.Series``),
990 - ``unsafe``: evaluation of all methods and function calls but not of
991 syntax with side-effects like `del x`,
992 - ``dangerous``: completely arbitrary evaluation; does not support auto-import.
993
994 To override specific elements of the policy, you can use ``policy_overrides`` trait.
995 """,
996 ).tag(config=True)
997
998 use_jedi = Bool(default_value=JEDI_INSTALLED,
999 help="Experimental: Use Jedi to generate autocompletions. "
1000 "Default to True if jedi is installed.").tag(config=True)
1001
1002 jedi_compute_type_timeout = Int(default_value=400,
1003 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
1004 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
1005 performance by preventing jedi to build its cache.
1006 """).tag(config=True)
1007
1008 debug = Bool(default_value=False,
1009 help='Enable debug for the Completer. Mostly print extra '
1010 'information for experimental jedi integration.')\
1011 .tag(config=True)
1012
1013 backslash_combining_completions = Bool(True,
1014 help="Enable unicode completions, e.g. \\alpha<tab> . "
1015 "Includes completion of latex commands, unicode names, and expanding "
1016 "unicode characters back to latex commands.").tag(config=True)
1017
1018 auto_close_dict_keys = Bool(
1019 False,
1020 help="""
1021 Enable auto-closing dictionary keys.
1022
1023 When enabled string keys will be suffixed with a final quote
1024 (matching the opening quote), tuple keys will also receive a
1025 separating comma if needed, and keys which are final will
1026 receive a closing bracket (``]``).
1027 """,
1028 ).tag(config=True)
1029
1030 policy_overrides = DictTrait(
1031 default_value={},
1032 key_trait=Unicode(),
1033 help="""Overrides for policy evaluation.
1034
1035 For example, to enable auto-import on completion specify:
1036
1037 .. code-block::
1038
1039 ipython --Completer.policy_overrides='{"allow_auto_import": True}' --Completer.use_jedi=False
1040
1041 """,
1042 ).tag(config=True)
1043
1044 @observe("evaluation")
1045 def _evaluation_changed(self, _change):
1046 _validate_policy_overrides(
1047 policy_name=self.evaluation, policy_overrides=self.policy_overrides
1048 )
1049
1050 @observe("policy_overrides")
1051 def _policy_overrides_changed(self, _change):
1052 _validate_policy_overrides(
1053 policy_name=self.evaluation, policy_overrides=self.policy_overrides
1054 )
1055
1056 auto_import_method = DottedObjectName(
1057 default_value="importlib.import_module",
1058 allow_none=True,
1059 help="""\
1060 Provisional:
1061 This is a provisional API in IPython 9.3, it may change without warnings.
1062
1063 A fully qualified path to an auto-import method for use by completer.
1064 The function should take a single string and return `ModuleType` and
1065 can raise `ImportError` exception if module is not found.
1066
1067 The default auto-import implementation does not populate the user namespace with the imported module.
1068 """,
1069 ).tag(config=True)
1070
1071 def __init__(self, namespace=None, global_namespace=None, **kwargs):
1072 """Create a new completer for the command line.
1073
1074 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
1075
1076 If unspecified, the default namespace where completions are performed
1077 is __main__ (technically, __main__.__dict__). Namespaces should be
1078 given as dictionaries.
1079
1080 An optional second namespace can be given. This allows the completer
1081 to handle cases where both the local and global scopes need to be
1082 distinguished.
1083 """
1084
1085 # Don't bind to namespace quite yet, but flag whether the user wants a
1086 # specific namespace or to use __main__.__dict__. This will allow us
1087 # to bind to __main__.__dict__ at completion time, not now.
1088 if namespace is None:
1089 self.use_main_ns = True
1090 else:
1091 self.use_main_ns = False
1092 self.namespace = namespace
1093
1094 # The global namespace, if given, can be bound directly
1095 if global_namespace is None:
1096 self.global_namespace = {}
1097 else:
1098 self.global_namespace = global_namespace
1099
1100 self.custom_matchers = []
1101
1102 super(Completer, self).__init__(**kwargs)
1103
1104 def complete(self, text, state):
1105 """Return the next possible completion for 'text'.
1106
1107 This is called successively with state == 0, 1, 2, ... until it
1108 returns None. The completion should begin with 'text'.
1109
1110 """
1111 if self.use_main_ns:
1112 self.namespace = __main__.__dict__
1113
1114 if state == 0:
1115 if "." in text:
1116 self.matches = self.attr_matches(text)
1117 else:
1118 self.matches = self.global_matches(text)
1119 try:
1120 return self.matches[state]
1121 except IndexError:
1122 return None
1123
1124 def global_matches(self, text: str, context: Optional[CompletionContext] = None):
1125 """Compute matches when text is a simple name.
1126
1127 Return a list of all keywords, built-in functions and names currently
1128 defined in self.namespace or self.global_namespace that match.
1129
1130 """
1131 matches = []
1132 match_append = matches.append
1133 n = len(text)
1134
1135 search_lists = [
1136 keyword.kwlist,
1137 builtin_mod.__dict__.keys(),
1138 list(self.namespace.keys()),
1139 list(self.global_namespace.keys()),
1140 ]
1141 if context and context.full_text.count("\n") > 1:
1142 # try to evaluate on full buffer
1143 previous_lines = "\n".join(
1144 context.full_text.split("\n")[: context.cursor_line]
1145 )
1146 if previous_lines:
1147 all_code_lines_before_cursor = (
1148 self._extract_code(previous_lines) + "\n" + text
1149 )
1150 context = EvaluationContext(
1151 globals=self.global_namespace,
1152 locals=self.namespace,
1153 evaluation=self.evaluation,
1154 auto_import=self._auto_import,
1155 policy_overrides=self.policy_overrides,
1156 )
1157 try:
1158 obj = guarded_eval(
1159 all_code_lines_before_cursor,
1160 context,
1161 )
1162 except Exception as e:
1163 if self.debug:
1164 warnings.warn(f"Evaluation exception {e}")
1165
1166 search_lists.append(list(context.transient_locals.keys()))
1167
1168 for lst in search_lists:
1169 for word in lst:
1170 if word[:n] == text and word != "__builtins__":
1171 match_append(word)
1172
1173 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
1174 for lst in [list(self.namespace.keys()), list(self.global_namespace.keys())]:
1175 shortened = {
1176 "_".join([sub[0] for sub in word.split("_")]): word
1177 for word in lst
1178 if snake_case_re.match(word)
1179 }
1180 for word in shortened.keys():
1181 if word[:n] == text and word != "__builtins__":
1182 match_append(shortened[word])
1183
1184 return matches
1185
1186 def attr_matches(self, text):
1187 """Compute matches when text contains a dot.
1188
1189 Assuming the text is of the form NAME.NAME....[NAME], and is
1190 evaluatable in self.namespace or self.global_namespace, it will be
1191 evaluated and its attributes (as revealed by dir()) are used as
1192 possible completions. (For class instances, class members are
1193 also considered.)
1194
1195 WARNING: this can still invoke arbitrary C code, if an object
1196 with a __getattr__ hook is evaluated.
1197
1198 """
1199 return self._attr_matches(text)[0]
1200
1201 # we simple attribute matching with normal identifiers.
1202 _ATTR_MATCH_RE = re.compile(r"(.+)\.(\w*)$")
1203
1204 def _strip_code_before_operator(self, code: str) -> str:
1205 o_parens = {"(", "[", "{"}
1206 c_parens = {")", "]", "}"}
1207
1208 # Dry-run tokenize to catch errors
1209 try:
1210 _ = list(tokenize.generate_tokens(iter(code.splitlines()).__next__))
1211 except tokenize.TokenError:
1212 # Try trimming the expression and retrying
1213 trimmed_code = self._trim_expr(code)
1214 try:
1215 _ = list(
1216 tokenize.generate_tokens(iter(trimmed_code.splitlines()).__next__)
1217 )
1218 code = trimmed_code
1219 except tokenize.TokenError:
1220 return code
1221
1222 tokens = _parse_tokens(code)
1223 encountered_operator = False
1224 after_operator = []
1225 nesting_level = 0
1226
1227 for t in tokens:
1228 if t.type == tokenize.OP:
1229 if t.string in o_parens:
1230 nesting_level += 1
1231 elif t.string in c_parens:
1232 nesting_level -= 1
1233 elif t.string != "." and nesting_level == 0:
1234 encountered_operator = True
1235 after_operator = []
1236 continue
1237
1238 if encountered_operator:
1239 after_operator.append(t.string)
1240
1241 if encountered_operator:
1242 return "".join(after_operator)
1243 else:
1244 return code
1245
1246 def _extract_code(self, line: str):
1247 """No-op in Completer, but can be used in subclasses to customise behaviour"""
1248 return line
1249
1250 def _attr_matches(
1251 self,
1252 text: str,
1253 include_prefix: bool = True,
1254 context: Optional[CompletionContext] = None,
1255 ) -> tuple[Sequence[str], str]:
1256 m2 = self._ATTR_MATCH_RE.match(text)
1257 if not m2:
1258 return [], ""
1259 expr, attr = m2.group(1, 2)
1260 try:
1261 expr = self._strip_code_before_operator(expr)
1262 except tokenize.TokenError:
1263 pass
1264
1265 obj = self._evaluate_expr(expr)
1266 if obj is not_found:
1267 if context:
1268 # try to evaluate on full buffer
1269 previous_lines = "\n".join(
1270 context.full_text.split("\n")[: context.cursor_line]
1271 )
1272 if previous_lines:
1273 all_code_lines_before_cursor = (
1274 self._extract_code(previous_lines) + "\n" + expr
1275 )
1276 obj = self._evaluate_expr(all_code_lines_before_cursor)
1277
1278 if obj is not_found:
1279 return [], ""
1280
1281 if self.limit_to__all__ and hasattr(obj, '__all__'):
1282 words = get__all__entries(obj)
1283 else:
1284 words = dir2(obj)
1285
1286 try:
1287 words = generics.complete_object(obj, words)
1288 except TryNext:
1289 pass
1290 except AssertionError:
1291 raise
1292 except Exception:
1293 # Silence errors from completion function
1294 pass
1295 # Build match list to return
1296 n = len(attr)
1297
1298 # Note: ideally we would just return words here and the prefix
1299 # reconciliator would know that we intend to append to rather than
1300 # replace the input text; this requires refactoring to return range
1301 # which ought to be replaced (as does jedi).
1302 if include_prefix:
1303 tokens = _parse_tokens(expr)
1304 rev_tokens = reversed(tokens)
1305 skip_over = {tokenize.ENDMARKER, tokenize.NEWLINE}
1306 name_turn = True
1307
1308 parts = []
1309 for token in rev_tokens:
1310 if token.type in skip_over:
1311 continue
1312 if token.type == tokenize.NAME and name_turn:
1313 parts.append(token.string)
1314 name_turn = False
1315 elif (
1316 token.type == tokenize.OP and token.string == "." and not name_turn
1317 ):
1318 parts.append(token.string)
1319 name_turn = True
1320 else:
1321 # short-circuit if not empty nor name token
1322 break
1323
1324 prefix_after_space = "".join(reversed(parts))
1325 else:
1326 prefix_after_space = ""
1327
1328 return (
1329 ["%s.%s" % (prefix_after_space, w) for w in words if w[:n] == attr],
1330 "." + attr,
1331 )
1332
1333 def _trim_expr(self, code: str) -> str:
1334 """
1335 Trim the code until it is a valid expression and not a tuple;
1336
1337 return the trimmed expression for guarded_eval.
1338 """
1339 while code:
1340 code = code[1:]
1341 try:
1342 res = ast.parse(code)
1343 except SyntaxError:
1344 continue
1345
1346 assert res is not None
1347 if len(res.body) != 1:
1348 continue
1349 if not isinstance(res.body[0], ast.Expr):
1350 continue
1351 expr = res.body[0].value
1352 if isinstance(expr, ast.Tuple) and not code[-1] == ")":
1353 # we skip implicit tuple, like when trimming `fun(a,b`<completion>
1354 # as `a,b` would be a tuple, and we actually expect to get only `b`
1355 continue
1356 return code
1357 return ""
1358
1359 def _evaluate_expr(self, expr):
1360 obj = not_found
1361 done = False
1362 while not done and expr:
1363 try:
1364 obj = guarded_eval(
1365 expr,
1366 EvaluationContext(
1367 globals=self.global_namespace,
1368 locals=self.namespace,
1369 evaluation=self.evaluation,
1370 auto_import=self._auto_import,
1371 policy_overrides=self.policy_overrides,
1372 ),
1373 )
1374 done = True
1375 except (SyntaxError, TypeError) as e:
1376 if self.debug:
1377 warnings.warn(f"Trimming because of {e}")
1378 # TypeError can show up with something like `+ d`
1379 # where `d` is a dictionary.
1380
1381 # trim the expression to remove any invalid prefix
1382 # e.g. user starts `(d[`, so we get `expr = '(d'`,
1383 # where parenthesis is not closed.
1384 # TODO: make this faster by reusing parts of the computation?
1385 expr = self._trim_expr(expr)
1386 except Exception as e:
1387 if self.debug:
1388 warnings.warn(f"Evaluation exception {e}")
1389 done = True
1390 if self.debug:
1391 warnings.warn(f"Resolved to {obj}")
1392 return obj
1393
1394 @property
1395 def _auto_import(self):
1396 if self.auto_import_method is None:
1397 return None
1398 if not hasattr(self, "_auto_import_func"):
1399 self._auto_import_func = import_item(self.auto_import_method)
1400 return self._auto_import_func
1401
1402
1403 def get__all__entries(obj):
1404 """returns the strings in the __all__ attribute"""
1405 try:
1406 words = getattr(obj, '__all__')
1407 except Exception:
1408 return []
1409
1410 return [w for w in words if isinstance(w, str)]
1411
1412
1413 class _DictKeyState(enum.Flag):
1414 """Represent state of the key match in context of other possible matches.
1415
1416 - given `d1 = {'a': 1}` completion on `d1['<tab>` will yield `{'a': END_OF_ITEM}` as there is no tuple.
1417 - given `d2 = {('a', 'b'): 1}`: `d2['a', '<tab>` will yield `{'b': END_OF_TUPLE}` as there is no tuple members to add beyond `'b'`.
1418 - given `d3 = {('a', 'b'): 1}`: `d3['<tab>` will yield `{'a': IN_TUPLE}` as `'a'` can be added.
1419 - given `d4 = {'a': 1, ('a', 'b'): 2}`: `d4['<tab>` will yield `{'a': END_OF_ITEM & END_OF_TUPLE}`
1420 """
1421
1422 BASELINE = 0
1423 END_OF_ITEM = enum.auto()
1424 END_OF_TUPLE = enum.auto()
1425 IN_TUPLE = enum.auto()
1426
1427
1428 def _parse_tokens(c):
1429 """Parse tokens even if there is an error."""
1430 tokens = []
1431 token_generator = tokenize.generate_tokens(iter(c.splitlines()).__next__)
1432 while True:
1433 try:
1434 tokens.append(next(token_generator))
1435 except tokenize.TokenError:
1436 return tokens
1437 except StopIteration:
1438 return tokens
1439
1440
1441 def _match_number_in_dict_key_prefix(prefix: str) -> Union[str, None]:
1442 """Match any valid Python numeric literal in a prefix of dictionary keys.
1443
1444 References:
1445 - https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals
1446 - https://docs.python.org/3/library/tokenize.html
1447 """
1448 if prefix[-1].isspace():
1449 # if user typed a space we do not have anything to complete
1450 # even if there was a valid number token before
1451 return None
1452 tokens = _parse_tokens(prefix)
1453 rev_tokens = reversed(tokens)
1454 skip_over = {tokenize.ENDMARKER, tokenize.NEWLINE}
1455 number = None
1456 for token in rev_tokens:
1457 if token.type in skip_over:
1458 continue
1459 if number is None:
1460 if token.type == tokenize.NUMBER:
1461 number = token.string
1462 continue
1463 else:
1464 # we did not match a number
1465 return None
1466 if token.type == tokenize.OP:
1467 if token.string == ",":
1468 break
1469 if token.string in {"+", "-"}:
1470 number = token.string + number
1471 else:
1472 return None
1473 return number
1474
1475
1476 _INT_FORMATS = {
1477 "0b": bin,
1478 "0o": oct,
1479 "0x": hex,
1480 }
1481
1482
1483 def match_dict_keys(
1484 keys: list[Union[str, bytes, tuple[Union[str, bytes], ...]]],
1485 prefix: str,
1486 delims: str,
1487 extra_prefix: Optional[tuple[Union[str, bytes], ...]] = None,
1488 ) -> tuple[str, int, dict[str, _DictKeyState]]:
1489 """Used by dict_key_matches, matching the prefix to a list of keys
1490
1491 Parameters
1492 ----------
1493 keys
1494 list of keys in dictionary currently being completed.
1495 prefix
1496 Part of the text already typed by the user. E.g. `mydict[b'fo`
1497 delims
1498 String of delimiters to consider when finding the current key.
1499 extra_prefix : optional
1500 Part of the text already typed in multi-key index cases. E.g. for
1501 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
1502
1503 Returns
1504 -------
1505 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
1506 ``quote`` being the quote that need to be used to close current string.
1507 ``token_start`` the position where the replacement should start occurring,
1508 ``matches`` a dictionary of replacement/completion keys on keys and values
1509 indicating whether the state.
1510 """
1511 prefix_tuple = extra_prefix if extra_prefix else ()
1512
1513 prefix_tuple_size = sum(
1514 [
1515 # for pandas, do not count slices as taking space
1516 not isinstance(k, slice)
1517 for k in prefix_tuple
1518 ]
1519 )
1520 text_serializable_types = (str, bytes, int, float, slice)
1521
1522 def filter_prefix_tuple(key):
1523 # Reject too short keys
1524 if len(key) <= prefix_tuple_size:
1525 return False
1526 # Reject keys which cannot be serialised to text
1527 for k in key:
1528 if not isinstance(k, text_serializable_types):
1529 return False
1530 # Reject keys that do not match the prefix
1531 for k, pt in zip(key, prefix_tuple):
1532 if k != pt and not isinstance(pt, slice):
1533 return False
1534 # All checks passed!
1535 return True
1536
1537 filtered_key_is_final: dict[
1538 Union[str, bytes, int, float], _DictKeyState
1539 ] = defaultdict(lambda: _DictKeyState.BASELINE)
1540
1541 for k in keys:
1542 # If at least one of the matches is not final, mark as undetermined.
1543 # This can happen with `d = {111: 'b', (111, 222): 'a'}` where
1544 # `111` appears final on first match but is not final on the second.
1545
1546 if isinstance(k, tuple):
1547 if filter_prefix_tuple(k):
1548 key_fragment = k[prefix_tuple_size]
1549 filtered_key_is_final[key_fragment] |= (
1550 _DictKeyState.END_OF_TUPLE
1551 if len(k) == prefix_tuple_size + 1
1552 else _DictKeyState.IN_TUPLE
1553 )
1554 elif prefix_tuple_size > 0:
1555 # we are completing a tuple but this key is not a tuple,
1556 # so we should ignore it
1557 pass
1558 else:
1559 if isinstance(k, text_serializable_types):
1560 filtered_key_is_final[k] |= _DictKeyState.END_OF_ITEM
1561
1562 filtered_keys = filtered_key_is_final.keys()
1563
1564 if not prefix:
1565 return "", 0, {repr(k): v for k, v in filtered_key_is_final.items()}
1566
1567 quote_match = re.search("(?:\"|')", prefix)
1568 is_user_prefix_numeric = False
1569
1570 if quote_match:
1571 quote = quote_match.group()
1572 valid_prefix = prefix + quote
1573 try:
1574 prefix_str = literal_eval(valid_prefix)
1575 except Exception:
1576 return "", 0, {}
1577 else:
1578 # If it does not look like a string, let's assume
1579 # we are dealing with a number or variable.
1580 number_match = _match_number_in_dict_key_prefix(prefix)
1581
1582 # We do not want the key matcher to suggest variable names so we yield:
1583 if number_match is None:
1584 # The alternative would be to assume that user forgort the quote
1585 # and if the substring matches, suggest adding it at the start.
1586 return "", 0, {}
1587
1588 prefix_str = number_match
1589 is_user_prefix_numeric = True
1590 quote = ""
1591
1592 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
1593 token_match = re.search(pattern, prefix, re.UNICODE)
1594 assert token_match is not None # silence mypy
1595 token_start = token_match.start()
1596 token_prefix = token_match.group()
1597
1598 matched: dict[str, _DictKeyState] = {}
1599
1600 str_key: Union[str, bytes]
1601
1602 for key in filtered_keys:
1603 if isinstance(key, (int, float)):
1604 # User typed a number but this key is not a number.
1605 if not is_user_prefix_numeric:
1606 continue
1607 str_key = str(key)
1608 if isinstance(key, int):
1609 int_base = prefix_str[:2].lower()
1610 # if user typed integer using binary/oct/hex notation:
1611 if int_base in _INT_FORMATS:
1612 int_format = _INT_FORMATS[int_base]
1613 str_key = int_format(key)
1614 else:
1615 # User typed a string but this key is a number.
1616 if is_user_prefix_numeric:
1617 continue
1618 str_key = key
1619 try:
1620 if not str_key.startswith(prefix_str):
1621 continue
1622 except (AttributeError, TypeError, UnicodeError):
1623 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
1624 continue
1625
1626 # reformat remainder of key to begin with prefix
1627 rem = str_key[len(prefix_str) :]
1628 # force repr wrapped in '
1629 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
1630 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
1631 if quote == '"':
1632 # The entered prefix is quoted with ",
1633 # but the match is quoted with '.
1634 # A contained " hence needs escaping for comparison:
1635 rem_repr = rem_repr.replace('"', '\\"')
1636
1637 # then reinsert prefix from start of token
1638 match = "%s%s" % (token_prefix, rem_repr)
1639
1640 matched[match] = filtered_key_is_final[key]
1641 return quote, token_start, matched
1642
1643
1644 def cursor_to_position(text:str, line:int, column:int)->int:
1645 """
1646 Convert the (line,column) position of the cursor in text to an offset in a
1647 string.
1648
1649 Parameters
1650 ----------
1651 text : str
1652 The text in which to calculate the cursor offset
1653 line : int
1654 Line of the cursor; 0-indexed
1655 column : int
1656 Column of the cursor 0-indexed
1657
1658 Returns
1659 -------
1660 Position of the cursor in ``text``, 0-indexed.
1661
1662 See Also
1663 --------
1664 position_to_cursor : reciprocal of this function
1665
1666 """
1667 lines = text.split('\n')
1668 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
1669
1670 return sum(len(line) + 1 for line in lines[:line]) + column
1671
1672
1673 def position_to_cursor(text: str, offset: int) -> tuple[int, int]:
1674 """
1675 Convert the position of the cursor in text (0 indexed) to a line
1676 number(0-indexed) and a column number (0-indexed) pair
1677
1678 Position should be a valid position in ``text``.
1679
1680 Parameters
1681 ----------
1682 text : str
1683 The text in which to calculate the cursor offset
1684 offset : int
1685 Position of the cursor in ``text``, 0-indexed.
1686
1687 Returns
1688 -------
1689 (line, column) : (int, int)
1690 Line of the cursor; 0-indexed, column of the cursor 0-indexed
1691
1692 See Also
1693 --------
1694 cursor_to_position : reciprocal of this function
1695
1696 """
1697
1698 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
1699
1700 before = text[:offset]
1701 blines = before.split('\n') # ! splitnes trim trailing \n
1702 line = before.count('\n')
1703 col = len(blines[-1])
1704 return line, col
1705
1706
1707 def _safe_isinstance(obj, module, class_name, *attrs):
1708 """Checks if obj is an instance of module.class_name if loaded
1709 """
1710 if module in sys.modules:
1711 m = sys.modules[module]
1712 for attr in [class_name, *attrs]:
1713 m = getattr(m, attr)
1714 return isinstance(obj, m)
1715
1716
1717 @context_matcher()
1718 def back_unicode_name_matcher(context: CompletionContext):
1719 """Match Unicode characters back to Unicode name
1720
1721 Same as :any:`back_unicode_name_matches`, but adopted to new Matcher API.
1722 """
1723 fragment, matches = back_unicode_name_matches(context.text_until_cursor)
1724 return _convert_matcher_v1_result_to_v2(
1725 matches, type="unicode", fragment=fragment, suppress_if_matches=True
1726 )
1727
1728
1729 def back_unicode_name_matches(text: str) -> tuple[str, Sequence[str]]:
1730 """Match Unicode characters back to Unicode name
1731
1732 This does ``☃`` -> ``\\snowman``
1733
1734 Note that snowman is not a valid python3 combining character but will be expanded.
1735 Though it will not recombine back to the snowman character by the completion machinery.
1736
1737 This will not either back-complete standard sequences like \\n, \\b ...
1738
1739 .. deprecated:: 8.6
1740 You can use :meth:`back_unicode_name_matcher` instead.
1741
1742 Returns
1743 =======
1744
1745 Return a tuple with two elements:
1746
1747 - The Unicode character that was matched (preceded with a backslash), or
1748 empty string,
1749 - a sequence (of 1), name for the match Unicode character, preceded by
1750 backslash, or empty if no match.
1751 """
1752 if len(text)<2:
1753 return '', ()
1754 maybe_slash = text[-2]
1755 if maybe_slash != '\\':
1756 return '', ()
1757
1758 char = text[-1]
1759 # no expand on quote for completion in strings.
1760 # nor backcomplete standard ascii keys
1761 if char in string.ascii_letters or char in ('"',"'"):
1762 return '', ()
1763 try :
1764 unic = unicodedata.name(char)
1765 return '\\'+char,('\\'+unic,)
1766 except KeyError:
1767 pass
1768 return '', ()
1769
1770
1771 @context_matcher()
1772 def back_latex_name_matcher(context: CompletionContext) -> SimpleMatcherResult:
1773 """Match latex characters back to unicode name
1774
1775 This does ``\\ℵ`` -> ``\\aleph``
1776 """
1777
1778 text = context.text_until_cursor
1779 no_match = {
1780 "completions": [],
1781 "suppress": False,
1782 }
1783
1784 if len(text)<2:
1785 return no_match
1786 maybe_slash = text[-2]
1787 if maybe_slash != '\\':
1788 return no_match
1789
1790 char = text[-1]
1791 # no expand on quote for completion in strings.
1792 # nor backcomplete standard ascii keys
1793 if char in string.ascii_letters or char in ('"',"'"):
1794 return no_match
1795 try :
1796 latex = reverse_latex_symbol[char]
1797 # '\\' replace the \ as well
1798 return {
1799 "completions": [SimpleCompletion(text=latex, type="latex")],
1800 "suppress": True,
1801 "matched_fragment": "\\" + char,
1802 }
1803 except KeyError:
1804 pass
1805
1806 return no_match
1807
1808 def _formatparamchildren(parameter) -> str:
1809 """
1810 Get parameter name and value from Jedi Private API
1811
1812 Jedi does not expose a simple way to get `param=value` from its API.
1813
1814 Parameters
1815 ----------
1816 parameter
1817 Jedi's function `Param`
1818
1819 Returns
1820 -------
1821 A string like 'a', 'b=1', '*args', '**kwargs'
1822
1823 """
1824 description = parameter.description
1825 if not description.startswith('param '):
1826 raise ValueError('Jedi function parameter description have change format.'
1827 'Expected "param ...", found %r".' % description)
1828 return description[6:]
1829
1830 def _make_signature(completion)-> str:
1831 """
1832 Make the signature from a jedi completion
1833
1834 Parameters
1835 ----------
1836 completion : jedi.Completion
1837 object does not complete a function type
1838
1839 Returns
1840 -------
1841 a string consisting of the function signature, with the parenthesis but
1842 without the function name. example:
1843 `(a, *args, b=1, **kwargs)`
1844
1845 """
1846
1847 # it looks like this might work on jedi 0.17
1848 if hasattr(completion, 'get_signatures'):
1849 signatures = completion.get_signatures()
1850 if not signatures:
1851 return '(?)'
1852
1853 c0 = completion.get_signatures()[0]
1854 return '('+c0.to_string().split('(', maxsplit=1)[1]
1855
1856 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1857 for p in signature.defined_names()) if f])
1858
1859
1860 _CompleteResult = dict[str, MatcherResult]
1861
1862
1863 DICT_MATCHER_REGEX = re.compile(
1864 r"""(?x)
1865 ( # match dict-referring - or any get item object - expression
1866 .+
1867 )
1868 \[ # open bracket
1869 \s* # and optional whitespace
1870 # Capture any number of serializable objects (e.g. "a", "b", 'c')
1871 # and slices
1872 ((?:(?:
1873 (?: # closed string
1874 [uUbB]? # string prefix (r not handled)
1875 (?:
1876 '(?:[^']|(?<!\\)\\')*'
1877 |
1878 "(?:[^"]|(?<!\\)\\")*"
1879 )
1880 )
1881 |
1882 # capture integers and slices
1883 (?:[-+]?\d+)?(?::(?:[-+]?\d+)?){0,2}
1884 |
1885 # integer in bin/hex/oct notation
1886 0[bBxXoO]_?(?:\w|\d)+
1887 )
1888 \s*,\s*
1889 )*)
1890 ((?:
1891 (?: # unclosed string
1892 [uUbB]? # string prefix (r not handled)
1893 (?:
1894 '(?:[^']|(?<!\\)\\')*
1895 |
1896 "(?:[^"]|(?<!\\)\\")*
1897 )
1898 )
1899 |
1900 # unfinished integer
1901 (?:[-+]?\d+)
1902 |
1903 # integer in bin/hex/oct notation
1904 0[bBxXoO]_?(?:\w|\d)+
1905 )
1906 )?
1907 $
1908 """
1909 )
1910
1911
1912 def _convert_matcher_v1_result_to_v2_no_no(
1913 matches: Sequence[str],
1914 type: str,
1915 ) -> SimpleMatcherResult:
1916 """same as _convert_matcher_v1_result_to_v2 but fragment=None, and suppress_if_matches is False by construction"""
1917 return SimpleMatcherResult(
1918 completions=[SimpleCompletion(text=match, type=type) for match in matches],
1919 suppress=False,
1920 )
1921
1922
1923 def _convert_matcher_v1_result_to_v2(
1924 matches: Sequence[str],
1925 type: str,
1926 fragment: Optional[str] = None,
1927 suppress_if_matches: bool = False,
1928 ) -> SimpleMatcherResult:
1929 """Utility to help with transition"""
1930 result = {
1931 "completions": [SimpleCompletion(text=match, type=type) for match in matches],
1932 "suppress": (True if matches else False) if suppress_if_matches else False,
1933 }
1934 if fragment is not None:
1935 result["matched_fragment"] = fragment
1936 return cast(SimpleMatcherResult, result)
1937
1938
1939 class IPCompleter(Completer):
1940 """Extension of the completer class with IPython-specific features"""
1941
1942 @observe('greedy')
1943 def _greedy_changed(self, change):
1944 """update the splitter and readline delims when greedy is changed"""
1945 if change["new"]:
1946 self.evaluation = "unsafe"
1947 self.auto_close_dict_keys = True
1948 self.splitter.delims = GREEDY_DELIMS
1949 else:
1950 self.evaluation = "limited"
1951 self.auto_close_dict_keys = False
1952 self.splitter.delims = DELIMS
1953
1954 dict_keys_only = Bool(
1955 False,
1956 help="""
1957 Whether to show dict key matches only.
1958
1959 (disables all matchers except for `IPCompleter.dict_key_matcher`).
1960 """,
1961 )
1962
1963 suppress_competing_matchers = UnionTrait(
1964 [Bool(allow_none=True), DictTrait(Bool(None, allow_none=True))],
1965 default_value=None,
1966 help="""
1967 Whether to suppress completions from other *Matchers*.
1968
1969 When set to ``None`` (default) the matchers will attempt to auto-detect
1970 whether suppression of other matchers is desirable. For example, at
1971 the beginning of a line followed by `%` we expect a magic completion
1972 to be the only applicable option, and after ``my_dict['`` we usually
1973 expect a completion with an existing dictionary key.
1974
1975 If you want to disable this heuristic and see completions from all matchers,
1976 set ``IPCompleter.suppress_competing_matchers = False``.
1977 To disable the heuristic for specific matchers provide a dictionary mapping:
1978 ``IPCompleter.suppress_competing_matchers = {'IPCompleter.dict_key_matcher': False}``.
1979
1980 Set ``IPCompleter.suppress_competing_matchers = True`` to limit
1981 completions to the set of matchers with the highest priority;
1982 this is equivalent to ``IPCompleter.merge_completions`` and
1983 can be beneficial for performance, but will sometimes omit relevant
1984 candidates from matchers further down the priority list.
1985 """,
1986 ).tag(config=True)
1987
1988 merge_completions = Bool(
1989 True,
1990 help="""Whether to merge completion results into a single list
1991
1992 If False, only the completion results from the first non-empty
1993 completer will be returned.
1994
1995 As of version 8.6.0, setting the value to ``False`` is an alias for:
1996 ``IPCompleter.suppress_competing_matchers = True.``.
1997 """,
1998 ).tag(config=True)
1999
2000 disable_matchers = ListTrait(
2001 Unicode(),
2002 help="""List of matchers to disable.
2003
2004 The list should contain matcher identifiers (see :any:`completion_matcher`).
2005 """,
2006 ).tag(config=True)
2007
2008 omit__names = Enum(
2009 (0, 1, 2),
2010 default_value=2,
2011 help="""Instruct the completer to omit private method names
2012
2013 Specifically, when completing on ``object.<tab>``.
2014
2015 When 2 [default]: all names that start with '_' will be excluded.
2016
2017 When 1: all 'magic' names (``__foo__``) will be excluded.
2018
2019 When 0: nothing will be excluded.
2020 """
2021 ).tag(config=True)
2022 limit_to__all__ = Bool(False,
2023 help="""
2024 DEPRECATED as of version 5.0.
2025
2026 Instruct the completer to use __all__ for the completion
2027
2028 Specifically, when completing on ``object.<tab>``.
2029
2030 When True: only those names in obj.__all__ will be included.
2031
2032 When False [default]: the __all__ attribute is ignored
2033 """,
2034 ).tag(config=True)
2035
2036 profile_completions = Bool(
2037 default_value=False,
2038 help="If True, emit profiling data for completion subsystem using cProfile."
2039 ).tag(config=True)
2040
2041 profiler_output_dir = Unicode(
2042 default_value=".completion_profiles",
2043 help="Template for path at which to output profile data for completions."
2044 ).tag(config=True)
2045
2046 @observe('limit_to__all__')
2047 def _limit_to_all_changed(self, change):
2048 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
2049 'value has been deprecated since IPython 5.0, will be made to have '
2050 'no effects and then removed in future version of IPython.',
2051 UserWarning)
2052
2053 def __init__(
2054 self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
2055 ):
2056 """IPCompleter() -> completer
2057
2058 Return a completer object.
2059
2060 Parameters
2061 ----------
2062 shell
2063 a pointer to the ipython shell itself. This is needed
2064 because this completer knows about magic functions, and those can
2065 only be accessed via the ipython instance.
2066 namespace : dict, optional
2067 an optional dict where completions are performed.
2068 global_namespace : dict, optional
2069 secondary optional dict for completions, to
2070 handle cases (such as IPython embedded inside functions) where
2071 both Python scopes are visible.
2072 config : Config
2073 traitlet's config object
2074 **kwargs
2075 passed to super class unmodified.
2076 """
2077
2078 self.magic_escape = ESC_MAGIC
2079 self.splitter = CompletionSplitter()
2080
2081 # _greedy_changed() depends on splitter and readline being defined:
2082 super().__init__(
2083 namespace=namespace,
2084 global_namespace=global_namespace,
2085 config=config,
2086 **kwargs,
2087 )
2088
2089 # List where completion matches will be stored
2090 self.matches = []
2091 self.shell = shell
2092 # Regexp to split filenames with spaces in them
2093 self.space_name_re = re.compile(r'([^\\] )')
2094 # Hold a local ref. to glob.glob for speed
2095 self.glob = glob.glob
2096
2097 # Determine if we are running on 'dumb' terminals, like (X)Emacs
2098 # buffers, to avoid completion problems.
2099 term = os.environ.get('TERM','xterm')
2100 self.dumb_terminal = term in ['dumb','emacs']
2101
2102 # Special handling of backslashes needed in win32 platforms
2103 if sys.platform == "win32":
2104 self.clean_glob = self._clean_glob_win32
2105 else:
2106 self.clean_glob = self._clean_glob
2107
2108 #regexp to parse docstring for function signature
2109 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
2110 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
2111 #use this if positional argument name is also needed
2112 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
2113
2114 self.magic_arg_matchers = [
2115 self.magic_config_matcher,
2116 self.magic_color_matcher,
2117 ]
2118
2119 # This is set externally by InteractiveShell
2120 self.custom_completers = None
2121
2122 # This is a list of names of unicode characters that can be completed
2123 # into their corresponding unicode value. The list is large, so we
2124 # lazily initialize it on first use. Consuming code should access this
2125 # attribute through the `@unicode_names` property.
2126 self._unicode_names = None
2127
2128 self._backslash_combining_matchers = [
2129 self.latex_name_matcher,
2130 self.unicode_name_matcher,
2131 back_latex_name_matcher,
2132 back_unicode_name_matcher,
2133 self.fwd_unicode_matcher,
2134 ]
2135
2136 if not self.backslash_combining_completions:
2137 for matcher in self._backslash_combining_matchers:
2138 self.disable_matchers.append(_get_matcher_id(matcher))
2139
2140 if not self.merge_completions:
2141 self.suppress_competing_matchers = True
2142
2143 @property
2144 def matchers(self) -> list[Matcher]:
2145 """All active matcher routines for completion"""
2146 if self.dict_keys_only:
2147 return [self.dict_key_matcher]
2148
2149 if self.use_jedi:
2150 return [
2151 *self.custom_matchers,
2152 *self._backslash_combining_matchers,
2153 *self.magic_arg_matchers,
2154 self.custom_completer_matcher,
2155 self.magic_matcher,
2156 self._jedi_matcher,
2157 self.dict_key_matcher,
2158 self.file_matcher,
2159 ]
2160 else:
2161 return [
2162 *self.custom_matchers,
2163 *self._backslash_combining_matchers,
2164 *self.magic_arg_matchers,
2165 self.custom_completer_matcher,
2166 self.dict_key_matcher,
2167 self.magic_matcher,
2168 self.python_matcher,
2169 self.file_matcher,
2170 self.python_func_kw_matcher,
2171 ]
2172
2173 def all_completions(self, text: str) -> list[str]:
2174 """
2175 Wrapper around the completion methods for the benefit of emacs.
2176 """
2177 prefix = text.rpartition('.')[0]
2178 with provisionalcompleter():
2179 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
2180 for c in self.completions(text, len(text))]
2181
2182 return self.complete(text)[1]
2183
2184 def _clean_glob(self, text:str):
2185 return self.glob("%s*" % text)
2186
2187 def _clean_glob_win32(self, text:str):
2188 return [f.replace("\\","/")
2189 for f in self.glob("%s*" % text)]
2190
2191 @context_matcher()
2192 def file_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2193 """Match filenames, expanding ~USER type strings.
2194
2195 Most of the seemingly convoluted logic in this completer is an
2196 attempt to handle filenames with spaces in them. And yet it's not
2197 quite perfect, because Python's readline doesn't expose all of the
2198 GNU readline details needed for this to be done correctly.
2199
2200 For a filename with a space in it, the printed completions will be
2201 only the parts after what's already been typed (instead of the
2202 full completions, as is normally done). I don't think with the
2203 current (as of Python 2.3) Python readline it's possible to do
2204 better.
2205 """
2206 # TODO: add a heuristic for suppressing (e.g. if it has OS-specific delimiter,
2207 # starts with `/home/`, `C:\`, etc)
2208
2209 text = context.token
2210 code_until_cursor = self._extract_code(context.text_until_cursor)
2211 completion_type = self._determine_completion_context(code_until_cursor)
2212 in_cli_context = self._is_completing_in_cli_context(code_until_cursor)
2213 if (
2214 completion_type == self._CompletionContextType.ATTRIBUTE
2215 and not in_cli_context
2216 ):
2217 return {
2218 "completions": [],
2219 "suppress": False,
2220 }
2221
2222 # chars that require escaping with backslash - i.e. chars
2223 # that readline treats incorrectly as delimiters, but we
2224 # don't want to treat as delimiters in filename matching
2225 # when escaped with backslash
2226 if text.startswith('!'):
2227 text = text[1:]
2228 text_prefix = u'!'
2229 else:
2230 text_prefix = u''
2231
2232 text_until_cursor = self.text_until_cursor
2233 # track strings with open quotes
2234 open_quotes = has_open_quotes(text_until_cursor)
2235
2236 if '(' in text_until_cursor or '[' in text_until_cursor:
2237 lsplit = text
2238 else:
2239 try:
2240 # arg_split ~ shlex.split, but with unicode bugs fixed by us
2241 lsplit = arg_split(text_until_cursor)[-1]
2242 except ValueError:
2243 # typically an unmatched ", or backslash without escaped char.
2244 if open_quotes:
2245 lsplit = text_until_cursor.split(open_quotes)[-1]
2246 else:
2247 return {
2248 "completions": [],
2249 "suppress": False,
2250 }
2251 except IndexError:
2252 # tab pressed on empty line
2253 lsplit = ""
2254
2255 if not open_quotes and lsplit != protect_filename(lsplit):
2256 # if protectables are found, do matching on the whole escaped name
2257 has_protectables = True
2258 text0,text = text,lsplit
2259 else:
2260 has_protectables = False
2261 text = os.path.expanduser(text)
2262
2263 if text == "":
2264 return {
2265 "completions": [
2266 SimpleCompletion(
2267 text=text_prefix + protect_filename(f), type="path"
2268 )
2269 for f in self.glob("*")
2270 ],
2271 "suppress": False,
2272 }
2273
2274 # Compute the matches from the filesystem
2275 if sys.platform == 'win32':
2276 m0 = self.clean_glob(text)
2277 else:
2278 m0 = self.clean_glob(text.replace('\\', ''))
2279
2280 if has_protectables:
2281 # If we had protectables, we need to revert our changes to the
2282 # beginning of filename so that we don't double-write the part
2283 # of the filename we have so far
2284 len_lsplit = len(lsplit)
2285 matches = [text_prefix + text0 +
2286 protect_filename(f[len_lsplit:]) for f in m0]
2287 else:
2288 if open_quotes:
2289 # if we have a string with an open quote, we don't need to
2290 # protect the names beyond the quote (and we _shouldn't_, as
2291 # it would cause bugs when the filesystem call is made).
2292 matches = m0 if sys.platform == "win32" else\
2293 [protect_filename(f, open_quotes) for f in m0]
2294 else:
2295 matches = [text_prefix +
2296 protect_filename(f) for f in m0]
2297
2298 # Mark directories in input list by appending '/' to their names.
2299 return {
2300 "completions": [
2301 SimpleCompletion(text=x + "/" if os.path.isdir(x) else x, type="path")
2302 for x in matches
2303 ],
2304 "suppress": False,
2305 }
2306
2307 def _extract_code(self, line: str) -> str:
2308 """Extract code from magics if any."""
2309
2310 if not line:
2311 return line
2312 maybe_magic, *rest = line.split(maxsplit=1)
2313 if not rest:
2314 return line
2315 args = rest[0]
2316 known_magics = self.shell.magics_manager.lsmagic()
2317 line_magics = known_magics["line"]
2318 magic_name = maybe_magic.lstrip(self.magic_escape)
2319 if magic_name not in line_magics:
2320 return line
2321
2322 if not maybe_magic.startswith(self.magic_escape):
2323 all_variables = [*self.namespace.keys(), *self.global_namespace.keys()]
2324 if magic_name in all_variables:
2325 # short circuit if we see a line starting with say `time`
2326 # but time is defined as a variable (in addition to being
2327 # a magic). In these cases users need to use explicit `%time`.
2328 return line
2329
2330 magic_method = line_magics[magic_name]
2331
2332 try:
2333 if magic_name == "timeit":
2334 opts, stmt = magic_method.__self__.parse_options(
2335 args,
2336 "n:r:tcp:qov:",
2337 posix=False,
2338 strict=False,
2339 preserve_non_opts=True,
2340 )
2341 return stmt
2342 elif magic_name == "prun":
2343 opts, stmt = magic_method.__self__.parse_options(
2344 args, "D:l:rs:T:q", list_all=True, posix=False
2345 )
2346 return stmt
2347 elif hasattr(magic_method, "parser") and getattr(
2348 magic_method, "has_arguments", False
2349 ):
2350 # e.g. %debug, %time
2351 args, extra = magic_method.parser.parse_argstring(args, partial=True)
2352 return " ".join(extra)
2353 except UsageError:
2354 return line
2355
2356 return line
2357
2358 @context_matcher()
2359 def magic_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2360 """Match magics."""
2361
2362 # Get all shell magics now rather than statically, so magics loaded at
2363 # runtime show up too.
2364 text = context.token
2365 lsm = self.shell.magics_manager.lsmagic()
2366 line_magics = lsm['line']
2367 cell_magics = lsm['cell']
2368 pre = self.magic_escape
2369 pre2 = pre + pre
2370
2371 explicit_magic = text.startswith(pre)
2372
2373 # Completion logic:
2374 # - user gives %%: only do cell magics
2375 # - user gives %: do both line and cell magics
2376 # - no prefix: do both
2377 # In other words, line magics are skipped if the user gives %% explicitly
2378 #
2379 # We also exclude magics that match any currently visible names:
2380 # https://github.com/ipython/ipython/issues/4877, unless the user has
2381 # typed a %:
2382 # https://github.com/ipython/ipython/issues/10754
2383 bare_text = text.lstrip(pre)
2384 global_matches = self.global_matches(bare_text)
2385 if not explicit_magic:
2386 def matches(magic):
2387 """
2388 Filter magics, in particular remove magics that match
2389 a name present in global namespace.
2390 """
2391 return ( magic.startswith(bare_text) and
2392 magic not in global_matches )
2393 else:
2394 def matches(magic):
2395 return magic.startswith(bare_text)
2396
2397 completions = [pre2 + m for m in cell_magics if matches(m)]
2398 if not text.startswith(pre2):
2399 completions += [pre + m for m in line_magics if matches(m)]
2400
2401 is_magic_prefix = len(text) > 0 and text[0] == "%"
2402
2403 return {
2404 "completions": [
2405 SimpleCompletion(text=comp, type="magic") for comp in completions
2406 ],
2407 "suppress": is_magic_prefix and len(completions) > 0,
2408 }
2409
2410 @context_matcher()
2411 def magic_config_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2412 """Match class names and attributes for %config magic."""
2413 # NOTE: uses `line_buffer` equivalent for compatibility
2414 matches = self.magic_config_matches(context.line_with_cursor)
2415 return _convert_matcher_v1_result_to_v2_no_no(matches, type="param")
2416
2417 def magic_config_matches(self, text: str) -> list[str]:
2418 """Match class names and attributes for %config magic.
2419
2420 .. deprecated:: 8.6
2421 You can use :meth:`magic_config_matcher` instead.
2422 """
2423 texts = text.strip().split()
2424
2425 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
2426 # get all configuration classes
2427 classes = sorted(set([ c for c in self.shell.configurables
2428 if c.__class__.class_traits(config=True)
2429 ]), key=lambda x: x.__class__.__name__)
2430 classnames = [ c.__class__.__name__ for c in classes ]
2431
2432 # return all classnames if config or %config is given
2433 if len(texts) == 1:
2434 return classnames
2435
2436 # match classname
2437 classname_texts = texts[1].split('.')
2438 classname = classname_texts[0]
2439 classname_matches = [ c for c in classnames
2440 if c.startswith(classname) ]
2441
2442 # return matched classes or the matched class with attributes
2443 if texts[1].find('.') < 0:
2444 return classname_matches
2445 elif len(classname_matches) == 1 and \
2446 classname_matches[0] == classname:
2447 cls = classes[classnames.index(classname)].__class__
2448 help = cls.class_get_help()
2449 # strip leading '--' from cl-args:
2450 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
2451 return [ attr.split('=')[0]
2452 for attr in help.strip().splitlines()
2453 if attr.startswith(texts[1]) ]
2454 return []
2455
2456 @context_matcher()
2457 def magic_color_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2458 """Match color schemes for %colors magic."""
2459 text = context.line_with_cursor
2460 texts = text.split()
2461 if text.endswith(' '):
2462 # .split() strips off the trailing whitespace. Add '' back
2463 # so that: '%colors ' -> ['%colors', '']
2464 texts.append('')
2465
2466 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
2467 prefix = texts[1]
2468 return SimpleMatcherResult(
2469 completions=[
2470 SimpleCompletion(color, type="param")
2471 for color in theme_table.keys()
2472 if color.startswith(prefix)
2473 ],
2474 suppress=False,
2475 )
2476 return SimpleMatcherResult(
2477 completions=[],
2478 suppress=False,
2479 )
2480
2481 @context_matcher(identifier="IPCompleter.jedi_matcher")
2482 def _jedi_matcher(self, context: CompletionContext) -> _JediMatcherResult:
2483 matches = self._jedi_matches(
2484 cursor_column=context.cursor_position,
2485 cursor_line=context.cursor_line,
2486 text=context.full_text,
2487 )
2488 return {
2489 "completions": matches,
2490 # static analysis should not suppress other matcher
2491 # NOTE: file_matcher is automatically suppressed on attribute completions
2492 "suppress": False,
2493 }
2494
2495 def _jedi_matches(
2496 self, cursor_column: int, cursor_line: int, text: str
2497 ) -> Iterator[_JediCompletionLike]:
2498 """
2499 Return a list of :any:`jedi.api.Completion`\\s object from a ``text`` and
2500 cursor position.
2501
2502 Parameters
2503 ----------
2504 cursor_column : int
2505 column position of the cursor in ``text``, 0-indexed.
2506 cursor_line : int
2507 line position of the cursor in ``text``, 0-indexed
2508 text : str
2509 text to complete
2510
2511 Notes
2512 -----
2513 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
2514 object containing a string with the Jedi debug information attached.
2515
2516 .. deprecated:: 8.6
2517 You can use :meth:`_jedi_matcher` instead.
2518 """
2519 namespaces = [self.namespace]
2520 if self.global_namespace is not None:
2521 namespaces.append(self.global_namespace)
2522
2523 completion_filter = lambda x:x
2524 offset = cursor_to_position(text, cursor_line, cursor_column)
2525 # filter output if we are completing for object members
2526 if offset:
2527 pre = text[offset-1]
2528 if pre == '.':
2529 if self.omit__names == 2:
2530 completion_filter = lambda c:not c.name.startswith('_')
2531 elif self.omit__names == 1:
2532 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
2533 elif self.omit__names == 0:
2534 completion_filter = lambda x:x
2535 else:
2536 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
2537
2538 interpreter = jedi.Interpreter(text[:offset], namespaces)
2539 try_jedi = True
2540
2541 try:
2542 # find the first token in the current tree -- if it is a ' or " then we are in a string
2543 completing_string = False
2544 try:
2545 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
2546 except StopIteration:
2547 pass
2548 else:
2549 # note the value may be ', ", or it may also be ''' or """, or
2550 # in some cases, """what/you/typed..., but all of these are
2551 # strings.
2552 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
2553
2554 # if we are in a string jedi is likely not the right candidate for
2555 # now. Skip it.
2556 try_jedi = not completing_string
2557 except Exception as e:
2558 # many of things can go wrong, we are using private API just don't crash.
2559 if self.debug:
2560 print("Error detecting if completing a non-finished string :", e, '|')
2561
2562 if not try_jedi:
2563 return iter([])
2564 try:
2565 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
2566 except Exception as e:
2567 if self.debug:
2568 return iter(
2569 [
2570 _FakeJediCompletion(
2571 'Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""'
2572 % (e)
2573 )
2574 ]
2575 )
2576 else:
2577 return iter([])
2578
2579 class _CompletionContextType(enum.Enum):
2580 ATTRIBUTE = "attribute" # For attribute completion
2581 GLOBAL = "global" # For global completion
2582
2583 def _determine_completion_context(self, line):
2584 """
2585 Determine whether the cursor is in an attribute or global completion context.
2586 """
2587 # Cursor in string/comment → GLOBAL.
2588 is_string, is_in_expression = self._is_in_string_or_comment(line)
2589 if is_string and not is_in_expression:
2590 return self._CompletionContextType.GLOBAL
2591
2592 # If we're in a template string expression, handle specially
2593 if is_string and is_in_expression:
2594 # Extract the expression part - look for the last { that isn't closed
2595 expr_start = line.rfind("{")
2596 if expr_start >= 0:
2597 # We're looking at the expression inside a template string
2598 expr = line[expr_start + 1 :]
2599 # Recursively determine the context of the expression
2600 return self._determine_completion_context(expr)
2601
2602 # Handle plain number literals - should be global context
2603 # Ex: 3. -42.14 but not 3.1.
2604 if re.search(r"(?<!\w)(?<!\d\.)([-+]?\d+\.(\d+)?)(?!\w)$", line):
2605 return self._CompletionContextType.GLOBAL
2606
2607 # Handle all other attribute matches np.ran, d[0].k, (a,b).count, obj._private
2608 chain_match = re.search(r".*(.+(?<!\s)\.(?:[a-zA-Z_]\w*)?)$", line)
2609 if chain_match:
2610 return self._CompletionContextType.ATTRIBUTE
2611
2612 return self._CompletionContextType.GLOBAL
2613
2614 def _is_completing_in_cli_context(self, text: str) -> bool:
2615 """
2616 Determine if we are completing in a CLI alias, line magic, or bang expression context.
2617 """
2618 stripped = text.lstrip()
2619 if stripped.startswith("!") or stripped.startswith("%"):
2620 return True
2621 # Check for CLI aliases
2622 try:
2623 tokens = stripped.split(None, 1)
2624 if not tokens:
2625 return False
2626 first_token = tokens[0]
2627
2628 # Must have arguments after the command for this to apply
2629 if len(tokens) < 2:
2630 return False
2631
2632 # Check if first token is a known alias
2633 if not any(
2634 alias[0] == first_token for alias in self.shell.alias_manager.aliases
2635 ):
2636 return False
2637
2638 try:
2639 if first_token in self.shell.user_ns:
2640 # There's a variable defined, so the alias is overshadowed
2641 return False
2642 except (AttributeError, KeyError):
2643 pass
2644
2645 return True
2646 except Exception:
2647 return False
2648
2649 def _is_in_string_or_comment(self, text):
2650 """
2651 Determine if the cursor is inside a string or comment.
2652 Returns (is_string, is_in_expression) tuple:
2653 - is_string: True if in any kind of string
2654 - is_in_expression: True if inside an f-string/t-string expression
2655 """
2656 in_single_quote = False
2657 in_double_quote = False
2658 in_triple_single = False
2659 in_triple_double = False
2660 in_template_string = False # Covers both f-strings and t-strings
2661 in_expression = False # For expressions in f/t-strings
2662 expression_depth = 0 # Track nested braces in expressions
2663 i = 0
2664
2665 while i < len(text):
2666 # Check for f-string or t-string start
2667 if (
2668 i + 1 < len(text)
2669 and text[i] in ("f", "t")
2670 and (text[i + 1] == '"' or text[i + 1] == "'")
2671 and not (
2672 in_single_quote
2673 or in_double_quote
2674 or in_triple_single
2675 or in_triple_double
2676 )
2677 ):
2678 in_template_string = True
2679 i += 1 # Skip the 'f' or 't'
2680
2681 # Handle triple quotes
2682 if i + 2 < len(text):
2683 if (
2684 text[i : i + 3] == '"""'
2685 and not in_single_quote
2686 and not in_triple_single
2687 ):
2688 in_triple_double = not in_triple_double
2689 if not in_triple_double:
2690 in_template_string = False
2691 i += 3
2692 continue
2693 if (
2694 text[i : i + 3] == "'''"
2695 and not in_double_quote
2696 and not in_triple_double
2697 ):
2698 in_triple_single = not in_triple_single
2699 if not in_triple_single:
2700 in_template_string = False
2701 i += 3
2702 continue
2703
2704 # Handle escapes
2705 if text[i] == "\\" and i + 1 < len(text):
2706 i += 2
2707 continue
2708
2709 # Handle nested braces within f-strings
2710 if in_template_string:
2711 # Special handling for consecutive opening braces
2712 if i + 1 < len(text) and text[i : i + 2] == "{{":
2713 i += 2
2714 continue
2715
2716 # Detect start of an expression
2717 if text[i] == "{":
2718 # Only increment depth and mark as expression if not already in an expression
2719 # or if we're at a top-level nested brace
2720 if not in_expression or (in_expression and expression_depth == 0):
2721 in_expression = True
2722 expression_depth += 1
2723 i += 1
2724 continue
2725
2726 # Detect end of an expression
2727 if text[i] == "}":
2728 expression_depth -= 1
2729 if expression_depth <= 0:
2730 in_expression = False
2731 expression_depth = 0
2732 i += 1
2733 continue
2734
2735 in_triple_quote = in_triple_single or in_triple_double
2736
2737 # Handle quotes - also reset template string when closing quotes are encountered
2738 if text[i] == '"' and not in_single_quote and not in_triple_quote:
2739 in_double_quote = not in_double_quote
2740 if not in_double_quote and not in_triple_quote:
2741 in_template_string = False
2742 elif text[i] == "'" and not in_double_quote and not in_triple_quote:
2743 in_single_quote = not in_single_quote
2744 if not in_single_quote and not in_triple_quote:
2745 in_template_string = False
2746
2747 # Check for comment
2748 if text[i] == "#" and not (
2749 in_single_quote or in_double_quote or in_triple_quote
2750 ):
2751 return True, False
2752
2753 i += 1
2754
2755 is_string = (
2756 in_single_quote or in_double_quote or in_triple_single or in_triple_double
2757 )
2758
2759 # Return tuple (is_string, is_in_expression)
2760 return (
2761 is_string or (in_template_string and not in_expression),
2762 in_expression and expression_depth > 0,
2763 )
2764
2765 @context_matcher()
2766 def python_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2767 """Match attributes or global python names"""
2768 text = context.text_until_cursor
2769 text = self._extract_code(text)
2770 in_cli_context = self._is_completing_in_cli_context(text)
2771 if in_cli_context:
2772 completion_type = self._CompletionContextType.GLOBAL
2773 else:
2774 completion_type = self._determine_completion_context(text)
2775 if completion_type == self._CompletionContextType.ATTRIBUTE:
2776 try:
2777 matches, fragment = self._attr_matches(
2778 text, include_prefix=False, context=context
2779 )
2780 if text.endswith(".") and self.omit__names:
2781 if self.omit__names == 1:
2782 # true if txt is _not_ a __ name, false otherwise:
2783 no__name = lambda txt: re.match(r".*\.__.*?__", txt) is None
2784 else:
2785 # true if txt is _not_ a _ name, false otherwise:
2786 no__name = (
2787 lambda txt: re.match(r"\._.*?", txt[txt.rindex(".") :])
2788 is None
2789 )
2790 matches = filter(no__name, matches)
2791 matches = _convert_matcher_v1_result_to_v2(
2792 matches, type="attribute", fragment=fragment
2793 )
2794 return matches
2795 except NameError:
2796 # catches <undefined attributes>.<tab>
2797 return SimpleMatcherResult(completions=[], suppress=False)
2798 else:
2799 try:
2800 matches = self.global_matches(context.token, context=context)
2801 except TypeError:
2802 matches = self.global_matches(context.token)
2803 # TODO: maybe distinguish between functions, modules and just "variables"
2804 return SimpleMatcherResult(
2805 completions=[
2806 SimpleCompletion(text=match, type="variable") for match in matches
2807 ],
2808 suppress=False,
2809 )
2810
2811 @completion_matcher(api_version=1)
2812 def python_matches(self, text: str) -> Iterable[str]:
2813 """Match attributes or global python names.
2814
2815 .. deprecated:: 8.27
2816 You can use :meth:`python_matcher` instead."""
2817 if "." in text:
2818 try:
2819 matches = self.attr_matches(text)
2820 if text.endswith('.') and self.omit__names:
2821 if self.omit__names == 1:
2822 # true if txt is _not_ a __ name, false otherwise:
2823 no__name = (lambda txt:
2824 re.match(r'.*\.__.*?__',txt) is None)
2825 else:
2826 # true if txt is _not_ a _ name, false otherwise:
2827 no__name = (lambda txt:
2828 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
2829 matches = filter(no__name, matches)
2830 except NameError:
2831 # catches <undefined attributes>.<tab>
2832 matches = []
2833 else:
2834 matches = self.global_matches(text)
2835 return matches
2836
2837 def _default_arguments_from_docstring(self, doc):
2838 """Parse the first line of docstring for call signature.
2839
2840 Docstring should be of the form 'min(iterable[, key=func])\n'.
2841 It can also parse cython docstring of the form
2842 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
2843 """
2844 if doc is None:
2845 return []
2846
2847 #care only the firstline
2848 line = doc.lstrip().splitlines()[0]
2849
2850 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
2851 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
2852 sig = self.docstring_sig_re.search(line)
2853 if sig is None:
2854 return []
2855 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
2856 sig = sig.groups()[0].split(',')
2857 ret = []
2858 for s in sig:
2859 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
2860 ret += self.docstring_kwd_re.findall(s)
2861 return ret
2862
2863 def _default_arguments(self, obj):
2864 """Return the list of default arguments of obj if it is callable,
2865 or empty list otherwise."""
2866 call_obj = obj
2867 ret = []
2868 if inspect.isbuiltin(obj):
2869 pass
2870 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
2871 if inspect.isclass(obj):
2872 #for cython embedsignature=True the constructor docstring
2873 #belongs to the object itself not __init__
2874 ret += self._default_arguments_from_docstring(
2875 getattr(obj, '__doc__', ''))
2876 # for classes, check for __init__,__new__
2877 call_obj = (getattr(obj, '__init__', None) or
2878 getattr(obj, '__new__', None))
2879 # for all others, check if they are __call__able
2880 elif hasattr(obj, '__call__'):
2881 call_obj = obj.__call__
2882 ret += self._default_arguments_from_docstring(
2883 getattr(call_obj, '__doc__', ''))
2884
2885 _keeps = (inspect.Parameter.KEYWORD_ONLY,
2886 inspect.Parameter.POSITIONAL_OR_KEYWORD)
2887
2888 try:
2889 sig = inspect.signature(obj)
2890 ret.extend(k for k, v in sig.parameters.items() if
2891 v.kind in _keeps)
2892 except ValueError:
2893 pass
2894
2895 return list(set(ret))
2896
2897 @context_matcher()
2898 def python_func_kw_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
2899 """Match named parameters (kwargs) of the last open function."""
2900 matches = self.python_func_kw_matches(context.token)
2901 return _convert_matcher_v1_result_to_v2_no_no(matches, type="param")
2902
2903 def python_func_kw_matches(self, text):
2904 """Match named parameters (kwargs) of the last open function.
2905
2906 .. deprecated:: 8.6
2907 You can use :meth:`python_func_kw_matcher` instead.
2908 """
2909
2910 if "." in text: # a parameter cannot be dotted
2911 return []
2912 try: regexp = self.__funcParamsRegex
2913 except AttributeError:
2914 regexp = self.__funcParamsRegex = re.compile(r'''
2915 '.*?(?<!\\)' | # single quoted strings or
2916 ".*?(?<!\\)" | # double quoted strings or
2917 \w+ | # identifier
2918 \S # other characters
2919 ''', re.VERBOSE | re.DOTALL)
2920 # 1. find the nearest identifier that comes before an unclosed
2921 # parenthesis before the cursor
2922 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
2923 tokens = regexp.findall(self.text_until_cursor)
2924 iterTokens = reversed(tokens)
2925 openPar = 0
2926
2927 for token in iterTokens:
2928 if token == ')':
2929 openPar -= 1
2930 elif token == '(':
2931 openPar += 1
2932 if openPar > 0:
2933 # found the last unclosed parenthesis
2934 break
2935 else:
2936 return []
2937 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
2938 ids = []
2939 isId = re.compile(r'\w+$').match
2940
2941 while True:
2942 try:
2943 ids.append(next(iterTokens))
2944 if not isId(ids[-1]):
2945 ids.pop()
2946 break
2947 if not next(iterTokens) == '.':
2948 break
2949 except StopIteration:
2950 break
2951
2952 # Find all named arguments already assigned to, as to avoid suggesting
2953 # them again
2954 usedNamedArgs = set()
2955 par_level = -1
2956 for token, next_token in zip(tokens, tokens[1:]):
2957 if token == '(':
2958 par_level += 1
2959 elif token == ')':
2960 par_level -= 1
2961
2962 if par_level != 0:
2963 continue
2964
2965 if next_token != '=':
2966 continue
2967
2968 usedNamedArgs.add(token)
2969
2970 argMatches = []
2971 try:
2972 callableObj = '.'.join(ids[::-1])
2973 namedArgs = self._default_arguments(eval(callableObj,
2974 self.namespace))
2975
2976 # Remove used named arguments from the list, no need to show twice
2977 for namedArg in set(namedArgs) - usedNamedArgs:
2978 if namedArg.startswith(text):
2979 argMatches.append("%s=" %namedArg)
2980 except:
2981 pass
2982
2983 return argMatches
2984
2985 @staticmethod
2986 def _get_keys(obj: Any) -> list[Any]:
2987 # Objects can define their own completions by defining an
2988 # _ipy_key_completions_() method.
2989 method = get_real_method(obj, '_ipython_key_completions_')
2990 if method is not None:
2991 return method()
2992
2993 # Special case some common in-memory dict-like types
2994 if isinstance(obj, dict) or _safe_isinstance(obj, "pandas", "DataFrame"):
2995 try:
2996 return list(obj.keys())
2997 except Exception:
2998 return []
2999 elif _safe_isinstance(obj, "pandas", "core", "indexing", "_LocIndexer"):
3000 try:
3001 return list(obj.obj.keys())
3002 except Exception:
3003 return []
3004 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
3005 _safe_isinstance(obj, 'numpy', 'void'):
3006 return obj.dtype.names or []
3007 return []
3008
3009 @context_matcher()
3010 def dict_key_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
3011 """Match string keys in a dictionary, after e.g. ``foo[``."""
3012 matches = self.dict_key_matches(context.token)
3013 return _convert_matcher_v1_result_to_v2(
3014 matches, type="dict key", suppress_if_matches=True
3015 )
3016
3017 def dict_key_matches(self, text: str) -> list[str]:
3018 """Match string keys in a dictionary, after e.g. ``foo[``.
3019
3020 .. deprecated:: 8.6
3021 You can use :meth:`dict_key_matcher` instead.
3022 """
3023
3024 # Short-circuit on closed dictionary (regular expression would
3025 # not match anyway, but would take quite a while).
3026 if self.text_until_cursor.strip().endswith("]"):
3027 return []
3028
3029 match = DICT_MATCHER_REGEX.search(self.text_until_cursor)
3030
3031 if match is None:
3032 return []
3033
3034 expr, prior_tuple_keys, key_prefix = match.groups()
3035
3036 obj = self._evaluate_expr(expr)
3037
3038 if obj is not_found:
3039 return []
3040
3041 keys = self._get_keys(obj)
3042 if not keys:
3043 return keys
3044
3045 tuple_prefix = guarded_eval(
3046 prior_tuple_keys,
3047 EvaluationContext(
3048 globals=self.global_namespace,
3049 locals=self.namespace,
3050 evaluation=self.evaluation, # type: ignore
3051 in_subscript=True,
3052 auto_import=self._auto_import,
3053 policy_overrides=self.policy_overrides,
3054 ),
3055 )
3056
3057 closing_quote, token_offset, matches = match_dict_keys(
3058 keys, key_prefix, self.splitter.delims, extra_prefix=tuple_prefix
3059 )
3060 if not matches:
3061 return []
3062
3063 # get the cursor position of
3064 # - the text being completed
3065 # - the start of the key text
3066 # - the start of the completion
3067 text_start = len(self.text_until_cursor) - len(text)
3068 if key_prefix:
3069 key_start = match.start(3)
3070 completion_start = key_start + token_offset
3071 else:
3072 key_start = completion_start = match.end()
3073
3074 # grab the leading prefix, to make sure all completions start with `text`
3075 if text_start > key_start:
3076 leading = ''
3077 else:
3078 leading = text[text_start:completion_start]
3079
3080 # append closing quote and bracket as appropriate
3081 # this is *not* appropriate if the opening quote or bracket is outside
3082 # the text given to this method, e.g. `d["""a\nt
3083 can_close_quote = False
3084 can_close_bracket = False
3085
3086 continuation = self.line_buffer[len(self.text_until_cursor) :].strip()
3087
3088 if continuation.startswith(closing_quote):
3089 # do not close if already closed, e.g. `d['a<tab>'`
3090 continuation = continuation[len(closing_quote) :]
3091 else:
3092 can_close_quote = True
3093
3094 continuation = continuation.strip()
3095
3096 # e.g. `pandas.DataFrame` has different tuple indexer behaviour,
3097 # handling it is out of scope, so let's avoid appending suffixes.
3098 has_known_tuple_handling = isinstance(obj, dict)
3099
3100 can_close_bracket = (
3101 not continuation.startswith("]") and self.auto_close_dict_keys
3102 )
3103 can_close_tuple_item = (
3104 not continuation.startswith(",")
3105 and has_known_tuple_handling
3106 and self.auto_close_dict_keys
3107 )
3108 can_close_quote = can_close_quote and self.auto_close_dict_keys
3109
3110 # fast path if closing quote should be appended but not suffix is allowed
3111 if not can_close_quote and not can_close_bracket and closing_quote:
3112 return [leading + k for k in matches]
3113
3114 results = []
3115
3116 end_of_tuple_or_item = _DictKeyState.END_OF_TUPLE | _DictKeyState.END_OF_ITEM
3117
3118 for k, state_flag in matches.items():
3119 result = leading + k
3120 if can_close_quote and closing_quote:
3121 result += closing_quote
3122
3123 if state_flag == end_of_tuple_or_item:
3124 # We do not know which suffix to add,
3125 # e.g. both tuple item and string
3126 # match this item.
3127 pass
3128
3129 if state_flag in end_of_tuple_or_item and can_close_bracket:
3130 result += "]"
3131 if state_flag == _DictKeyState.IN_TUPLE and can_close_tuple_item:
3132 result += ", "
3133 results.append(result)
3134 return results
3135
3136 @context_matcher()
3137 def unicode_name_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
3138 """Match Latex-like syntax for unicode characters base
3139 on the name of the character.
3140
3141 This does ``\\GREEK SMALL LETTER ETA`` -> ``η``
3142
3143 Works only on valid python 3 identifier, or on combining characters that
3144 will combine to form a valid identifier.
3145 """
3146
3147 text = context.text_until_cursor
3148
3149 slashpos = text.rfind('\\')
3150 if slashpos > -1:
3151 s = text[slashpos+1:]
3152 try :
3153 unic = unicodedata.lookup(s)
3154 # allow combining chars
3155 if ('a'+unic).isidentifier():
3156 return {
3157 "completions": [SimpleCompletion(text=unic, type="unicode")],
3158 "suppress": True,
3159 "matched_fragment": "\\" + s,
3160 }
3161 except KeyError:
3162 pass
3163 return {
3164 "completions": [],
3165 "suppress": False,
3166 }
3167
3168 @context_matcher()
3169 def latex_name_matcher(self, context: CompletionContext):
3170 """Match Latex syntax for unicode characters.
3171
3172 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``
3173 """
3174 fragment, matches = self.latex_matches(context.text_until_cursor)
3175 return _convert_matcher_v1_result_to_v2(
3176 matches, type="latex", fragment=fragment, suppress_if_matches=True
3177 )
3178
3179 def latex_matches(self, text: str) -> tuple[str, Sequence[str]]:
3180 """Match Latex syntax for unicode characters.
3181
3182 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``
3183
3184 .. deprecated:: 8.6
3185 You can use :meth:`latex_name_matcher` instead.
3186 """
3187 slashpos = text.rfind('\\')
3188 if slashpos > -1:
3189 s = text[slashpos:]
3190 if s in latex_symbols:
3191 # Try to complete a full latex symbol to unicode
3192 # \\alpha -> α
3193 return s, [latex_symbols[s]]
3194 else:
3195 # If a user has partially typed a latex symbol, give them
3196 # a full list of options \al -> [\aleph, \alpha]
3197 matches = [k for k in latex_symbols if k.startswith(s)]
3198 if matches:
3199 return s, matches
3200 return '', ()
3201
3202 @context_matcher()
3203 def custom_completer_matcher(self, context):
3204 """Dispatch custom completer.
3205
3206 If a match is found, suppresses all other matchers except for Jedi.
3207 """
3208 matches = self.dispatch_custom_completer(context.token) or []
3209 result = _convert_matcher_v1_result_to_v2(
3210 matches, type=_UNKNOWN_TYPE, suppress_if_matches=True
3211 )
3212 result["ordered"] = True
3213 result["do_not_suppress"] = {_get_matcher_id(self._jedi_matcher)}
3214 return result
3215
3216 def dispatch_custom_completer(self, text):
3217 """
3218 .. deprecated:: 8.6
3219 You can use :meth:`custom_completer_matcher` instead.
3220 """
3221 if not self.custom_completers:
3222 return
3223
3224 line = self.line_buffer
3225 if not line.strip():
3226 return None
3227
3228 # Create a little structure to pass all the relevant information about
3229 # the current completion to any custom completer.
3230 event = SimpleNamespace()
3231 event.line = line
3232 event.symbol = text
3233 cmd = line.split(None,1)[0]
3234 event.command = cmd
3235 event.text_until_cursor = self.text_until_cursor
3236
3237 # for foo etc, try also to find completer for %foo
3238 if not cmd.startswith(self.magic_escape):
3239 try_magic = self.custom_completers.s_matches(
3240 self.magic_escape + cmd)
3241 else:
3242 try_magic = []
3243
3244 for c in itertools.chain(self.custom_completers.s_matches(cmd),
3245 try_magic,
3246 self.custom_completers.flat_matches(self.text_until_cursor)):
3247 try:
3248 res = c(event)
3249 if res:
3250 # first, try case sensitive match
3251 withcase = [r for r in res if r.startswith(text)]
3252 if withcase:
3253 return withcase
3254 # if none, then case insensitive ones are ok too
3255 text_low = text.lower()
3256 return [r for r in res if r.lower().startswith(text_low)]
3257 except TryNext:
3258 pass
3259 except KeyboardInterrupt:
3260 """
3261 If custom completer take too long,
3262 let keyboard interrupt abort and return nothing.
3263 """
3264 break
3265
3266 return None
3267
3268 def completions(self, text: str, offset: int)->Iterator[Completion]:
3269 """
3270 Returns an iterator over the possible completions
3271
3272 .. warning::
3273
3274 Unstable
3275
3276 This function is unstable, API may change without warning.
3277 It will also raise unless use in proper context manager.
3278
3279 Parameters
3280 ----------
3281 text : str
3282 Full text of the current input, multi line string.
3283 offset : int
3284 Integer representing the position of the cursor in ``text``. Offset
3285 is 0-based indexed.
3286
3287 Yields
3288 ------
3289 Completion
3290
3291 Notes
3292 -----
3293 The cursor on a text can either be seen as being "in between"
3294 characters or "On" a character depending on the interface visible to
3295 the user. For consistency the cursor being on "in between" characters X
3296 and Y is equivalent to the cursor being "on" character Y, that is to say
3297 the character the cursor is on is considered as being after the cursor.
3298
3299 Combining characters may span more that one position in the
3300 text.
3301
3302 .. note::
3303
3304 If ``IPCompleter.debug`` is :py:data:`True` will yield a ``--jedi/ipython--``
3305 fake Completion token to distinguish completion returned by Jedi
3306 and usual IPython completion.
3307
3308 .. note::
3309
3310 Completions are not completely deduplicated yet. If identical
3311 completions are coming from different sources this function does not
3312 ensure that each completion object will only be present once.
3313 """
3314 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
3315 "It may change without warnings. "
3316 "Use in corresponding context manager.",
3317 category=ProvisionalCompleterWarning, stacklevel=2)
3318
3319 seen = set()
3320 profiler:Optional[cProfile.Profile]
3321 try:
3322 if self.profile_completions:
3323 import cProfile
3324 profiler = cProfile.Profile()
3325 profiler.enable()
3326 else:
3327 profiler = None
3328
3329 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
3330 if c and (c in seen):
3331 continue
3332 yield c
3333 seen.add(c)
3334 except KeyboardInterrupt:
3335 """if completions take too long and users send keyboard interrupt,
3336 do not crash and return ASAP. """
3337 pass
3338 finally:
3339 if profiler is not None:
3340 profiler.disable()
3341 ensure_dir_exists(self.profiler_output_dir)
3342 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
3343 print("Writing profiler output to", output_path)
3344 profiler.dump_stats(output_path)
3345
3346 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
3347 """
3348 Core completion module.Same signature as :any:`completions`, with the
3349 extra `timeout` parameter (in seconds).
3350
3351 Computing jedi's completion ``.type`` can be quite expensive (it is a
3352 lazy property) and can require some warm-up, more warm up than just
3353 computing the ``name`` of a completion. The warm-up can be :
3354
3355 - Long warm-up the first time a module is encountered after
3356 install/update: actually build parse/inference tree.
3357
3358 - first time the module is encountered in a session: load tree from
3359 disk.
3360
3361 We don't want to block completions for tens of seconds so we give the
3362 completer a "budget" of ``_timeout`` seconds per invocation to compute
3363 completions types, the completions that have not yet been computed will
3364 be marked as "unknown" an will have a chance to be computed next round
3365 are things get cached.
3366
3367 Keep in mind that Jedi is not the only thing treating the completion so
3368 keep the timeout short-ish as if we take more than 0.3 second we still
3369 have lots of processing to do.
3370
3371 """
3372 deadline = time.monotonic() + _timeout
3373
3374 before = full_text[:offset]
3375 cursor_line, cursor_column = position_to_cursor(full_text, offset)
3376
3377 jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
3378
3379 def is_non_jedi_result(
3380 result: MatcherResult, identifier: str
3381 ) -> TypeGuard[SimpleMatcherResult]:
3382 return identifier != jedi_matcher_id
3383
3384 results = self._complete(
3385 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column
3386 )
3387
3388 non_jedi_results: dict[str, SimpleMatcherResult] = {
3389 identifier: result
3390 for identifier, result in results.items()
3391 if is_non_jedi_result(result, identifier)
3392 }
3393
3394 jedi_matches = (
3395 cast(_JediMatcherResult, results[jedi_matcher_id])["completions"]
3396 if jedi_matcher_id in results
3397 else ()
3398 )
3399
3400 iter_jm = iter(jedi_matches)
3401 if _timeout:
3402 for jm in iter_jm:
3403 try:
3404 type_ = jm.type
3405 except Exception:
3406 if self.debug:
3407 print("Error in Jedi getting type of ", jm)
3408 type_ = None
3409 delta = len(jm.name_with_symbols) - len(jm.complete)
3410 if type_ == 'function':
3411 signature = _make_signature(jm)
3412 else:
3413 signature = ''
3414 yield Completion(start=offset - delta,
3415 end=offset,
3416 text=jm.name_with_symbols,
3417 type=type_,
3418 signature=signature,
3419 _origin='jedi')
3420
3421 if time.monotonic() > deadline:
3422 break
3423
3424 for jm in iter_jm:
3425 delta = len(jm.name_with_symbols) - len(jm.complete)
3426 yield Completion(
3427 start=offset - delta,
3428 end=offset,
3429 text=jm.name_with_symbols,
3430 type=_UNKNOWN_TYPE, # don't compute type for speed
3431 _origin="jedi",
3432 signature="",
3433 )
3434
3435 # TODO:
3436 # Suppress this, right now just for debug.
3437 if jedi_matches and non_jedi_results and self.debug:
3438 some_start_offset = before.rfind(
3439 next(iter(non_jedi_results.values()))["matched_fragment"]
3440 )
3441 yield Completion(
3442 start=some_start_offset,
3443 end=offset,
3444 text="--jedi/ipython--",
3445 _origin="debug",
3446 type="none",
3447 signature="",
3448 )
3449
3450 ordered: list[Completion] = []
3451 sortable: list[Completion] = []
3452
3453 for origin, result in non_jedi_results.items():
3454 matched_text = result["matched_fragment"]
3455 start_offset = before.rfind(matched_text)
3456 is_ordered = result.get("ordered", False)
3457 container = ordered if is_ordered else sortable
3458
3459 # I'm unsure if this is always true, so let's assert and see if it
3460 # crash
3461 assert before.endswith(matched_text)
3462
3463 for simple_completion in result["completions"]:
3464 completion = Completion(
3465 start=start_offset,
3466 end=offset,
3467 text=simple_completion.text,
3468 _origin=origin,
3469 signature="",
3470 type=simple_completion.type or _UNKNOWN_TYPE,
3471 )
3472 container.append(completion)
3473
3474 yield from list(self._deduplicate(ordered + self._sort(sortable)))[
3475 :MATCHES_LIMIT
3476 ]
3477
3478 def complete(
3479 self, text=None, line_buffer=None, cursor_pos=None
3480 ) -> tuple[str, Sequence[str]]:
3481 """Find completions for the given text and line context.
3482
3483 Note that both the text and the line_buffer are optional, but at least
3484 one of them must be given.
3485
3486 Parameters
3487 ----------
3488 text : string, optional
3489 Text to perform the completion on. If not given, the line buffer
3490 is split using the instance's CompletionSplitter object.
3491 line_buffer : string, optional
3492 If not given, the completer attempts to obtain the current line
3493 buffer via readline. This keyword allows clients which are
3494 requesting for text completions in non-readline contexts to inform
3495 the completer of the entire text.
3496 cursor_pos : int, optional
3497 Index of the cursor in the full line buffer. Should be provided by
3498 remote frontends where kernel has no access to frontend state.
3499
3500 Returns
3501 -------
3502 Tuple of two items:
3503 text : str
3504 Text that was actually used in the completion.
3505 matches : list
3506 A list of completion matches.
3507
3508 Notes
3509 -----
3510 This API is likely to be deprecated and replaced by
3511 :any:`IPCompleter.completions` in the future.
3512
3513 """
3514 warnings.warn('`Completer.complete` is pending deprecation since '
3515 'IPython 6.0 and will be replaced by `Completer.completions`.',
3516 PendingDeprecationWarning)
3517 # potential todo, FOLD the 3rd throw away argument of _complete
3518 # into the first 2 one.
3519 # TODO: Q: does the above refer to jedi completions (i.e. 0-indexed?)
3520 # TODO: should we deprecate now, or does it stay?
3521
3522 results = self._complete(
3523 line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0
3524 )
3525
3526 jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
3527
3528 return self._arrange_and_extract(
3529 results,
3530 # TODO: can we confirm that excluding Jedi here was a deliberate choice in previous version?
3531 skip_matchers={jedi_matcher_id},
3532 # this API does not support different start/end positions (fragments of token).
3533 abort_if_offset_changes=True,
3534 )
3535
3536 def _arrange_and_extract(
3537 self,
3538 results: dict[str, MatcherResult],
3539 skip_matchers: set[str],
3540 abort_if_offset_changes: bool,
3541 ):
3542 sortable: list[AnyMatcherCompletion] = []
3543 ordered: list[AnyMatcherCompletion] = []
3544 most_recent_fragment = None
3545 for identifier, result in results.items():
3546 if identifier in skip_matchers:
3547 continue
3548 if not result["completions"]:
3549 continue
3550 if not most_recent_fragment:
3551 most_recent_fragment = result["matched_fragment"]
3552 if (
3553 abort_if_offset_changes
3554 and result["matched_fragment"] != most_recent_fragment
3555 ):
3556 break
3557 if result.get("ordered", False):
3558 ordered.extend(result["completions"])
3559 else:
3560 sortable.extend(result["completions"])
3561
3562 if not most_recent_fragment:
3563 most_recent_fragment = "" # to satisfy typechecker (and just in case)
3564
3565 return most_recent_fragment, [
3566 m.text for m in self._deduplicate(ordered + self._sort(sortable))
3567 ]
3568
3569 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
3570 full_text=None) -> _CompleteResult:
3571 """
3572 Like complete but can also returns raw jedi completions as well as the
3573 origin of the completion text. This could (and should) be made much
3574 cleaner but that will be simpler once we drop the old (and stateful)
3575 :any:`complete` API.
3576
3577 With current provisional API, cursor_pos act both (depending on the
3578 caller) as the offset in the ``text`` or ``line_buffer``, or as the
3579 ``column`` when passing multiline strings this could/should be renamed
3580 but would add extra noise.
3581
3582 Parameters
3583 ----------
3584 cursor_line
3585 Index of the line the cursor is on. 0 indexed.
3586 cursor_pos
3587 Position of the cursor in the current line/line_buffer/text. 0
3588 indexed.
3589 line_buffer : optional, str
3590 The current line the cursor is in, this is mostly due to legacy
3591 reason that readline could only give a us the single current line.
3592 Prefer `full_text`.
3593 text : str
3594 The current "token" the cursor is in, mostly also for historical
3595 reasons. as the completer would trigger only after the current line
3596 was parsed.
3597 full_text : str
3598 Full text of the current cell.
3599
3600 Returns
3601 -------
3602 An ordered dictionary where keys are identifiers of completion
3603 matchers and values are ``MatcherResult``s.
3604 """
3605
3606 # if the cursor position isn't given, the only sane assumption we can
3607 # make is that it's at the end of the line (the common case)
3608 if cursor_pos is None:
3609 cursor_pos = len(line_buffer) if text is None else len(text)
3610
3611 if self.use_main_ns:
3612 self.namespace = __main__.__dict__
3613
3614 # if text is either None or an empty string, rely on the line buffer
3615 if (not line_buffer) and full_text:
3616 line_buffer = full_text.split('\n')[cursor_line]
3617 if not text: # issue #11508: check line_buffer before calling split_line
3618 text = (
3619 self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ""
3620 )
3621
3622 # If no line buffer is given, assume the input text is all there was
3623 if line_buffer is None:
3624 line_buffer = text
3625
3626 # deprecated - do not use `line_buffer` in new code.
3627 self.line_buffer = line_buffer
3628 self.text_until_cursor = self.line_buffer[:cursor_pos]
3629
3630 if not full_text:
3631 full_text = line_buffer
3632
3633 context = CompletionContext(
3634 full_text=full_text,
3635 cursor_position=cursor_pos,
3636 cursor_line=cursor_line,
3637 token=self._extract_code(text),
3638 limit=MATCHES_LIMIT,
3639 )
3640
3641 # Start with a clean slate of completions
3642 results: dict[str, MatcherResult] = {}
3643
3644 jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
3645
3646 suppressed_matchers: set[str] = set()
3647
3648 matchers = {
3649 _get_matcher_id(matcher): matcher
3650 for matcher in sorted(
3651 self.matchers, key=_get_matcher_priority, reverse=True
3652 )
3653 }
3654
3655 for matcher_id, matcher in matchers.items():
3656 matcher_id = _get_matcher_id(matcher)
3657
3658 if matcher_id in self.disable_matchers:
3659 continue
3660
3661 if matcher_id in results:
3662 warnings.warn(f"Duplicate matcher ID: {matcher_id}.")
3663
3664 if matcher_id in suppressed_matchers:
3665 continue
3666
3667 result: MatcherResult
3668 try:
3669 if _is_matcher_v1(matcher):
3670 result = _convert_matcher_v1_result_to_v2_no_no(
3671 matcher(text), type=_UNKNOWN_TYPE
3672 )
3673 elif _is_matcher_v2(matcher):
3674 result = matcher(context)
3675 else:
3676 api_version = _get_matcher_api_version(matcher)
3677 raise ValueError(f"Unsupported API version {api_version}")
3678 except BaseException:
3679 # Show the ugly traceback if the matcher causes an
3680 # exception, but do NOT crash the kernel!
3681 sys.excepthook(*sys.exc_info())
3682 continue
3683
3684 # set default value for matched fragment if suffix was not selected.
3685 result["matched_fragment"] = result.get("matched_fragment", context.token)
3686
3687 if not suppressed_matchers:
3688 suppression_recommended: Union[bool, set[str]] = result.get(
3689 "suppress", False
3690 )
3691
3692 suppression_config = (
3693 self.suppress_competing_matchers.get(matcher_id, None)
3694 if isinstance(self.suppress_competing_matchers, dict)
3695 else self.suppress_competing_matchers
3696 )
3697 should_suppress = (
3698 (suppression_config is True)
3699 or (suppression_recommended and (suppression_config is not False))
3700 ) and has_any_completions(result)
3701
3702 if should_suppress:
3703 suppression_exceptions: set[str] = result.get(
3704 "do_not_suppress", set()
3705 )
3706 if isinstance(suppression_recommended, Iterable):
3707 to_suppress = set(suppression_recommended)
3708 else:
3709 to_suppress = set(matchers)
3710 suppressed_matchers = to_suppress - suppression_exceptions
3711
3712 new_results = {}
3713 for previous_matcher_id, previous_result in results.items():
3714 if previous_matcher_id not in suppressed_matchers:
3715 new_results[previous_matcher_id] = previous_result
3716 results = new_results
3717
3718 results[matcher_id] = result
3719
3720 _, matches = self._arrange_and_extract(
3721 results,
3722 # TODO Jedi completions non included in legacy stateful API; was this deliberate or omission?
3723 # if it was omission, we can remove the filtering step, otherwise remove this comment.
3724 skip_matchers={jedi_matcher_id},
3725 abort_if_offset_changes=False,
3726 )
3727
3728 # populate legacy stateful API
3729 self.matches = matches
3730
3731 return results
3732
3733 @staticmethod
3734 def _deduplicate(
3735 matches: Sequence[AnyCompletion],
3736 ) -> Iterable[AnyCompletion]:
3737 filtered_matches: dict[str, AnyCompletion] = {}
3738 for match in matches:
3739 text = match.text
3740 if (
3741 text not in filtered_matches
3742 or filtered_matches[text].type == _UNKNOWN_TYPE
3743 ):
3744 filtered_matches[text] = match
3745
3746 return filtered_matches.values()
3747
3748 @staticmethod
3749 def _sort(matches: Sequence[AnyCompletion]):
3750 return sorted(matches, key=lambda x: completions_sorting_key(x.text))
3751
3752 @context_matcher()
3753 def fwd_unicode_matcher(self, context: CompletionContext):
3754 """Same as :any:`fwd_unicode_match`, but adopted to new Matcher API."""
3755 # TODO: use `context.limit` to terminate early once we matched the maximum
3756 # number that will be used downstream; can be added as an optional to
3757 # `fwd_unicode_match(text: str, limit: int = None)` or we could re-implement here.
3758 fragment, matches = self.fwd_unicode_match(context.text_until_cursor)
3759 return _convert_matcher_v1_result_to_v2(
3760 matches, type="unicode", fragment=fragment, suppress_if_matches=True
3761 )
3762
3763 def fwd_unicode_match(self, text: str) -> tuple[str, Sequence[str]]:
3764 """
3765 Forward match a string starting with a backslash with a list of
3766 potential Unicode completions.
3767
3768 Will compute list of Unicode character names on first call and cache it.
3769
3770 .. deprecated:: 8.6
3771 You can use :meth:`fwd_unicode_matcher` instead.
3772
3773 Returns
3774 -------
3775 At tuple with:
3776 - matched text (empty if no matches)
3777 - list of potential completions, empty tuple otherwise)
3778 """
3779 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
3780 # We could do a faster match using a Trie.
3781
3782 # Using pygtrie the following seem to work:
3783
3784 # s = PrefixSet()
3785
3786 # for c in range(0,0x10FFFF + 1):
3787 # try:
3788 # s.add(unicodedata.name(chr(c)))
3789 # except ValueError:
3790 # pass
3791 # [''.join(k) for k in s.iter(prefix)]
3792
3793 # But need to be timed and adds an extra dependency.
3794
3795 slashpos = text.rfind('\\')
3796 # if text starts with slash
3797 if slashpos > -1:
3798 # PERF: It's important that we don't access self._unicode_names
3799 # until we're inside this if-block. _unicode_names is lazily
3800 # initialized, and it takes a user-noticeable amount of time to
3801 # initialize it, so we don't want to initialize it unless we're
3802 # actually going to use it.
3803 s = text[slashpos + 1 :]
3804 sup = s.upper()
3805 candidates = [x for x in self.unicode_names if x.startswith(sup)]
3806 if candidates:
3807 return s, candidates
3808 candidates = [x for x in self.unicode_names if sup in x]
3809 if candidates:
3810 return s, candidates
3811 splitsup = sup.split(" ")
3812 candidates = [
3813 x for x in self.unicode_names if all(u in x for u in splitsup)
3814 ]
3815 if candidates:
3816 return s, candidates
3817
3818 return "", ()
3819
3820 # if text does not start with slash
3821 else:
3822 return '', ()
3823
3824 @property
3825 def unicode_names(self) -> list[str]:
3826 """List of names of unicode code points that can be completed.
3827
3828 The list is lazily initialized on first access.
3829 """
3830 if self._unicode_names is None:
3831 names = []
3832 for c in range(0,0x10FFFF + 1):
3833 try:
3834 names.append(unicodedata.name(chr(c)))
3835 except ValueError:
3836 pass
3837 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
3838
3839 return self._unicode_names
3840
3841
3842 def _unicode_name_compute(ranges: list[tuple[int, int]]) -> list[str]:
3843 names = []
3844 for start,stop in ranges:
3845 for c in range(start, stop) :
3846 try:
3847 names.append(unicodedata.name(chr(c)))
3848 except ValueError:
3849 pass
3850 return names