Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/IPython/core/completer.py: 19%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1433 statements  

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": {_get_matcher_id(self.file_matcher)} if matches else 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 matches = _convert_matcher_v1_result_to_v2( 

2745 matches, type="attribute", fragment=fragment 

2746 ) 

2747 if matches["completions"]: 

2748 matches["suppress"] = {_get_matcher_id(self.file_matcher)} 

2749 return matches 

2750 except NameError: 

2751 # catches <undefined attributes>.<tab> 

2752 return SimpleMatcherResult(completions=[], suppress=False) 

2753 else: 

2754 try: 

2755 matches = self.global_matches(context.token, context=context) 

2756 except TypeError: 

2757 matches = self.global_matches(context.token) 

2758 # TODO: maybe distinguish between functions, modules and just "variables" 

2759 return SimpleMatcherResult( 

2760 completions=[ 

2761 SimpleCompletion(text=match, type="variable") for match in matches 

2762 ], 

2763 suppress=False, 

2764 ) 

2765 

2766 @completion_matcher(api_version=1) 

2767 def python_matches(self, text: str) -> Iterable[str]: 

2768 """Match attributes or global python names. 

2769 

2770 .. deprecated:: 8.27 

2771 You can use :meth:`python_matcher` instead.""" 

2772 if "." in text: 

2773 try: 

2774 matches = self.attr_matches(text) 

2775 if text.endswith('.') and self.omit__names: 

2776 if self.omit__names == 1: 

2777 # true if txt is _not_ a __ name, false otherwise: 

2778 no__name = (lambda txt: 

2779 re.match(r'.*\.__.*?__',txt) is None) 

2780 else: 

2781 # true if txt is _not_ a _ name, false otherwise: 

2782 no__name = (lambda txt: 

2783 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) 

2784 matches = filter(no__name, matches) 

2785 except NameError: 

2786 # catches <undefined attributes>.<tab> 

2787 matches = [] 

2788 else: 

2789 matches = self.global_matches(text) 

2790 return matches 

2791 

2792 def _default_arguments_from_docstring(self, doc): 

2793 """Parse the first line of docstring for call signature. 

2794 

2795 Docstring should be of the form 'min(iterable[, key=func])\n'. 

2796 It can also parse cython docstring of the form 

2797 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. 

2798 """ 

2799 if doc is None: 

2800 return [] 

2801 

2802 #care only the firstline 

2803 line = doc.lstrip().splitlines()[0] 

2804 

2805 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') 

2806 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' 

2807 sig = self.docstring_sig_re.search(line) 

2808 if sig is None: 

2809 return [] 

2810 # iterable[, key=func]' -> ['iterable[' ,' key=func]'] 

2811 sig = sig.groups()[0].split(',') 

2812 ret = [] 

2813 for s in sig: 

2814 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') 

2815 ret += self.docstring_kwd_re.findall(s) 

2816 return ret 

2817 

2818 def _default_arguments(self, obj): 

2819 """Return the list of default arguments of obj if it is callable, 

2820 or empty list otherwise.""" 

2821 call_obj = obj 

2822 ret = [] 

2823 if inspect.isbuiltin(obj): 

2824 pass 

2825 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): 

2826 if inspect.isclass(obj): 

2827 #for cython embedsignature=True the constructor docstring 

2828 #belongs to the object itself not __init__ 

2829 ret += self._default_arguments_from_docstring( 

2830 getattr(obj, '__doc__', '')) 

2831 # for classes, check for __init__,__new__ 

2832 call_obj = (getattr(obj, '__init__', None) or 

2833 getattr(obj, '__new__', None)) 

2834 # for all others, check if they are __call__able 

2835 elif hasattr(obj, '__call__'): 

2836 call_obj = obj.__call__ 

2837 ret += self._default_arguments_from_docstring( 

2838 getattr(call_obj, '__doc__', '')) 

2839 

2840 _keeps = (inspect.Parameter.KEYWORD_ONLY, 

2841 inspect.Parameter.POSITIONAL_OR_KEYWORD) 

2842 

2843 try: 

2844 sig = inspect.signature(obj) 

2845 ret.extend(k for k, v in sig.parameters.items() if 

2846 v.kind in _keeps) 

2847 except ValueError: 

2848 pass 

2849 

2850 return list(set(ret)) 

2851 

2852 @context_matcher() 

2853 def python_func_kw_matcher(self, context: CompletionContext) -> SimpleMatcherResult: 

2854 """Match named parameters (kwargs) of the last open function.""" 

2855 matches = self.python_func_kw_matches(context.token) 

2856 return _convert_matcher_v1_result_to_v2_no_no(matches, type="param") 

2857 

2858 def python_func_kw_matches(self, text): 

2859 """Match named parameters (kwargs) of the last open function. 

2860 

2861 .. deprecated:: 8.6 

2862 You can use :meth:`python_func_kw_matcher` instead. 

2863 """ 

2864 

2865 if "." in text: # a parameter cannot be dotted 

