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