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