2866 return [] 

2867 try: regexp = self.__funcParamsRegex 

2868 except AttributeError: 

2869 regexp = self.__funcParamsRegex = re.compile(r''' 

2870 '.*?(?<!\\)' | # single quoted strings or 

2871 ".*?(?<!\\)" | # double quoted strings or 

2872 \w+ | # identifier 

2873 \S # other characters 

2874 ''', re.VERBOSE | re.DOTALL) 

2875 # 1. find the nearest identifier that comes before an unclosed 

2876 # parenthesis before the cursor 

2877 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" 

2878 tokens = regexp.findall(self.text_until_cursor) 

2879 iterTokens = reversed(tokens) 

2880 openPar = 0 

2881 

2882 for token in iterTokens: 

2883 if token == ')': 

2884 openPar -= 1 

2885 elif token == '(': 

2886 openPar += 1 

2887 if openPar > 0: 

2888 # found the last unclosed parenthesis 

2889 break 

2890 else: 

2891 return [] 

2892 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) 

2893 ids = [] 

2894 isId = re.compile(r'\w+$').match 

2895 

2896 while True: 

2897 try: 

2898 ids.append(next(iterTokens)) 

2899 if not isId(ids[-1]): 

2900 ids.pop() 

2901 break 

2902 if not next(iterTokens) == '.': 

2903 break 

2904 except StopIteration: 

2905 break 

2906 

2907 # Find all named arguments already assigned to, as to avoid suggesting 

2908 # them again 

2909 usedNamedArgs = set() 

2910 par_level = -1 

2911 for token, next_token in zip(tokens, tokens[1:]): 

2912 if token == '(': 

2913 par_level += 1 

2914 elif token == ')': 

2915 par_level -= 1 

2916 

2917 if par_level != 0: 

2918 continue 

2919 

2920 if next_token != '=': 

2921 continue 

2922 

2923 usedNamedArgs.add(token) 

2924 

2925 argMatches = [] 

2926 try: 

2927 callableObj = '.'.join(ids[::-1]) 

2928 namedArgs = self._default_arguments(eval(callableObj, 

2929 self.namespace)) 

2930 

2931 # Remove used named arguments from the list, no need to show twice 

2932 for namedArg in set(namedArgs) - usedNamedArgs: 

2933 if namedArg.startswith(text): 

2934 argMatches.append("%s=" %namedArg) 

2935 except: 

2936 pass 

2937 

2938 return argMatches 

2939 

2940 @staticmethod 

2941 def _get_keys(obj: Any) -> list[Any]: 

2942 # Objects can define their own completions by defining an 

2943 # _ipy_key_completions_() method. 

2944 method = get_real_method(obj, '_ipython_key_completions_') 

2945 if method is not None: 

2946 return method() 

2947 

2948 # Special case some common in-memory dict-like types 

2949 if isinstance(obj, dict) or _safe_isinstance(obj, "pandas", "DataFrame"): 

2950 try: 

2951 return list(obj.keys()) 

2952 except Exception: 

2953 return [] 

2954 elif _safe_isinstance(obj, "pandas", "core", "indexing", "_LocIndexer"): 

2955 try: 

2956 return list(obj.obj.keys()) 

2957 except Exception: 

2958 return [] 

2959 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ 

2960 _safe_isinstance(obj, 'numpy', 'void'): 

2961 return obj.dtype.names or [] 

2962 return [] 

2963 

2964 @context_matcher() 

2965 def dict_key_matcher(self, context: CompletionContext) -> SimpleMatcherResult: 

2966 """Match string keys in a dictionary, after e.g. ``foo[``.""" 

2967 matches = self.dict_key_matches(context.token) 

2968 return _convert_matcher_v1_result_to_v2( 

2969 matches, type="dict key", suppress_if_matches=True 

2970 ) 

2971 

2972 def dict_key_matches(self, text: str) -> list[str]: 

2973 """Match string keys in a dictionary, after e.g. ``foo[``. 

2974 

2975 .. deprecated:: 8.6 

2976 You can use :meth:`dict_key_matcher` instead. 

2977 """ 

2978 

2979 # Short-circuit on closed dictionary (regular expression would 

2980 # not match anyway, but would take quite a while). 

2981 if self.text_until_cursor.strip().endswith("]"): 

2982 return [] 

2983 

2984 match = DICT_MATCHER_REGEX.search(self.text_until_cursor) 

2985 

2986 if match is None: 

2987 return [] 

2988 

2989 expr, prior_tuple_keys, key_prefix = match.groups() 

2990 

2991 obj = self._evaluate_expr(expr) 

2992 

2993 if obj is not_found: 

2994 return [] 

2995 

2996 keys = self._get_keys(obj) 

2997 if not keys: 

2998 return keys 

2999 

3000 tuple_prefix = guarded_eval( 

3001 prior_tuple_keys, 

3002 EvaluationContext( 

3003 globals=self.global_namespace, 

3004 locals=self.namespace, 

3005 evaluation=self.evaluation, # type: ignore 

3006 in_subscript=True, 

3007 auto_import=self._auto_import, 

3008 policy_overrides=self.policy_overrides, 

3009 ), 

3010 ) 

