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