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