3011 

3012 closing_quote, token_offset, matches = match_dict_keys( 

3013 keys, key_prefix, self.splitter.delims, extra_prefix=tuple_prefix 

3014 ) 

3015 if not matches: 

3016 return [] 

3017 

3018 # get the cursor position of 

3019 # - the text being completed 

3020 # - the start of the key text 

3021 # - the start of the completion 

3022 text_start = len(self.text_until_cursor) - len(text) 

3023 if key_prefix: 

3024 key_start = match.start(3) 

3025 completion_start = key_start + token_offset 

3026 else: 

3027 key_start = completion_start = match.end() 

3028 

3029 # grab the leading prefix, to make sure all completions start with `text` 

3030 if text_start > key_start: 

3031 leading = '' 

3032 else: 

3033 leading = text[text_start:completion_start] 

3034 

3035 # append closing quote and bracket as appropriate 

3036 # this is *not* appropriate if the opening quote or bracket is outside 

3037 # the text given to this method, e.g. `d["""a\nt 

3038 can_close_quote = False 

3039 can_close_bracket = False 

3040 

3041 continuation = self.line_buffer[len(self.text_until_cursor) :].strip() 

3042 

3043 if continuation.startswith(closing_quote): 

3044 # do not close if already closed, e.g. `d['a<tab>'` 

3045 continuation = continuation[len(closing_quote) :] 

3046 else: 

3047 can_close_quote = True 

3048 

3049 continuation = continuation.strip() 

3050 

3051 # e.g. `pandas.DataFrame` has different tuple indexer behaviour, 

3052 # handling it is out of scope, so let's avoid appending suffixes. 

3053 has_known_tuple_handling = isinstance(obj, dict) 

3054 

3055 can_close_bracket = ( 

3056 not continuation.startswith("]") and self.auto_close_dict_keys 

3057 ) 

3058 can_close_tuple_item = ( 

3059 not continuation.startswith(",") 

3060 and has_known_tuple_handling 

3061 and self.auto_close_dict_keys 

3062 ) 

3063 can_close_quote = can_close_quote and self.auto_close_dict_keys 

3064 

3065 # fast path if closing quote should be appended but not suffix is allowed 

3066 if not can_close_quote and not can_close_bracket and closing_quote: 

3067 return [leading + k for k in matches] 

3068 

3069 results = [] 

3070 

3071 end_of_tuple_or_item = _DictKeyState.END_OF_TUPLE | _DictKeyState.END_OF_ITEM 

3072 

3073 for k, state_flag in matches.items(): 

3074 result = leading + k 

3075 if can_close_quote and closing_quote: 

3076 result += closing_quote 

3077 

3078 if state_flag == end_of_tuple_or_item: 

3079 # We do not know which suffix to add, 

3080 # e.g. both tuple item and string 

3081 # match this item. 

3082 pass 

3083 

3084 if state_flag in end_of_tuple_or_item and can_close_bracket: 

3085 result += "]" 

3086 if state_flag == _DictKeyState.IN_TUPLE and can_close_tuple_item: 

3087 result += ", " 

3088 results.append(result) 

3089 return results 

3090 

3091 @context_matcher() 

3092 def unicode_name_matcher(self, context: CompletionContext) -> SimpleMatcherResult: 

3093 """Match Latex-like syntax for unicode characters base 

3094 on the name of the character. 

3095 

3096 This does ``\\GREEK SMALL LETTER ETA`` -> ``η`` 

3097 

3098 Works only on valid python 3 identifier, or on combining characters that 

3099 will combine to form a valid identifier. 

3100 """ 

3101 

3102 text = context.text_until_cursor 

3103 

3104 slashpos = text.rfind('\\') 

3105 if slashpos > -1: 

3106 s = text[slashpos+1:] 

3107 try : 

3108 unic = unicodedata.lookup(s) 

3109 # allow combining chars 

3110 if ('a'+unic).isidentifier(): 

3111 return { 

3112 "completions": [SimpleCompletion(text=unic, type="unicode")], 

3113 "suppress": True, 

3114 "matched_fragment": "\\" + s, 

3115 } 

3116 except KeyError: 

3117 pass 

3118 return { 

3119 "completions": [], 

3120 "suppress": False, 

3121 } 

3122 

3123 @context_matcher() 

3124 def latex_name_matcher(self, context: CompletionContext): 

3125 """Match Latex syntax for unicode characters. 

3126 

3127 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α`` 

3128 """ 

3129 fragment, matches = self.latex_matches(context.text_until_cursor) 

3130 return _convert_matcher_v1_result_to_v2( 

3131 matches, type="latex", fragment=fragment, suppress_if_matches=True 

3132 ) 

3133 

3134 def latex_matches(self, text: str) -> tuple[str, Sequence[str]]: 

3135 """Match Latex syntax for unicode characters. 

3136 

3137 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α`` 

3138 

3139 .. deprecated:: 8.6 

3140 You can use :meth:`latex_name_matcher` instead. 

3141 """ 

3142 slashpos = text.rfind('\\') 

3143 if slashpos > -1: 

3144 s = text[slashpos:] 

3145 if s in latex_symbols: 

3146 # Try to complete a full latex symbol to unicode 

3147 # \\alpha -> α 

3148 return s, [latex_symbols[s]] 

3149 else: 

3150 # If a user has partially typed a latex symbol, give them 

3151 # a full list of options \al -> [\aleph, \alpha] 

3152 matches = [k for k in latex_symbols if k.startswith(s)] 

3153 if matches: 

3154 return s, matches 

3155 return '', () 

3156 

3157 @context_matcher() 

3158 def custom_completer_matcher(self, context): 

3159 """Dispatch custom completer. 

3160 

3161 If a match is found, suppresses all other matchers except for Jedi. 

3162 """ 

3163 matches = self.dispatch_custom_completer(context.token) or [] 

3164 result = _convert_matcher_v1_result_to_v2( 

3165 matches, type=_UNKNOWN_TYPE, suppress_if_matches=True 

3166 ) 

3167 result["ordered"] = True 

3168 result["do_not_suppress"] = {_get_matcher_id(self._jedi_matcher)} 

3169 return result 

3170 

3171 def dispatch_custom_completer(self, text): 

3172 """ 

3173 .. deprecated:: 8.6 

3174 You can use :meth:`custom_completer_matcher` instead. 

3175 """ 

3176 if not self.custom_completers: 

3177 return 

3178 

3179 line = self.line_buffer 

3180 if not line.strip(): 

3181 return None 

3182 

3183 # Create a little structure to pass all the relevant information about 

3184 # the current completion to any custom completer. 

3185 event = SimpleNamespace() 

3186 event.line = line 

3187 event.symbol = text 

3188 cmd = line.split(None,1)[0] 

3189 event.command = cmd 

3190 event.text_until_cursor = self.text_until_cursor 

3191 

3192 # for foo etc, try also to find completer for %foo 

3193 if not cmd.startswith(self.magic_escape): 

3194 try_magic = self.custom_completers.s_matches( 

3195 self.magic_escape + cmd) 

3196 else: 

3197 try_magic = [] 

3198 

3199 for c in itertools.chain(self.custom_completers.s_matches(cmd), 

3200 try_magic, 

3201 self.custom_completers.flat_matches(self.text_until_cursor)): 

3202 try: 

3203 res = c(event) 

3204 if res: 

3205 # first, try case sensitive match 

3206 withcase = [r for r in res if r.startswith(text)] 

3207 if withcase: 

3208 return withcase 

3209 # if none, then case insensitive ones are ok too 

3210 text_low = text.lower() 

3211 return [r for r in res if r.lower().startswith(text_low)] 

3212 except TryNext: 

3213 pass 

3214 except KeyboardInterrupt: 

3215 """ 

3216 If custom completer take too long, 

3217 let keyboard interrupt abort and return nothing. 

3218 """ 

3219 break 

3220 

3221 return None 

3222 

3223 def completions(self, text: str, offset: int)->Iterator[Completion]: 

3224 """ 

3225 Returns an iterator over the possible completions 

3226 

3227 .. warning:: 

3228 

3229 Unstable 

3230 

3231 This function is unstable, API may change without warning. 

3232 It will also raise unless use in proper context manager. 

3233 

3234 Parameters 

3235 ---------- 

3236 text : str 

3237 Full text of the current input, multi line string. 

3238 offset : int 

3239 Integer representing the position of the cursor in ``text``. Offset 

3240 is 0-based indexed. 

3241 

3242 Yields 

3243 ------ 

3244 Completion 

3245 

3246 Notes 

3247 ----- 

3248 The cursor on a text can either be seen as being "in between" 

3249 characters or "On" a character depending on the interface visible to 

3250 the user. For consistency the cursor being on "in between" characters X 

3251 and Y is equivalent to the cursor being "on" character Y, that is to say 

3252 the character the cursor is on is considered as being after the cursor. 

3253 

3254 Combining characters may span more that one position in the 

3255 text. 

3256 

3257 .. note:: 

3258 

3259 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--`` 

3260 fake Completion token to distinguish completion returned by Jedi 

3261 and usual IPython completion. 

3262 

3263 .. note:: 

3264 

3265 Completions are not completely deduplicated yet. If identical 

3266 completions are coming from different sources this function does not 

3267 ensure that each completion object will only be present once. 

3268 """ 

3269 warnings.warn("_complete is a provisional API (as of IPython 6.0). " 

3270 "It may change without warnings. " 

3271 "Use in corresponding context manager.", 

3272 category=ProvisionalCompleterWarning, stacklevel=2) 

3273 

3274 seen = set() 

3275 profiler:Optional[cProfile.Profile] 

3276 try: 

3277 if self.profile_completions: 

3278 import cProfile 

3279 profiler = cProfile.Profile() 

3280 profiler.enable() 

3281 else: 

3282 profiler = None 

3283 

3284 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000): 

3285 if c and (c in seen): 

3286 continue 

3287 yield c 

3288 seen.add(c) 

3289 except KeyboardInterrupt: 

3290 """if completions take too long and users send keyboard interrupt, 

3291 do not crash and return ASAP. """ 

3292 pass 

3293 finally: 

3294 if profiler is not None: 

3295 profiler.disable() 

3296 ensure_dir_exists(self.profiler_output_dir) 

3297 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4())) 

3298 print("Writing profiler output to", output_path) 

3299 profiler.dump_stats(output_path) 

3300 

3301 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]: 

3302 """ 

3303 Core completion module.Same signature as :any:`completions`, with the 

3304 extra `timeout` parameter (in seconds). 

3305 

3306 Computing jedi's completion ``.type`` can be quite expensive (it is a 

3307 lazy property) and can require some warm-up, more warm up than just 

3308 computing the ``name`` of a completion. The warm-up can be : 

3309 

3310 - Long warm-up the first time a module is encountered after 

3311 install/update: actually build parse/inference tree. 

3312 

3313 - first time the module is encountered in a session: load tree from 

3314 disk. 

3315 

3316 We don't want to block completions for tens of seconds so we give the 

3317 completer a "budget" of ``_timeout`` seconds per invocation to compute 

3318 completions types, the completions that have not yet been computed will 

3319 be marked as "unknown" an will have a chance to be computed next round 

3320 are things get cached. 

3321 

3322 Keep in mind that Jedi is not the only thing treating the completion so 

3323 keep the timeout short-ish as if we take more than 0.3 second we still 

3324 have lots of processing to do. 

3325 

3326 """ 

3327 deadline = time.monotonic() + _timeout 

3328 

3329 before = full_text[:offset] 

3330 cursor_line, cursor_column = position_to_cursor(full_text, offset) 

3331 

3332 jedi_matcher_id = _get_matcher_id(self._jedi_matcher) 

3333 

3334 def is_non_jedi_result( 

3335 result: MatcherResult, identifier: str 

3336 ) -> TypeGuard[SimpleMatcherResult]: 

3337 return identifier != jedi_matcher_id 

3338 

3339 results = self._complete( 

3340 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column 

3341 ) 

3342 

3343 non_jedi_results: dict[str, SimpleMatcherResult] = { 

3344 identifier: result 

3345 for identifier, result in results.items() 

3346 if is_non_jedi_result(result, identifier) 

3347 } 

3348 

3349 jedi_matches = ( 

3350 cast(_JediMatcherResult, results[jedi_matcher_id])["completions"] 

3351 if jedi_matcher_id in results 

3352 else () 

3353 ) 

3354 

3355 iter_jm = iter(jedi_matches) 

3356 if _timeout: 

3357 for jm in iter_jm: 

3358 try: 

3359 type_ = jm.type 

3360 except Exception: 

3361 if self.debug: 

3362 print("Error in Jedi getting type of ", jm) 

3363 type_ = None 

3364 delta = len(jm.name_with_symbols) - len(jm.complete) 

3365 if type_ == 'function': 

3366 signature = _make_signature(jm) 

3367 else: 

3368 signature = '' 

3369 yield Completion(start=offset - delta, 

3370 end=offset, 

3371 text=jm.name_with_symbols, 

3372 type=type_, 

3373 signature=signature, 

3374 _origin='jedi') 

3375 

3376 if time.monotonic() > deadline: 

3377 break 

3378 

3379 for jm in iter_jm: 

3380 delta = len(jm.name_with_symbols) - len(jm.complete) 

3381 yield Completion( 

3382 start=offset - delta, 

3383 end=offset, 

3384 text=jm.name_with_symbols, 

3385 type=_UNKNOWN_TYPE, # don't compute type for speed 

3386 _origin="jedi", 

3387 signature="", 

3388 ) 

3389 

3390 # TODO: 

3391 # Suppress this, right now just for debug. 

3392 if jedi_matches and non_jedi_results and self.debug: 

3393 some_start_offset = before.rfind( 

3394 next(iter(non_jedi_results.values()))["matched_fragment"] 

3395 ) 

3396 yield Completion( 

3397 start=some_start_offset, 

3398 end=offset, 

3399 text="--jedi/ipython--", 

3400 _origin="debug", 

3401 type="none", 

3402 signature="", 

3403 ) 

3404 

3405 ordered: list[Completion] = [] 

3406 sortable: list[Completion] = [] 

3407 

3408 for origin, result in non_jedi_results.items(): 

3409 matched_text = result["matched_fragment"] 

3410 start_offset = before.rfind(matched_text) 

3411 is_ordered = result.get("ordered", False) 

3412 container = ordered if is_ordered else sortable 

3413 

3414 # I'm unsure if this is always true, so let's assert and see if it 

3415 # crash 

3416 assert before.endswith(matched_text) 

3417 

3418 for simple_completion in result["completions"]: 

3419 completion = Completion( 

3420 start=start_offset, 

3421 end=offset, 

3422 text=simple_completion.text, 

3423 _origin=origin, 

3424 signature="", 

3425 type=simple_completion.type or _UNKNOWN_TYPE, 

3426 ) 

3427 container.append(completion) 

3428 

3429 yield from list(self._deduplicate(ordered + self._sort(sortable)))[ 

3430 :MATCHES_LIMIT 

3431 ] 

3432 

3433 def complete( 

3434 self, text=None, line_buffer=None, cursor_pos=None 

3435 ) -> tuple[str, Sequence[str]]: 

3436 """Find completions for the given text and line context. 

3437 

3438 Note that both the text and the line_buffer are optional, but at least 

3439 one of them must be given. 

3440 

3441 Parameters 

3442 ---------- 

3443 text : string, optional 

3444 Text to perform the completion on. If not given, the line buffer 

3445 is split using the instance's CompletionSplitter object. 

3446 line_buffer : string, optional 

3447 If not given, the completer attempts to obtain the current line 

3448 buffer via readline. This keyword allows clients which are 

3449 requesting for text completions in non-readline contexts to inform 

3450 the completer of the entire text. 

3451 cursor_pos : int, optional 

3452 Index of the cursor in the full line buffer. Should be provided by 

3453 remote frontends where kernel has no access to frontend state. 

3454 

3455 Returns 

3456 ------- 

3457 Tuple of two items: 

3458 text : str 

3459 Text that was actually used in the completion. 

3460 matches : list 

3461 A list of completion matches. 

3462 

3463 Notes 

3464 ----- 

3465 This API is likely to be deprecated and replaced by 

3466 :any:`IPCompleter.completions` in the future. 

3467 

3468 """ 

3469 warnings.warn('`Completer.complete` is pending deprecation since ' 

3470 'IPython 6.0 and will be replaced by `Completer.completions`.', 

3471 PendingDeprecationWarning) 

3472 # potential todo, FOLD the 3rd throw away argument of _complete 

3473 # into the first 2 one. 

3474 # TODO: Q: does the above refer to jedi completions (i.e. 0-indexed?) 

3475 # TODO: should we deprecate now, or does it stay? 

3476 

3477 results = self._complete( 

3478 line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0 

3479 ) 

3480 

3481 jedi_matcher_id = _get_matcher_id(self._jedi_matcher) 

3482 

3483 return self._arrange_and_extract( 

3484 results, 

3485 # TODO: can we confirm that excluding Jedi here was a deliberate choice in previous version? 

3486 skip_matchers={jedi_matcher_id}, 

3487 # this API does not support different start/end positions (fragments of token). 

3488 abort_if_offset_changes=True, 

3489 ) 

3490 

3491 def _arrange_and_extract( 

3492 self, 

3493 results: dict[str, MatcherResult], 

3494 skip_matchers: set[str], 

3495 abort_if_offset_changes: bool, 

3496 ): 

3497 sortable: list[AnyMatcherCompletion] = [] 

3498 ordered: list[AnyMatcherCompletion] = [] 

3499 most_recent_fragment = None 

3500 for identifier, result in results.items(): 

3501 if identifier in skip_matchers: 

3502 continue 

3503 if not result["completions"]: 

3504 continue 

3505 if not most_recent_fragment: 

3506 most_recent_fragment = result["matched_fragment"] 

3507 if ( 

3508 abort_if_offset_changes 

3509 and result["matched_fragment"] != most_recent_fragment 

3510 ): 

3511 break 

3512 if result.get("ordered", False): 

3513 ordered.extend(result["completions"]) 

3514 else: 

3515 sortable.extend(result["completions"]) 

3516 

3517 if not most_recent_fragment: 

3518 most_recent_fragment = "" # to satisfy typechecker (and just in case) 

3519 

3520 return most_recent_fragment, [ 

3521 m.text for m in self._deduplicate(ordered + self._sort(sortable)) 

3522 ] 

3523 

3524 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None, 

3525 full_text=None) -> _CompleteResult: 

3526 """ 

3527 Like complete but can also returns raw jedi completions as well as the 

3528 origin of the completion text. This could (and should) be made much 

3529 cleaner but that will be simpler once we drop the old (and stateful) 

3530 :any:`complete` API. 

3531 

3532 With current provisional API, cursor_pos act both (depending on the 

3533 caller) as the offset in the ``text`` or ``line_buffer``, or as the 

3534 ``column`` when passing multiline strings this could/should be renamed 

3535 but would add extra noise. 

3536 

3537 Parameters 

3538 ---------- 

3539 cursor_line 

3540 Index of the line the cursor is on. 0 indexed. 

3541 cursor_pos 

3542 Position of the cursor in the current line/line_buffer/text. 0 

3543 indexed. 

3544 line_buffer : optional, str 

3545 The current line the cursor is in, this is mostly due to legacy 

3546 reason that readline could only give a us the single current line. 

3547 Prefer `full_text`. 

3548 text : str 

3549 The current "token" the cursor is in, mostly also for historical 

3550 reasons. as the completer would trigger only after the current line 

3551 was parsed. 

3552 full_text : str 

3553 Full text of the current cell. 

3554 

3555 Returns 

3556 ------- 

3557 An ordered dictionary where keys are identifiers of completion 

3558 matchers and values are ``MatcherResult``s. 

3559 """ 

3560 

3561 # if the cursor position isn't given, the only sane assumption we can 

3562 # make is that it's at the end of the line (the common case) 

3563 if cursor_pos is None: 

3564 cursor_pos = len(line_buffer) if text is None else len(text) 

3565 

3566 if self.use_main_ns: 

3567 self.namespace = __main__.__dict__ 

3568 

3569 # if text is either None or an empty string, rely on the line buffer 

3570 if (not line_buffer) and full_text: 

3571 line_buffer = full_text.split('\n')[cursor_line] 

3572 if not text: # issue #11508: check line_buffer before calling split_line 

3573 text = ( 

3574 self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else "" 

3575 ) 

3576 

3577 # If no line buffer is given, assume the input text is all there was 

3578 if line_buffer is None: 

3579 line_buffer = text 

3580 

3581 # deprecated - do not use `line_buffer` in new code. 

3582 self.line_buffer = line_buffer 

3583 self.text_until_cursor = self.line_buffer[:cursor_pos] 

3584 

3585 if not full_text: 

3586 full_text = line_buffer 

3587 

3588 context = CompletionContext( 

3589 full_text=full_text, 

3590 cursor_position=cursor_pos, 

3591 cursor_line=cursor_line, 

3592 token=self._extract_code(text), 

3593 limit=MATCHES_LIMIT, 

3594 ) 

3595 

3596 # Start with a clean slate of completions 

3597 results: dict[str, MatcherResult] = {} 

3598 

3599 jedi_matcher_id = _get_matcher_id(self._jedi_matcher) 

3600 

3601 suppressed_matchers: set[str] = set() 

3602 

3603 matchers = { 

3604 _get_matcher_id(matcher): matcher 

3605 for matcher in sorted( 

3606 self.matchers, key=_get_matcher_priority, reverse=True 

3607 ) 

3608 } 

3609 

3610 for matcher_id, matcher in matchers.items(): 

3611 matcher_id = _get_matcher_id(matcher) 

3612 

3613 if matcher_id in self.disable_matchers: 

3614 continue 

3615 

3616 if matcher_id in results: 

3617 warnings.warn(f"Duplicate matcher ID: {matcher_id}.") 

3618 

3619 if matcher_id in suppressed_matchers: 

3620 continue 

3621 

3622 result: MatcherResult 

3623 try: 

3624 if _is_matcher_v1(matcher): 

3625 result = _convert_matcher_v1_result_to_v2_no_no( 

3626 matcher(text), type=_UNKNOWN_TYPE 

3627 ) 

3628 elif _is_matcher_v2(matcher): 

3629 result = matcher(context) 

3630 else: 

3631 api_version = _get_matcher_api_version(matcher) 

3632 raise ValueError(f"Unsupported API version {api_version}") 

3633 except BaseException: 

3634 # Show the ugly traceback if the matcher causes an 

3635 # exception, but do NOT crash the kernel! 

3636 sys.excepthook(*sys.exc_info()) 

3637 continue 

3638 

3639 # set default value for matched fragment if suffix was not selected. 

3640 result["matched_fragment"] = result.get("matched_fragment", context.token) 

3641 

3642 if not suppressed_matchers: 

3643 suppression_recommended: Union[bool, set[str]] = result.get( 

3644 "suppress", False 

3645 ) 

3646 

3647 suppression_config = ( 

3648 self.suppress_competing_matchers.get(matcher_id, None) 

3649 if isinstance(self.suppress_competing_matchers, dict) 

3650 else self.suppress_competing_matchers 

3651 ) 

3652 should_suppress = ( 

3653 (suppression_config is True) 

3654 or (suppression_recommended and (suppression_config is not False)) 

3655 ) and has_any_completions(result) 

3656 

3657 if should_suppress: 

3658 suppression_exceptions: set[str] = result.get( 

3659 "do_not_suppress", set() 

3660 ) 

3661 if isinstance(suppression_recommended, Iterable): 

3662 to_suppress = set(suppression_recommended) 

3663 else: 

3664 to_suppress = set(matchers) 

3665 suppressed_matchers = to_suppress - suppression_exceptions 

3666 

3667 new_results = {} 

3668 for previous_matcher_id, previous_result in results.items(): 

3669 if previous_matcher_id not in suppressed_matchers: 

3670 new_results[previous_matcher_id] = previous_result 

3671 results = new_results 

3672 

3673 results[matcher_id] = result 

3674 

3675 _, matches = self._arrange_and_extract( 

3676 results, 

3677 # TODO Jedi completions non included in legacy stateful API; was this deliberate or omission? 

3678 # if it was omission, we can remove the filtering step, otherwise remove this comment. 

3679 skip_matchers={jedi_matcher_id}, 

3680 abort_if_offset_changes=False, 

3681 ) 

3682 

3683 # populate legacy stateful API 

3684 self.matches = matches 

3685 

3686 return results 

3687 

3688 @staticmethod 

3689 def _deduplicate( 

3690 matches: Sequence[AnyCompletion], 

3691 ) -> Iterable[AnyCompletion]: 

3692 filtered_matches: dict[str, AnyCompletion] = {} 

3693 for match in matches: 

3694 text = match.text 

3695 if ( 

3696 text not in filtered_matches 

3697 or filtered_matches[text].type == _UNKNOWN_TYPE 

3698 ): 

3699 filtered_matches[text] = match 

3700 

3701 return filtered_matches.values() 

3702 

3703 @staticmethod 

3704 def _sort(matches: Sequence[AnyCompletion]): 

3705 return sorted(matches, key=lambda x: completions_sorting_key(x.text)) 

3706 

3707 @context_matcher() 

3708 def fwd_unicode_matcher(self, context: CompletionContext): 

3709 """Same as :any:`fwd_unicode_match`, but adopted to new Matcher API.""" 

3710 # TODO: use `context.limit` to terminate early once we matched the maximum 

3711 # number that will be used downstream; can be added as an optional to 

3712 # `fwd_unicode_match(text: str, limit: int = None)` or we could re-implement here. 

3713 fragment, matches = self.fwd_unicode_match(context.text_until_cursor) 

3714 return _convert_matcher_v1_result_to_v2( 

3715 matches, type="unicode", fragment=fragment, suppress_if_matches=True 

3716 ) 

3717 

3718 def fwd_unicode_match(self, text: str) -> tuple[str, Sequence[str]]: 

3719 """ 

3720 Forward match a string starting with a backslash with a list of 

3721 potential Unicode completions. 

3722 

3723 Will compute list of Unicode character names on first call and cache it. 

3724 

3725 .. deprecated:: 8.6 

3726 You can use :meth:`fwd_unicode_matcher` instead. 

3727 

3728 Returns 

3729 ------- 

3730 At tuple with: 

3731 - matched text (empty if no matches) 

3732 - list of potential completions, empty tuple otherwise) 

3733 """ 

3734 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements. 

3735 # We could do a faster match using a Trie. 

3736 

3737 # Using pygtrie the following seem to work: 

3738 

3739 # s = PrefixSet() 

3740 

3741 # for c in range(0,0x10FFFF + 1): 

3742 # try: 

3743 # s.add(unicodedata.name(chr(c))) 

3744 # except ValueError: 

3745 # pass 

3746 # [''.join(k) for k in s.iter(prefix)] 

3747 

3748 # But need to be timed and adds an extra dependency. 

3749 

3750 slashpos = text.rfind('\\') 

3751 # if text starts with slash 

3752 if slashpos > -1: 

3753 # PERF: It's important that we don't access self._unicode_names 

3754 # until we're inside this if-block. _unicode_names is lazily 

3755 # initialized, and it takes a user-noticeable amount of time to 

3756 # initialize it, so we don't want to initialize it unless we're 

3757 # actually going to use it. 

3758 s = text[slashpos + 1 :] 

3759 sup = s.upper() 

3760 candidates = [x for x in self.unicode_names if x.startswith(sup)] 

3761 if candidates: 

3762 return s, candidates 

3763 candidates = [x for x in self.unicode_names if sup in x] 

3764 if candidates: 

3765 return s, candidates 

3766 splitsup = sup.split(" ") 

3767 candidates = [ 

3768 x for x in self.unicode_names if all(u in x for u in splitsup) 

3769 ] 

3770 if candidates: 

3771 return s, candidates 

3772 

3773 return "", () 

3774 

3775 # if text does not start with slash 

3776 else: 

3777 return '', () 

3778 

3779 @property 

3780 def unicode_names(self) -> list[str]: 

3781 """List of names of unicode code points that can be completed. 

3782 

3783 The list is lazily initialized on first access. 

3784 """ 

3785 if self._unicode_names is None: 

3786 names = [] 

3787 for c in range(0,0x10FFFF + 1): 

3788 try: 

3789 names.append(unicodedata.name(chr(c))) 

3790 except ValueError: 

3791 pass 

3792 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES) 

3793 

3794 return self._unicode_names 

3795 

3796 

3797def _unicode_name_compute(ranges: list[tuple[int, int]]) -> list[str]: 

3798 names = [] 

3799 for start,stop in ranges: 

3800 for c in range(start, stop) : 

3801 try: 

3802 names.append(unicodedata.name(chr(c))) 

3803 except ValueError: 

3804 pass 

3805 return names