##// END OF EJS Templates
Avoid triggering jedi in string....
Matthias Bussonnier -
Show More
@@ -1,1760 +1,1780 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Completion for IPython.
2 """Completion for IPython.
3
3
4 This module started as fork of the rlcompleter module in the Python standard
4 This module started as fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3,
6 upstream and were accepted as of Python 2.3,
7
7
8 This module now support a wide variety of completion mechanism both available
8 This module now support a wide variety of completion mechanism both available
9 for normal classic Python code, as well as completer for IPython specific
9 for normal classic Python code, as well as completer for IPython specific
10 Syntax like magics.
10 Syntax like magics.
11
11
12 Experimental
12 Experimental
13 ============
13 ============
14
14
15 Starting with IPython 6.0, this module can make use of the Jedi library to
15 Starting with IPython 6.0, this module can make use of the Jedi library to
16 generate completions both using static analysis of the code, and dynamically
16 generate completions both using static analysis of the code, and dynamically
17 inspecting multiple namespaces. The APIs attached to this new mechanism is
17 inspecting multiple namespaces. The APIs attached to this new mechanism is
18 unstable and will raise unless use in an :any:`provisionalcompleter` context
18 unstable and will raise unless use in an :any:`provisionalcompleter` context
19 manager.
19 manager.
20
20
21 You will find that the following are experimental:
21 You will find that the following are experimental:
22
22
23 - :any:`provisionalcompleter`
23 - :any:`provisionalcompleter`
24 - :any:`IPCompleter.completions`
24 - :any:`IPCompleter.completions`
25 - :any:`Completion`
25 - :any:`Completion`
26 - :any:`rectify_completions`
26 - :any:`rectify_completions`
27
27
28 .. note::
28 .. note::
29
29
30 better name for :any:`rectify_completions` ?
30 better name for :any:`rectify_completions` ?
31
31
32 We welcome any feedback on these new API, and we also encourage you to try this
32 We welcome any feedback on these new API, and we also encourage you to try this
33 module in debug mode (start IPython with ``--Completer.debug=True``) in order
33 module in debug mode (start IPython with ``--Completer.debug=True``) in order
34 to have extra logging information is :any:`jedi` is crashing, or if current
34 to have extra logging information is :any:`jedi` is crashing, or if current
35 IPython completer pending deprecations are returning results not yet handled
35 IPython completer pending deprecations are returning results not yet handled
36 by :any:`jedi`.
36 by :any:`jedi`.
37
37
38 Using Jedi for tab completion allow snippets like the following to work without
38 Using Jedi for tab completion allow snippets like the following to work without
39 having to execute any code:
39 having to execute any code:
40
40
41 >>> myvar = ['hello', 42]
41 >>> myvar = ['hello', 42]
42 ... myvar[1].bi<tab>
42 ... myvar[1].bi<tab>
43
43
44 Tab completion will be able to infer that ``myvar[1]`` is a real number without
44 Tab completion will be able to infer that ``myvar[1]`` is a real number without
45 executing any code unlike the previously available ``IPCompleter.greedy``
45 executing any code unlike the previously available ``IPCompleter.greedy``
46 option.
46 option.
47
47
48 Be sure to update :any:`jedi` to the latest stable version or to try the
48 Be sure to update :any:`jedi` to the latest stable version or to try the
49 current development version to get better completions.
49 current development version to get better completions.
50 """
50 """
51
51
52 # skip module docstests
52 # skip module docstests
53 skip_doctest = True
53 skip_doctest = True
54
54
55 # Copyright (c) IPython Development Team.
55 # Copyright (c) IPython Development Team.
56 # Distributed under the terms of the Modified BSD License.
56 # Distributed under the terms of the Modified BSD License.
57 #
57 #
58 # Some of this code originated from rlcompleter in the Python standard library
58 # Some of this code originated from rlcompleter in the Python standard library
59 # Copyright (C) 2001 Python Software Foundation, www.python.org
59 # Copyright (C) 2001 Python Software Foundation, www.python.org
60
60
61
61
62 import __main__
62 import __main__
63 import builtins as builtin_mod
63 import builtins as builtin_mod
64 import glob
64 import glob
65 import time
65 import time
66 import inspect
66 import inspect
67 import itertools
67 import itertools
68 import keyword
68 import keyword
69 import os
69 import os
70 import re
70 import re
71 import sys
71 import sys
72 import unicodedata
72 import unicodedata
73 import string
73 import string
74 import warnings
74 import warnings
75
75
76 from contextlib import contextmanager
76 from contextlib import contextmanager
77 from importlib import import_module
77 from importlib import import_module
78 from typing import Iterator, List
78 from typing import Iterator, List
79 from types import SimpleNamespace
79 from types import SimpleNamespace
80
80
81 from traitlets.config.configurable import Configurable
81 from traitlets.config.configurable import Configurable
82 from IPython.core.error import TryNext
82 from IPython.core.error import TryNext
83 from IPython.core.inputsplitter import ESC_MAGIC
83 from IPython.core.inputsplitter import ESC_MAGIC
84 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
84 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
85 from IPython.utils import generics
85 from IPython.utils import generics
86 from IPython.utils.dir2 import dir2, get_real_method
86 from IPython.utils.dir2 import dir2, get_real_method
87 from IPython.utils.process import arg_split
87 from IPython.utils.process import arg_split
88 from IPython.utils.py3compat import cast_unicode_py2
88 from IPython.utils.py3compat import cast_unicode_py2
89 from traitlets import Bool, Enum, observe, Int
89 from traitlets import Bool, Enum, observe, Int
90
90
91 try:
91 try:
92 import jedi
92 import jedi
93 import jedi.api.helpers
93 import jedi.api.helpers
94 JEDI_INSTALLED = True
94 JEDI_INSTALLED = True
95 except ImportError:
95 except ImportError:
96 JEDI_INSTALLED = False
96 JEDI_INSTALLED = False
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98 # Globals
98 # Globals
99 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
100
100
101 # Public API
101 # Public API
102 __all__ = ['Completer','IPCompleter']
102 __all__ = ['Completer','IPCompleter']
103
103
104 if sys.platform == 'win32':
104 if sys.platform == 'win32':
105 PROTECTABLES = ' '
105 PROTECTABLES = ' '
106 else:
106 else:
107 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
107 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
108
108
109
109
110 _deprecation_readline_sentinel = object()
110 _deprecation_readline_sentinel = object()
111
111
112
112
113 class ProvisionalCompleterWarning(FutureWarning):
113 class ProvisionalCompleterWarning(FutureWarning):
114 """
114 """
115 Exception raise by an experimental feature in this module.
115 Exception raise by an experimental feature in this module.
116
116
117 Wrap code in :any:`provisionalcompleter` context manager if you
117 Wrap code in :any:`provisionalcompleter` context manager if you
118 are certain you want to use an unstable feature.
118 are certain you want to use an unstable feature.
119 """
119 """
120 pass
120 pass
121
121
122 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
122 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
123
123
124 @contextmanager
124 @contextmanager
125 def provisionalcompleter(action='ignore'):
125 def provisionalcompleter(action='ignore'):
126 """
126 """
127
127
128
128
129 This contest manager has to be used in any place where unstable completer
129 This contest manager has to be used in any place where unstable completer
130 behavior and API may be called.
130 behavior and API may be called.
131
131
132 >>> with provisionalcompleter():
132 >>> with provisionalcompleter():
133 ... completer.do_experimetal_things() # works
133 ... completer.do_experimetal_things() # works
134
134
135 >>> completer.do_experimental_things() # raises.
135 >>> completer.do_experimental_things() # raises.
136
136
137 .. note:: Unstable
137 .. note:: Unstable
138
138
139 By using this context manager you agree that the API in use may change
139 By using this context manager you agree that the API in use may change
140 without warning, and that you won't complain if they do so.
140 without warning, and that you won't complain if they do so.
141
141
142 You also understand that if the API is not to you liking you should report
142 You also understand that if the API is not to you liking you should report
143 a bug to explain your use case upstream and improve the API and will loose
143 a bug to explain your use case upstream and improve the API and will loose
144 credibility if you complain after the API is make stable.
144 credibility if you complain after the API is make stable.
145
145
146 We'll be happy to get your feedback , feature request and improvement on
146 We'll be happy to get your feedback , feature request and improvement on
147 any of the unstable APIs !
147 any of the unstable APIs !
148 """
148 """
149 with warnings.catch_warnings():
149 with warnings.catch_warnings():
150 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
150 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
151 yield
151 yield
152
152
153
153
154 def has_open_quotes(s):
154 def has_open_quotes(s):
155 """Return whether a string has open quotes.
155 """Return whether a string has open quotes.
156
156
157 This simply counts whether the number of quote characters of either type in
157 This simply counts whether the number of quote characters of either type in
158 the string is odd.
158 the string is odd.
159
159
160 Returns
160 Returns
161 -------
161 -------
162 If there is an open quote, the quote character is returned. Else, return
162 If there is an open quote, the quote character is returned. Else, return
163 False.
163 False.
164 """
164 """
165 # We check " first, then ', so complex cases with nested quotes will get
165 # We check " first, then ', so complex cases with nested quotes will get
166 # the " to take precedence.
166 # the " to take precedence.
167 if s.count('"') % 2:
167 if s.count('"') % 2:
168 return '"'
168 return '"'
169 elif s.count("'") % 2:
169 elif s.count("'") % 2:
170 return "'"
170 return "'"
171 else:
171 else:
172 return False
172 return False
173
173
174
174
175 def protect_filename(s):
175 def protect_filename(s):
176 """Escape a string to protect certain characters."""
176 """Escape a string to protect certain characters."""
177 if set(s) & set(PROTECTABLES):
177 if set(s) & set(PROTECTABLES):
178 if sys.platform == "win32":
178 if sys.platform == "win32":
179 return '"' + s + '"'
179 return '"' + s + '"'
180 else:
180 else:
181 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
181 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
182 else:
182 else:
183 return s
183 return s
184
184
185
185
186 def expand_user(path):
186 def expand_user(path):
187 """Expand ``~``-style usernames in strings.
187 """Expand ``~``-style usernames in strings.
188
188
189 This is similar to :func:`os.path.expanduser`, but it computes and returns
189 This is similar to :func:`os.path.expanduser`, but it computes and returns
190 extra information that will be useful if the input was being used in
190 extra information that will be useful if the input was being used in
191 computing completions, and you wish to return the completions with the
191 computing completions, and you wish to return the completions with the
192 original '~' instead of its expanded value.
192 original '~' instead of its expanded value.
193
193
194 Parameters
194 Parameters
195 ----------
195 ----------
196 path : str
196 path : str
197 String to be expanded. If no ~ is present, the output is the same as the
197 String to be expanded. If no ~ is present, the output is the same as the
198 input.
198 input.
199
199
200 Returns
200 Returns
201 -------
201 -------
202 newpath : str
202 newpath : str
203 Result of ~ expansion in the input path.
203 Result of ~ expansion in the input path.
204 tilde_expand : bool
204 tilde_expand : bool
205 Whether any expansion was performed or not.
205 Whether any expansion was performed or not.
206 tilde_val : str
206 tilde_val : str
207 The value that ~ was replaced with.
207 The value that ~ was replaced with.
208 """
208 """
209 # Default values
209 # Default values
210 tilde_expand = False
210 tilde_expand = False
211 tilde_val = ''
211 tilde_val = ''
212 newpath = path
212 newpath = path
213
213
214 if path.startswith('~'):
214 if path.startswith('~'):
215 tilde_expand = True
215 tilde_expand = True
216 rest = len(path)-1
216 rest = len(path)-1
217 newpath = os.path.expanduser(path)
217 newpath = os.path.expanduser(path)
218 if rest:
218 if rest:
219 tilde_val = newpath[:-rest]
219 tilde_val = newpath[:-rest]
220 else:
220 else:
221 tilde_val = newpath
221 tilde_val = newpath
222
222
223 return newpath, tilde_expand, tilde_val
223 return newpath, tilde_expand, tilde_val
224
224
225
225
226 def compress_user(path, tilde_expand, tilde_val):
226 def compress_user(path, tilde_expand, tilde_val):
227 """Does the opposite of expand_user, with its outputs.
227 """Does the opposite of expand_user, with its outputs.
228 """
228 """
229 if tilde_expand:
229 if tilde_expand:
230 return path.replace(tilde_val, '~')
230 return path.replace(tilde_val, '~')
231 else:
231 else:
232 return path
232 return path
233
233
234
234
235 def completions_sorting_key(word):
235 def completions_sorting_key(word):
236 """key for sorting completions
236 """key for sorting completions
237
237
238 This does several things:
238 This does several things:
239
239
240 - Lowercase all completions, so they are sorted alphabetically with
240 - Lowercase all completions, so they are sorted alphabetically with
241 upper and lower case words mingled
241 upper and lower case words mingled
242 - Demote any completions starting with underscores to the end
242 - Demote any completions starting with underscores to the end
243 - Insert any %magic and %%cellmagic completions in the alphabetical order
243 - Insert any %magic and %%cellmagic completions in the alphabetical order
244 by their name
244 by their name
245 """
245 """
246 # Case insensitive sort
246 # Case insensitive sort
247 word = word.lower()
247 word = word.lower()
248
248
249 prio1, prio2 = 0, 0
249 prio1, prio2 = 0, 0
250
250
251 if word.startswith('__'):
251 if word.startswith('__'):
252 prio1 = 2
252 prio1 = 2
253 elif word.startswith('_'):
253 elif word.startswith('_'):
254 prio1 = 1
254 prio1 = 1
255
255
256 if word.endswith('='):
256 if word.endswith('='):
257 prio1 = -1
257 prio1 = -1
258
258
259 if word.startswith('%%'):
259 if word.startswith('%%'):
260 # If there's another % in there, this is something else, so leave it alone
260 # If there's another % in there, this is something else, so leave it alone
261 if not "%" in word[2:]:
261 if not "%" in word[2:]:
262 word = word[2:]
262 word = word[2:]
263 prio2 = 2
263 prio2 = 2
264 elif word.startswith('%'):
264 elif word.startswith('%'):
265 if not "%" in word[1:]:
265 if not "%" in word[1:]:
266 word = word[1:]
266 word = word[1:]
267 prio2 = 1
267 prio2 = 1
268
268
269 return prio1, word, prio2
269 return prio1, word, prio2
270
270
271
271
272 class _FakeJediCompletion:
272 class _FakeJediCompletion:
273 """
273 """
274 This is a workaround to communicate to the UI that Jedi has crashed and to
274 This is a workaround to communicate to the UI that Jedi has crashed and to
275 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
275 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
276
276
277 Added in IPython 6.0 so should likely be removed for 7.0
277 Added in IPython 6.0 so should likely be removed for 7.0
278
278
279 """
279 """
280
280
281 def __init__(self, name):
281 def __init__(self, name):
282
282
283 self.name = name
283 self.name = name
284 self.complete = name
284 self.complete = name
285 self.type = 'crashed'
285 self.type = 'crashed'
286 self.name_with_symbols = name
286 self.name_with_symbols = name
287
287
288 def __repr__(self):
288 def __repr__(self):
289 return '<Fake completion object jedi has crashed>'
289 return '<Fake completion object jedi has crashed>'
290
290
291
291
292 class Completion:
292 class Completion:
293 """
293 """
294 Completion object used and return by IPython completers.
294 Completion object used and return by IPython completers.
295
295
296 .. warning:: Unstable
296 .. warning:: Unstable
297
297
298 This function is unstable, API may change without warning.
298 This function is unstable, API may change without warning.
299 It will also raise unless use in proper context manager.
299 It will also raise unless use in proper context manager.
300
300
301 This act as a middle ground :any:`Completion` object between the
301 This act as a middle ground :any:`Completion` object between the
302 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
302 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
303 object. While Jedi need a lot of information about evaluator and how the
303 object. While Jedi need a lot of information about evaluator and how the
304 code should be ran/inspected, PromptToolkit (and other frontend) mostly
304 code should be ran/inspected, PromptToolkit (and other frontend) mostly
305 need user facing information.
305 need user facing information.
306
306
307 - Which range should be replaced replaced by what.
307 - Which range should be replaced replaced by what.
308 - Some metadata (like completion type), or meta informations to displayed to
308 - Some metadata (like completion type), or meta informations to displayed to
309 the use user.
309 the use user.
310
310
311 For debugging purpose we can also store the origin of the completion (``jedi``,
311 For debugging purpose we can also store the origin of the completion (``jedi``,
312 ``IPython.python_matches``, ``IPython.magics_matches``...).
312 ``IPython.python_matches``, ``IPython.magics_matches``...).
313 """
313 """
314
314
315 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin=''):
315 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin=''):
316 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
316 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
317 "It may change without warnings. "
317 "It may change without warnings. "
318 "Use in corresponding context manager.",
318 "Use in corresponding context manager.",
319 category=ProvisionalCompleterWarning, stacklevel=2)
319 category=ProvisionalCompleterWarning, stacklevel=2)
320
320
321 self.start = start
321 self.start = start
322 self.end = end
322 self.end = end
323 self.text = text
323 self.text = text
324 self.type = type
324 self.type = type
325 self._origin = _origin
325 self._origin = _origin
326
326
327 def __repr__(self):
327 def __repr__(self):
328 return '<Completion start=%s end=%s text=%r type=%r>' % (self.start, self.end, self.text, self.type or '?')
328 return '<Completion start=%s end=%s text=%r type=%r>' % (self.start, self.end, self.text, self.type or '?')
329
329
330 def __eq__(self, other)->Bool:
330 def __eq__(self, other)->Bool:
331 """
331 """
332 Equality and hash do not hash the type (as some completer may not be
332 Equality and hash do not hash the type (as some completer may not be
333 able to infer the type), but are use to (partially) de-duplicate
333 able to infer the type), but are use to (partially) de-duplicate
334 completion.
334 completion.
335
335
336 Completely de-duplicating completion is a bit tricker that just
336 Completely de-duplicating completion is a bit tricker that just
337 comparing as it depends on surrounding text, which Completions are not
337 comparing as it depends on surrounding text, which Completions are not
338 aware of.
338 aware of.
339 """
339 """
340 return self.start == other.start and \
340 return self.start == other.start and \
341 self.end == other.end and \
341 self.end == other.end and \
342 self.text == other.text
342 self.text == other.text
343
343
344 def __hash__(self):
344 def __hash__(self):
345 return hash((self.start, self.end, self.text))
345 return hash((self.start, self.end, self.text))
346
346
347 _IC = Iterator[Completion]
347 _IC = Iterator[Completion]
348
348
349 def rectify_completions(text:str, completion:_IC, *, _debug=False)->_IC:
349 def rectify_completions(text:str, completion:_IC, *, _debug=False)->_IC:
350 """
350 """
351 Rectify a set of completion to all have the same ``start`` and ``end``
351 Rectify a set of completion to all have the same ``start`` and ``end``
352
352
353 .. warning:: Unstable
353 .. warning:: Unstable
354
354
355 This function is unstable, API may change without warning.
355 This function is unstable, API may change without warning.
356 It will also raise unless use in proper context manager.
356 It will also raise unless use in proper context manager.
357
357
358 Parameters
358 Parameters
359 ----------
359 ----------
360 text: str
360 text: str
361 text that should be completed.
361 text that should be completed.
362 completion: Iterator[Completion]
362 completion: Iterator[Completion]
363 iterator over the completions to rectify
363 iterator over the completions to rectify
364
364
365
365
366 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
366 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
367 the Jupyter Protocol requires them to behave like so. This will readjust
367 the Jupyter Protocol requires them to behave like so. This will readjust
368 the completion to have the same ``start`` and ``end` by padding both
368 the completion to have the same ``start`` and ``end` by padding both
369 extremities with surrounding text.
369 extremities with surrounding text.
370
370
371 During stabilisation should support a ``_debug`` option to log which
371 During stabilisation should support a ``_debug`` option to log which
372 completion are return by the IPython completer and not found in Jedi in
372 completion are return by the IPython completer and not found in Jedi in
373 order to make upstream bug report.
373 order to make upstream bug report.
374 """
374 """
375 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
375 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
376 "It may change without warnings. "
376 "It may change without warnings. "
377 "Use in corresponding context manager.",
377 "Use in corresponding context manager.",
378 category=ProvisionalCompleterWarning, stacklevel=2)
378 category=ProvisionalCompleterWarning, stacklevel=2)
379
379
380 completions = list(completion)
380 completions = list(completion)
381 if not completions:
381 if not completions:
382 return
382 return
383 starts = (c.start for c in completions)
383 starts = (c.start for c in completions)
384 ends = (c.end for c in completions)
384 ends = (c.end for c in completions)
385
385
386 new_start = min(starts)
386 new_start = min(starts)
387 new_end = max(ends)
387 new_end = max(ends)
388
388
389 seen_jedi = set()
389 seen_jedi = set()
390 seen_python_matches = set()
390 seen_python_matches = set()
391 for c in completions:
391 for c in completions:
392 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
392 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
393 if c._origin == 'jedi':
393 if c._origin == 'jedi':
394 seen_jedi.add(new_text)
394 seen_jedi.add(new_text)
395 elif c._origin == 'IPCompleter.python_matches':
395 elif c._origin == 'IPCompleter.python_matches':
396 seen_python_matches.add(new_text)
396 seen_python_matches.add(new_text)
397 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin)
397 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin)
398 diff = seen_python_matches.difference(seen_jedi)
398 diff = seen_python_matches.difference(seen_jedi)
399 if diff and _debug:
399 if diff and _debug:
400 print('IPython.python matches have extras:', diff)
400 print('IPython.python matches have extras:', diff)
401
401
402
402
403 if sys.platform == 'win32':
403 if sys.platform == 'win32':
404 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
404 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
405 else:
405 else:
406 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
406 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
407
407
408 GREEDY_DELIMS = ' =\r\n'
408 GREEDY_DELIMS = ' =\r\n'
409
409
410
410
411 class CompletionSplitter(object):
411 class CompletionSplitter(object):
412 """An object to split an input line in a manner similar to readline.
412 """An object to split an input line in a manner similar to readline.
413
413
414 By having our own implementation, we can expose readline-like completion in
414 By having our own implementation, we can expose readline-like completion in
415 a uniform manner to all frontends. This object only needs to be given the
415 a uniform manner to all frontends. This object only needs to be given the
416 line of text to be split and the cursor position on said line, and it
416 line of text to be split and the cursor position on said line, and it
417 returns the 'word' to be completed on at the cursor after splitting the
417 returns the 'word' to be completed on at the cursor after splitting the
418 entire line.
418 entire line.
419
419
420 What characters are used as splitting delimiters can be controlled by
420 What characters are used as splitting delimiters can be controlled by
421 setting the ``delims`` attribute (this is a property that internally
421 setting the ``delims`` attribute (this is a property that internally
422 automatically builds the necessary regular expression)"""
422 automatically builds the necessary regular expression)"""
423
423
424 # Private interface
424 # Private interface
425
425
426 # A string of delimiter characters. The default value makes sense for
426 # A string of delimiter characters. The default value makes sense for
427 # IPython's most typical usage patterns.
427 # IPython's most typical usage patterns.
428 _delims = DELIMS
428 _delims = DELIMS
429
429
430 # The expression (a normal string) to be compiled into a regular expression
430 # The expression (a normal string) to be compiled into a regular expression
431 # for actual splitting. We store it as an attribute mostly for ease of
431 # for actual splitting. We store it as an attribute mostly for ease of
432 # debugging, since this type of code can be so tricky to debug.
432 # debugging, since this type of code can be so tricky to debug.
433 _delim_expr = None
433 _delim_expr = None
434
434
435 # The regular expression that does the actual splitting
435 # The regular expression that does the actual splitting
436 _delim_re = None
436 _delim_re = None
437
437
438 def __init__(self, delims=None):
438 def __init__(self, delims=None):
439 delims = CompletionSplitter._delims if delims is None else delims
439 delims = CompletionSplitter._delims if delims is None else delims
440 self.delims = delims
440 self.delims = delims
441
441
442 @property
442 @property
443 def delims(self):
443 def delims(self):
444 """Return the string of delimiter characters."""
444 """Return the string of delimiter characters."""
445 return self._delims
445 return self._delims
446
446
447 @delims.setter
447 @delims.setter
448 def delims(self, delims):
448 def delims(self, delims):
449 """Set the delimiters for line splitting."""
449 """Set the delimiters for line splitting."""
450 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
450 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
451 self._delim_re = re.compile(expr)
451 self._delim_re = re.compile(expr)
452 self._delims = delims
452 self._delims = delims
453 self._delim_expr = expr
453 self._delim_expr = expr
454
454
455 def split_line(self, line, cursor_pos=None):
455 def split_line(self, line, cursor_pos=None):
456 """Split a line of text with a cursor at the given position.
456 """Split a line of text with a cursor at the given position.
457 """
457 """
458 l = line if cursor_pos is None else line[:cursor_pos]
458 l = line if cursor_pos is None else line[:cursor_pos]
459 return self._delim_re.split(l)[-1]
459 return self._delim_re.split(l)[-1]
460
460
461
461
462
462
463 class Completer(Configurable):
463 class Completer(Configurable):
464
464
465 greedy = Bool(False,
465 greedy = Bool(False,
466 help="""Activate greedy completion
466 help="""Activate greedy completion
467 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
467 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
468
468
469 This will enable completion on elements of lists, results of function calls, etc.,
469 This will enable completion on elements of lists, results of function calls, etc.,
470 but can be unsafe because the code is actually evaluated on TAB.
470 but can be unsafe because the code is actually evaluated on TAB.
471 """
471 """
472 ).tag(config=True)
472 ).tag(config=True)
473
473
474 use_jedi = Bool(default_value=JEDI_INSTALLED,
474 use_jedi = Bool(default_value=JEDI_INSTALLED,
475 help="Experimental: Use Jedi to generate autocompletions. "
475 help="Experimental: Use Jedi to generate autocompletions. "
476 "Default to True if jedi is installed").tag(config=True)
476 "Default to True if jedi is installed").tag(config=True)
477
477
478 jedi_compute_type_timeout = Int(default_value=400,
478 jedi_compute_type_timeout = Int(default_value=400,
479 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
479 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
480 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
480 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
481 performance by preventing jedi to build its cache.
481 performance by preventing jedi to build its cache.
482 """).tag(config=True)
482 """).tag(config=True)
483
483
484 debug = Bool(default_value=False,
484 debug = Bool(default_value=False,
485 help='Enable debug for the Completer. Mostly print extra '
485 help='Enable debug for the Completer. Mostly print extra '
486 'information for experimental jedi integration.')\
486 'information for experimental jedi integration.')\
487 .tag(config=True)
487 .tag(config=True)
488
488
489
489
490 def __init__(self, namespace=None, global_namespace=None, **kwargs):
490 def __init__(self, namespace=None, global_namespace=None, **kwargs):
491 """Create a new completer for the command line.
491 """Create a new completer for the command line.
492
492
493 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
493 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
494
494
495 If unspecified, the default namespace where completions are performed
495 If unspecified, the default namespace where completions are performed
496 is __main__ (technically, __main__.__dict__). Namespaces should be
496 is __main__ (technically, __main__.__dict__). Namespaces should be
497 given as dictionaries.
497 given as dictionaries.
498
498
499 An optional second namespace can be given. This allows the completer
499 An optional second namespace can be given. This allows the completer
500 to handle cases where both the local and global scopes need to be
500 to handle cases where both the local and global scopes need to be
501 distinguished.
501 distinguished.
502 """
502 """
503
503
504 # Don't bind to namespace quite yet, but flag whether the user wants a
504 # Don't bind to namespace quite yet, but flag whether the user wants a
505 # specific namespace or to use __main__.__dict__. This will allow us
505 # specific namespace or to use __main__.__dict__. This will allow us
506 # to bind to __main__.__dict__ at completion time, not now.
506 # to bind to __main__.__dict__ at completion time, not now.
507 if namespace is None:
507 if namespace is None:
508 self.use_main_ns = True
508 self.use_main_ns = True
509 else:
509 else:
510 self.use_main_ns = False
510 self.use_main_ns = False
511 self.namespace = namespace
511 self.namespace = namespace
512
512
513 # The global namespace, if given, can be bound directly
513 # The global namespace, if given, can be bound directly
514 if global_namespace is None:
514 if global_namespace is None:
515 self.global_namespace = {}
515 self.global_namespace = {}
516 else:
516 else:
517 self.global_namespace = global_namespace
517 self.global_namespace = global_namespace
518
518
519 super(Completer, self).__init__(**kwargs)
519 super(Completer, self).__init__(**kwargs)
520
520
521 def complete(self, text, state):
521 def complete(self, text, state):
522 """Return the next possible completion for 'text'.
522 """Return the next possible completion for 'text'.
523
523
524 This is called successively with state == 0, 1, 2, ... until it
524 This is called successively with state == 0, 1, 2, ... until it
525 returns None. The completion should begin with 'text'.
525 returns None. The completion should begin with 'text'.
526
526
527 """
527 """
528 if self.use_main_ns:
528 if self.use_main_ns:
529 self.namespace = __main__.__dict__
529 self.namespace = __main__.__dict__
530
530
531 if state == 0:
531 if state == 0:
532 if "." in text:
532 if "." in text:
533 self.matches = self.attr_matches(text)
533 self.matches = self.attr_matches(text)
534 else:
534 else:
535 self.matches = self.global_matches(text)
535 self.matches = self.global_matches(text)
536 try:
536 try:
537 return self.matches[state]
537 return self.matches[state]
538 except IndexError:
538 except IndexError:
539 return None
539 return None
540
540
541 def global_matches(self, text):
541 def global_matches(self, text):
542 """Compute matches when text is a simple name.
542 """Compute matches when text is a simple name.
543
543
544 Return a list of all keywords, built-in functions and names currently
544 Return a list of all keywords, built-in functions and names currently
545 defined in self.namespace or self.global_namespace that match.
545 defined in self.namespace or self.global_namespace that match.
546
546
547 """
547 """
548 matches = []
548 matches = []
549 match_append = matches.append
549 match_append = matches.append
550 n = len(text)
550 n = len(text)
551 for lst in [keyword.kwlist,
551 for lst in [keyword.kwlist,
552 builtin_mod.__dict__.keys(),
552 builtin_mod.__dict__.keys(),
553 self.namespace.keys(),
553 self.namespace.keys(),
554 self.global_namespace.keys()]:
554 self.global_namespace.keys()]:
555 for word in lst:
555 for word in lst:
556 if word[:n] == text and word != "__builtins__":
556 if word[:n] == text and word != "__builtins__":
557 match_append(word)
557 match_append(word)
558 return [cast_unicode_py2(m) for m in matches]
558 return [cast_unicode_py2(m) for m in matches]
559
559
560 def attr_matches(self, text):
560 def attr_matches(self, text):
561 """Compute matches when text contains a dot.
561 """Compute matches when text contains a dot.
562
562
563 Assuming the text is of the form NAME.NAME....[NAME], and is
563 Assuming the text is of the form NAME.NAME....[NAME], and is
564 evaluatable in self.namespace or self.global_namespace, it will be
564 evaluatable in self.namespace or self.global_namespace, it will be
565 evaluated and its attributes (as revealed by dir()) are used as
565 evaluated and its attributes (as revealed by dir()) are used as
566 possible completions. (For class instances, class members are are
566 possible completions. (For class instances, class members are are
567 also considered.)
567 also considered.)
568
568
569 WARNING: this can still invoke arbitrary C code, if an object
569 WARNING: this can still invoke arbitrary C code, if an object
570 with a __getattr__ hook is evaluated.
570 with a __getattr__ hook is evaluated.
571
571
572 """
572 """
573
573
574 # Another option, seems to work great. Catches things like ''.<tab>
574 # Another option, seems to work great. Catches things like ''.<tab>
575 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
575 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
576
576
577 if m:
577 if m:
578 expr, attr = m.group(1, 3)
578 expr, attr = m.group(1, 3)
579 elif self.greedy:
579 elif self.greedy:
580 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
580 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
581 if not m2:
581 if not m2:
582 return []
582 return []
583 expr, attr = m2.group(1,2)
583 expr, attr = m2.group(1,2)
584 else:
584 else:
585 return []
585 return []
586
586
587 try:
587 try:
588 obj = eval(expr, self.namespace)
588 obj = eval(expr, self.namespace)
589 except:
589 except:
590 try:
590 try:
591 obj = eval(expr, self.global_namespace)
591 obj = eval(expr, self.global_namespace)
592 except:
592 except:
593 return []
593 return []
594
594
595 if self.limit_to__all__ and hasattr(obj, '__all__'):
595 if self.limit_to__all__ and hasattr(obj, '__all__'):
596 words = get__all__entries(obj)
596 words = get__all__entries(obj)
597 else:
597 else:
598 words = dir2(obj)
598 words = dir2(obj)
599
599
600 try:
600 try:
601 words = generics.complete_object(obj, words)
601 words = generics.complete_object(obj, words)
602 except TryNext:
602 except TryNext:
603 pass
603 pass
604 except AssertionError:
604 except AssertionError:
605 raise
605 raise
606 except Exception:
606 except Exception:
607 # Silence errors from completion function
607 # Silence errors from completion function
608 #raise # dbg
608 #raise # dbg
609 pass
609 pass
610 # Build match list to return
610 # Build match list to return
611 n = len(attr)
611 n = len(attr)
612 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
612 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
613
613
614
614
615 def get__all__entries(obj):
615 def get__all__entries(obj):
616 """returns the strings in the __all__ attribute"""
616 """returns the strings in the __all__ attribute"""
617 try:
617 try:
618 words = getattr(obj, '__all__')
618 words = getattr(obj, '__all__')
619 except:
619 except:
620 return []
620 return []
621
621
622 return [cast_unicode_py2(w) for w in words if isinstance(w, str)]
622 return [cast_unicode_py2(w) for w in words if isinstance(w, str)]
623
623
624
624
625 def match_dict_keys(keys: List[str], prefix: str, delims: str):
625 def match_dict_keys(keys: List[str], prefix: str, delims: str):
626 """Used by dict_key_matches, matching the prefix to a list of keys
626 """Used by dict_key_matches, matching the prefix to a list of keys
627
627
628 Parameters
628 Parameters
629 ==========
629 ==========
630 keys:
630 keys:
631 list of keys in dictionary currently being completed.
631 list of keys in dictionary currently being completed.
632 prefix:
632 prefix:
633 Part of the text already typed by the user. e.g. `mydict[b'fo`
633 Part of the text already typed by the user. e.g. `mydict[b'fo`
634 delims:
634 delims:
635 String of delimiters to consider when finding the current key.
635 String of delimiters to consider when finding the current key.
636
636
637 Returns
637 Returns
638 =======
638 =======
639
639
640 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
640 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
641 ``quote`` being the quote that need to be used to close current string.
641 ``quote`` being the quote that need to be used to close current string.
642 ``token_start`` the position where the replacement should start occurring,
642 ``token_start`` the position where the replacement should start occurring,
643 ``matches`` a list of replacement/completion
643 ``matches`` a list of replacement/completion
644
644
645 """
645 """
646 if not prefix:
646 if not prefix:
647 return None, 0, [repr(k) for k in keys
647 return None, 0, [repr(k) for k in keys
648 if isinstance(k, (str, bytes))]
648 if isinstance(k, (str, bytes))]
649 quote_match = re.search('["\']', prefix)
649 quote_match = re.search('["\']', prefix)
650 quote = quote_match.group()
650 quote = quote_match.group()
651 try:
651 try:
652 prefix_str = eval(prefix + quote, {})
652 prefix_str = eval(prefix + quote, {})
653 except Exception:
653 except Exception:
654 return None, 0, []
654 return None, 0, []
655
655
656 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
656 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
657 token_match = re.search(pattern, prefix, re.UNICODE)
657 token_match = re.search(pattern, prefix, re.UNICODE)
658 token_start = token_match.start()
658 token_start = token_match.start()
659 token_prefix = token_match.group()
659 token_prefix = token_match.group()
660
660
661 matched = []
661 matched = []
662 for key in keys:
662 for key in keys:
663 try:
663 try:
664 if not key.startswith(prefix_str):
664 if not key.startswith(prefix_str):
665 continue
665 continue
666 except (AttributeError, TypeError, UnicodeError):
666 except (AttributeError, TypeError, UnicodeError):
667 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
667 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
668 continue
668 continue
669
669
670 # reformat remainder of key to begin with prefix
670 # reformat remainder of key to begin with prefix
671 rem = key[len(prefix_str):]
671 rem = key[len(prefix_str):]
672 # force repr wrapped in '
672 # force repr wrapped in '
673 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
673 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
674 if rem_repr.startswith('u') and prefix[0] not in 'uU':
674 if rem_repr.startswith('u') and prefix[0] not in 'uU':
675 # Found key is unicode, but prefix is Py2 string.
675 # Found key is unicode, but prefix is Py2 string.
676 # Therefore attempt to interpret key as string.
676 # Therefore attempt to interpret key as string.
677 try:
677 try:
678 rem_repr = repr(rem.encode('ascii') + '"')
678 rem_repr = repr(rem.encode('ascii') + '"')
679 except UnicodeEncodeError:
679 except UnicodeEncodeError:
680 continue
680 continue
681
681
682 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
682 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
683 if quote == '"':
683 if quote == '"':
684 # The entered prefix is quoted with ",
684 # The entered prefix is quoted with ",
685 # but the match is quoted with '.
685 # but the match is quoted with '.
686 # A contained " hence needs escaping for comparison:
686 # A contained " hence needs escaping for comparison:
687 rem_repr = rem_repr.replace('"', '\\"')
687 rem_repr = rem_repr.replace('"', '\\"')
688
688
689 # then reinsert prefix from start of token
689 # then reinsert prefix from start of token
690 matched.append('%s%s' % (token_prefix, rem_repr))
690 matched.append('%s%s' % (token_prefix, rem_repr))
691 return quote, token_start, matched
691 return quote, token_start, matched
692
692
693
693
694 def cursor_to_position(text:int, line:int, column:int)->int:
694 def cursor_to_position(text:int, line:int, column:int)->int:
695 """
695 """
696
696
697 Convert the (line,column) position of the cursor in text to an offset in a
697 Convert the (line,column) position of the cursor in text to an offset in a
698 string.
698 string.
699
699
700 Parameter
700 Parameter
701 ---------
701 ---------
702
702
703 text : str
703 text : str
704 The text in which to calculate the cursor offset
704 The text in which to calculate the cursor offset
705 line : int
705 line : int
706 Line of the cursor; 0-indexed
706 Line of the cursor; 0-indexed
707 column : int
707 column : int
708 Column of the cursor 0-indexed
708 Column of the cursor 0-indexed
709
709
710 Return
710 Return
711 ------
711 ------
712 Position of the cursor in ``text``, 0-indexed.
712 Position of the cursor in ``text``, 0-indexed.
713
713
714 See Also
714 See Also
715 --------
715 --------
716 position_to_cursor: reciprocal of this function
716 position_to_cursor: reciprocal of this function
717
717
718 """
718 """
719 lines = text.split('\n')
719 lines = text.split('\n')
720 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
720 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
721
721
722 return sum(len(l) + 1 for l in lines[:line]) + column
722 return sum(len(l) + 1 for l in lines[:line]) + column
723
723
724 def position_to_cursor(text:str, offset:int)->(int, int):
724 def position_to_cursor(text:str, offset:int)->(int, int):
725 """
725 """
726 Convert the position of the cursor in text (0 indexed) to a line
726 Convert the position of the cursor in text (0 indexed) to a line
727 number(0-indexed) and a column number (0-indexed) pair
727 number(0-indexed) and a column number (0-indexed) pair
728
728
729 Position should be a valid position in ``text``.
729 Position should be a valid position in ``text``.
730
730
731 Parameter
731 Parameter
732 ---------
732 ---------
733
733
734 text : str
734 text : str
735 The text in which to calculate the cursor offset
735 The text in which to calculate the cursor offset
736 offset : int
736 offset : int
737 Position of the cursor in ``text``, 0-indexed.
737 Position of the cursor in ``text``, 0-indexed.
738
738
739 Return
739 Return
740 ------
740 ------
741 (line, column) : (int, int)
741 (line, column) : (int, int)
742 Line of the cursor; 0-indexed, column of the cursor 0-indexed
742 Line of the cursor; 0-indexed, column of the cursor 0-indexed
743
743
744
744
745 See Also
745 See Also
746 --------
746 --------
747 cursor_to_position : reciprocal of this function
747 cursor_to_position : reciprocal of this function
748
748
749
749
750 """
750 """
751
751
752 assert 0 < offset <= len(text) , "0 < %s <= %s" % (offset , len(text))
752 assert 0 < offset <= len(text) , "0 < %s <= %s" % (offset , len(text))
753
753
754 before = text[:offset]
754 before = text[:offset]
755 blines = before.split('\n') # ! splitnes trim trailing \n
755 blines = before.split('\n') # ! splitnes trim trailing \n
756 line = before.count('\n')
756 line = before.count('\n')
757 col = len(blines[-1])
757 col = len(blines[-1])
758 return line, col
758 return line, col
759
759
760
760
761 def _safe_isinstance(obj, module, class_name):
761 def _safe_isinstance(obj, module, class_name):
762 """Checks if obj is an instance of module.class_name if loaded
762 """Checks if obj is an instance of module.class_name if loaded
763 """
763 """
764 return (module in sys.modules and
764 return (module in sys.modules and
765 isinstance(obj, getattr(import_module(module), class_name)))
765 isinstance(obj, getattr(import_module(module), class_name)))
766
766
767
767
768 def back_unicode_name_matches(text):
768 def back_unicode_name_matches(text):
769 u"""Match unicode characters back to unicode name
769 u"""Match unicode characters back to unicode name
770
770
771 This does ``β˜ƒ`` -> ``\\snowman``
771 This does ``β˜ƒ`` -> ``\\snowman``
772
772
773 Note that snowman is not a valid python3 combining character but will be expanded.
773 Note that snowman is not a valid python3 combining character but will be expanded.
774 Though it will not recombine back to the snowman character by the completion machinery.
774 Though it will not recombine back to the snowman character by the completion machinery.
775
775
776 This will not either back-complete standard sequences like \\n, \\b ...
776 This will not either back-complete standard sequences like \\n, \\b ...
777
777
778 Used on Python 3 only.
778 Used on Python 3 only.
779 """
779 """
780 if len(text)<2:
780 if len(text)<2:
781 return u'', ()
781 return u'', ()
782 maybe_slash = text[-2]
782 maybe_slash = text[-2]
783 if maybe_slash != '\\':
783 if maybe_slash != '\\':
784 return u'', ()
784 return u'', ()
785
785
786 char = text[-1]
786 char = text[-1]
787 # no expand on quote for completion in strings.
787 # no expand on quote for completion in strings.
788 # nor backcomplete standard ascii keys
788 # nor backcomplete standard ascii keys
789 if char in string.ascii_letters or char in ['"',"'"]:
789 if char in string.ascii_letters or char in ['"',"'"]:
790 return u'', ()
790 return u'', ()
791 try :
791 try :
792 unic = unicodedata.name(char)
792 unic = unicodedata.name(char)
793 return '\\'+char,['\\'+unic]
793 return '\\'+char,['\\'+unic]
794 except KeyError:
794 except KeyError:
795 pass
795 pass
796 return u'', ()
796 return u'', ()
797
797
798 def back_latex_name_matches(text:str):
798 def back_latex_name_matches(text:str):
799 """Match latex characters back to unicode name
799 """Match latex characters back to unicode name
800
800
801 This does ``\\β„΅`` -> ``\\aleph``
801 This does ``\\β„΅`` -> ``\\aleph``
802
802
803 Used on Python 3 only.
803 Used on Python 3 only.
804 """
804 """
805 if len(text)<2:
805 if len(text)<2:
806 return u'', ()
806 return u'', ()
807 maybe_slash = text[-2]
807 maybe_slash = text[-2]
808 if maybe_slash != '\\':
808 if maybe_slash != '\\':
809 return u'', ()
809 return u'', ()
810
810
811
811
812 char = text[-1]
812 char = text[-1]
813 # no expand on quote for completion in strings.
813 # no expand on quote for completion in strings.
814 # nor backcomplete standard ascii keys
814 # nor backcomplete standard ascii keys
815 if char in string.ascii_letters or char in ['"',"'"]:
815 if char in string.ascii_letters or char in ['"',"'"]:
816 return u'', ()
816 return u'', ()
817 try :
817 try :
818 latex = reverse_latex_symbol[char]
818 latex = reverse_latex_symbol[char]
819 # '\\' replace the \ as well
819 # '\\' replace the \ as well
820 return '\\'+char,[latex]
820 return '\\'+char,[latex]
821 except KeyError:
821 except KeyError:
822 pass
822 pass
823 return u'', ()
823 return u'', ()
824
824
825
825
826 class IPCompleter(Completer):
826 class IPCompleter(Completer):
827 """Extension of the completer class with IPython-specific features"""
827 """Extension of the completer class with IPython-specific features"""
828
828
829 @observe('greedy')
829 @observe('greedy')
830 def _greedy_changed(self, change):
830 def _greedy_changed(self, change):
831 """update the splitter and readline delims when greedy is changed"""
831 """update the splitter and readline delims when greedy is changed"""
832 if change['new']:
832 if change['new']:
833 self.splitter.delims = GREEDY_DELIMS
833 self.splitter.delims = GREEDY_DELIMS
834 else:
834 else:
835 self.splitter.delims = DELIMS
835 self.splitter.delims = DELIMS
836
836
837 merge_completions = Bool(True,
837 merge_completions = Bool(True,
838 help="""Whether to merge completion results into a single list
838 help="""Whether to merge completion results into a single list
839
839
840 If False, only the completion results from the first non-empty
840 If False, only the completion results from the first non-empty
841 completer will be returned.
841 completer will be returned.
842 """
842 """
843 ).tag(config=True)
843 ).tag(config=True)
844 omit__names = Enum((0,1,2), default_value=2,
844 omit__names = Enum((0,1,2), default_value=2,
845 help="""Instruct the completer to omit private method names
845 help="""Instruct the completer to omit private method names
846
846
847 Specifically, when completing on ``object.<tab>``.
847 Specifically, when completing on ``object.<tab>``.
848
848
849 When 2 [default]: all names that start with '_' will be excluded.
849 When 2 [default]: all names that start with '_' will be excluded.
850
850
851 When 1: all 'magic' names (``__foo__``) will be excluded.
851 When 1: all 'magic' names (``__foo__``) will be excluded.
852
852
853 When 0: nothing will be excluded.
853 When 0: nothing will be excluded.
854 """
854 """
855 ).tag(config=True)
855 ).tag(config=True)
856 limit_to__all__ = Bool(False,
856 limit_to__all__ = Bool(False,
857 help="""
857 help="""
858 DEPRECATED as of version 5.0.
858 DEPRECATED as of version 5.0.
859
859
860 Instruct the completer to use __all__ for the completion
860 Instruct the completer to use __all__ for the completion
861
861
862 Specifically, when completing on ``object.<tab>``.
862 Specifically, when completing on ``object.<tab>``.
863
863
864 When True: only those names in obj.__all__ will be included.
864 When True: only those names in obj.__all__ will be included.
865
865
866 When False [default]: the __all__ attribute is ignored
866 When False [default]: the __all__ attribute is ignored
867 """,
867 """,
868 ).tag(config=True)
868 ).tag(config=True)
869
869
870 @observe('limit_to__all__')
870 @observe('limit_to__all__')
871 def _limit_to_all_changed(self, change):
871 def _limit_to_all_changed(self, change):
872 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
872 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
873 'value has been deprecated since IPython 5.0, will be made to have '
873 'value has been deprecated since IPython 5.0, will be made to have '
874 'no effects and then removed in future version of IPython.',
874 'no effects and then removed in future version of IPython.',
875 UserWarning)
875 UserWarning)
876
876
877 def __init__(self, shell=None, namespace=None, global_namespace=None,
877 def __init__(self, shell=None, namespace=None, global_namespace=None,
878 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
878 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
879 """IPCompleter() -> completer
879 """IPCompleter() -> completer
880
880
881 Return a completer object.
881 Return a completer object.
882
882
883 Parameters
883 Parameters
884 ----------
884 ----------
885
885
886 shell
886 shell
887 a pointer to the ipython shell itself. This is needed
887 a pointer to the ipython shell itself. This is needed
888 because this completer knows about magic functions, and those can
888 because this completer knows about magic functions, and those can
889 only be accessed via the ipython instance.
889 only be accessed via the ipython instance.
890
890
891 namespace : dict, optional
891 namespace : dict, optional
892 an optional dict where completions are performed.
892 an optional dict where completions are performed.
893
893
894 global_namespace : dict, optional
894 global_namespace : dict, optional
895 secondary optional dict for completions, to
895 secondary optional dict for completions, to
896 handle cases (such as IPython embedded inside functions) where
896 handle cases (such as IPython embedded inside functions) where
897 both Python scopes are visible.
897 both Python scopes are visible.
898
898
899 use_readline : bool, optional
899 use_readline : bool, optional
900 DEPRECATED, ignored since IPython 6.0, will have no effects
900 DEPRECATED, ignored since IPython 6.0, will have no effects
901 """
901 """
902
902
903 self.magic_escape = ESC_MAGIC
903 self.magic_escape = ESC_MAGIC
904 self.splitter = CompletionSplitter()
904 self.splitter = CompletionSplitter()
905
905
906 if use_readline is not _deprecation_readline_sentinel:
906 if use_readline is not _deprecation_readline_sentinel:
907 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
907 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
908 DeprecationWarning, stacklevel=2)
908 DeprecationWarning, stacklevel=2)
909
909
910 # _greedy_changed() depends on splitter and readline being defined:
910 # _greedy_changed() depends on splitter and readline being defined:
911 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
911 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
912 config=config, **kwargs)
912 config=config, **kwargs)
913
913
914 # List where completion matches will be stored
914 # List where completion matches will be stored
915 self.matches = []
915 self.matches = []
916 self.shell = shell
916 self.shell = shell
917 # Regexp to split filenames with spaces in them
917 # Regexp to split filenames with spaces in them
918 self.space_name_re = re.compile(r'([^\\] )')
918 self.space_name_re = re.compile(r'([^\\] )')
919 # Hold a local ref. to glob.glob for speed
919 # Hold a local ref. to glob.glob for speed
920 self.glob = glob.glob
920 self.glob = glob.glob
921
921
922 # Determine if we are running on 'dumb' terminals, like (X)Emacs
922 # Determine if we are running on 'dumb' terminals, like (X)Emacs
923 # buffers, to avoid completion problems.
923 # buffers, to avoid completion problems.
924 term = os.environ.get('TERM','xterm')
924 term = os.environ.get('TERM','xterm')
925 self.dumb_terminal = term in ['dumb','emacs']
925 self.dumb_terminal = term in ['dumb','emacs']
926
926
927 # Special handling of backslashes needed in win32 platforms
927 # Special handling of backslashes needed in win32 platforms
928 if sys.platform == "win32":
928 if sys.platform == "win32":
929 self.clean_glob = self._clean_glob_win32
929 self.clean_glob = self._clean_glob_win32
930 else:
930 else:
931 self.clean_glob = self._clean_glob
931 self.clean_glob = self._clean_glob
932
932
933 #regexp to parse docstring for function signature
933 #regexp to parse docstring for function signature
934 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
934 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
935 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
935 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
936 #use this if positional argument name is also needed
936 #use this if positional argument name is also needed
937 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
937 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
938
938
939 # All active matcher routines for completion
939 # All active matcher routines for completion
940 self.matchers = [
940 self.matchers = [
941 self.python_matches,
941 self.python_matches,
942 self.file_matches,
942 self.file_matches,
943 self.magic_matches,
943 self.magic_matches,
944 self.python_func_kw_matches,
944 self.python_func_kw_matches,
945 self.dict_key_matches,
945 self.dict_key_matches,
946 ]
946 ]
947
947
948 # This is set externally by InteractiveShell
948 # This is set externally by InteractiveShell
949 self.custom_completers = None
949 self.custom_completers = None
950
950
951 def all_completions(self, text):
951 def all_completions(self, text):
952 """
952 """
953 Wrapper around the complete method for the benefit of emacs.
953 Wrapper around the complete method for the benefit of emacs.
954 """
954 """
955 return self.complete(text)[1]
955 return self.complete(text)[1]
956
956
957 def _clean_glob(self, text):
957 def _clean_glob(self, text):
958 return self.glob("%s*" % text)
958 return self.glob("%s*" % text)
959
959
960 def _clean_glob_win32(self,text):
960 def _clean_glob_win32(self,text):
961 return [f.replace("\\","/")
961 return [f.replace("\\","/")
962 for f in self.glob("%s*" % text)]
962 for f in self.glob("%s*" % text)]
963
963
964 def file_matches(self, text):
964 def file_matches(self, text):
965 """Match filenames, expanding ~USER type strings.
965 """Match filenames, expanding ~USER type strings.
966
966
967 Most of the seemingly convoluted logic in this completer is an
967 Most of the seemingly convoluted logic in this completer is an
968 attempt to handle filenames with spaces in them. And yet it's not
968 attempt to handle filenames with spaces in them. And yet it's not
969 quite perfect, because Python's readline doesn't expose all of the
969 quite perfect, because Python's readline doesn't expose all of the
970 GNU readline details needed for this to be done correctly.
970 GNU readline details needed for this to be done correctly.
971
971
972 For a filename with a space in it, the printed completions will be
972 For a filename with a space in it, the printed completions will be
973 only the parts after what's already been typed (instead of the
973 only the parts after what's already been typed (instead of the
974 full completions, as is normally done). I don't think with the
974 full completions, as is normally done). I don't think with the
975 current (as of Python 2.3) Python readline it's possible to do
975 current (as of Python 2.3) Python readline it's possible to do
976 better."""
976 better."""
977
977
978 # chars that require escaping with backslash - i.e. chars
978 # chars that require escaping with backslash - i.e. chars
979 # that readline treats incorrectly as delimiters, but we
979 # that readline treats incorrectly as delimiters, but we
980 # don't want to treat as delimiters in filename matching
980 # don't want to treat as delimiters in filename matching
981 # when escaped with backslash
981 # when escaped with backslash
982 if text.startswith('!'):
982 if text.startswith('!'):
983 text = text[1:]
983 text = text[1:]
984 text_prefix = u'!'
984 text_prefix = u'!'
985 else:
985 else:
986 text_prefix = u''
986 text_prefix = u''
987
987
988 text_until_cursor = self.text_until_cursor
988 text_until_cursor = self.text_until_cursor
989 # track strings with open quotes
989 # track strings with open quotes
990 open_quotes = has_open_quotes(text_until_cursor)
990 open_quotes = has_open_quotes(text_until_cursor)
991
991
992 if '(' in text_until_cursor or '[' in text_until_cursor:
992 if '(' in text_until_cursor or '[' in text_until_cursor:
993 lsplit = text
993 lsplit = text
994 else:
994 else:
995 try:
995 try:
996 # arg_split ~ shlex.split, but with unicode bugs fixed by us
996 # arg_split ~ shlex.split, but with unicode bugs fixed by us
997 lsplit = arg_split(text_until_cursor)[-1]
997 lsplit = arg_split(text_until_cursor)[-1]
998 except ValueError:
998 except ValueError:
999 # typically an unmatched ", or backslash without escaped char.
999 # typically an unmatched ", or backslash without escaped char.
1000 if open_quotes:
1000 if open_quotes:
1001 lsplit = text_until_cursor.split(open_quotes)[-1]
1001 lsplit = text_until_cursor.split(open_quotes)[-1]
1002 else:
1002 else:
1003 return []
1003 return []
1004 except IndexError:
1004 except IndexError:
1005 # tab pressed on empty line
1005 # tab pressed on empty line
1006 lsplit = ""
1006 lsplit = ""
1007
1007
1008 if not open_quotes and lsplit != protect_filename(lsplit):
1008 if not open_quotes and lsplit != protect_filename(lsplit):
1009 # if protectables are found, do matching on the whole escaped name
1009 # if protectables are found, do matching on the whole escaped name
1010 has_protectables = True
1010 has_protectables = True
1011 text0,text = text,lsplit
1011 text0,text = text,lsplit
1012 else:
1012 else:
1013 has_protectables = False
1013 has_protectables = False
1014 text = os.path.expanduser(text)
1014 text = os.path.expanduser(text)
1015
1015
1016 if text == "":
1016 if text == "":
1017 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
1017 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
1018
1018
1019 # Compute the matches from the filesystem
1019 # Compute the matches from the filesystem
1020 if sys.platform == 'win32':
1020 if sys.platform == 'win32':
1021 m0 = self.clean_glob(text)
1021 m0 = self.clean_glob(text)
1022 else:
1022 else:
1023 m0 = self.clean_glob(text.replace('\\', ''))
1023 m0 = self.clean_glob(text.replace('\\', ''))
1024
1024
1025 if has_protectables:
1025 if has_protectables:
1026 # If we had protectables, we need to revert our changes to the
1026 # If we had protectables, we need to revert our changes to the
1027 # beginning of filename so that we don't double-write the part
1027 # beginning of filename so that we don't double-write the part
1028 # of the filename we have so far
1028 # of the filename we have so far
1029 len_lsplit = len(lsplit)
1029 len_lsplit = len(lsplit)
1030 matches = [text_prefix + text0 +
1030 matches = [text_prefix + text0 +
1031 protect_filename(f[len_lsplit:]) for f in m0]
1031 protect_filename(f[len_lsplit:]) for f in m0]
1032 else:
1032 else:
1033 if open_quotes:
1033 if open_quotes:
1034 # if we have a string with an open quote, we don't need to
1034 # if we have a string with an open quote, we don't need to
1035 # protect the names at all (and we _shouldn't_, as it
1035 # protect the names at all (and we _shouldn't_, as it
1036 # would cause bugs when the filesystem call is made).
1036 # would cause bugs when the filesystem call is made).
1037 matches = m0
1037 matches = m0
1038 else:
1038 else:
1039 matches = [text_prefix +
1039 matches = [text_prefix +
1040 protect_filename(f) for f in m0]
1040 protect_filename(f) for f in m0]
1041
1041
1042 # Mark directories in input list by appending '/' to their names.
1042 # Mark directories in input list by appending '/' to their names.
1043 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
1043 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
1044
1044
1045 def magic_matches(self, text):
1045 def magic_matches(self, text):
1046 """Match magics"""
1046 """Match magics"""
1047 # Get all shell magics now rather than statically, so magics loaded at
1047 # Get all shell magics now rather than statically, so magics loaded at
1048 # runtime show up too.
1048 # runtime show up too.
1049 lsm = self.shell.magics_manager.lsmagic()
1049 lsm = self.shell.magics_manager.lsmagic()
1050 line_magics = lsm['line']
1050 line_magics = lsm['line']
1051 cell_magics = lsm['cell']
1051 cell_magics = lsm['cell']
1052 pre = self.magic_escape
1052 pre = self.magic_escape
1053 pre2 = pre+pre
1053 pre2 = pre+pre
1054
1054
1055 # Completion logic:
1055 # Completion logic:
1056 # - user gives %%: only do cell magics
1056 # - user gives %%: only do cell magics
1057 # - user gives %: do both line and cell magics
1057 # - user gives %: do both line and cell magics
1058 # - no prefix: do both
1058 # - no prefix: do both
1059 # In other words, line magics are skipped if the user gives %% explicitly
1059 # In other words, line magics are skipped if the user gives %% explicitly
1060 bare_text = text.lstrip(pre)
1060 bare_text = text.lstrip(pre)
1061 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
1061 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
1062 if not text.startswith(pre2):
1062 if not text.startswith(pre2):
1063 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
1063 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
1064 return [cast_unicode_py2(c) for c in comp]
1064 return [cast_unicode_py2(c) for c in comp]
1065
1065
1066 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str):
1066 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str):
1067 """
1067 """
1068
1068
1069 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1069 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1070 cursor position.
1070 cursor position.
1071
1071
1072 Parameters
1072 Parameters
1073 ----------
1073 ----------
1074 cursor_column : int
1074 cursor_column : int
1075 column position of the cursor in ``text``, 0-indexed.
1075 column position of the cursor in ``text``, 0-indexed.
1076 cursor_line : int
1076 cursor_line : int
1077 line position of the cursor in ``text``, 0-indexed
1077 line position of the cursor in ``text``, 0-indexed
1078 text : str
1078 text : str
1079 text to complete
1079 text to complete
1080
1080
1081 Debugging
1081 Debugging
1082 ---------
1082 ---------
1083
1083
1084 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1084 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1085 object containing a string with the Jedi debug information attached.
1085 object containing a string with the Jedi debug information attached.
1086 """
1086 """
1087 namespaces = [self.namespace]
1087 namespaces = [self.namespace]
1088 if self.global_namespace is not None:
1088 if self.global_namespace is not None:
1089 namespaces.append(self.global_namespace)
1089 namespaces.append(self.global_namespace)
1090
1090
1091 # cursor_pos is an it, jedi wants line and column
1091 # cursor_pos is an it, jedi wants line and column
1092 offset = cursor_to_position(text, cursor_line, cursor_column)
1092 offset = cursor_to_position(text, cursor_line, cursor_column)
1093 if offset:
1093 if offset:
1094 pre = text[offset-1]
1094 pre = text[offset-1]
1095 completion_filter = lambda x:x
1095 completion_filter = lambda x:x
1096 if pre == '.':
1096 if pre == '.':
1097 if self.omit__names == 2:
1097 if self.omit__names == 2:
1098 completion_filter = lambda c:not c.name.startswith('_')
1098 completion_filter = lambda c:not c.name.startswith('_')
1099 elif self.omit__names == 1:
1099 elif self.omit__names == 1:
1100 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1100 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1101 elif self.omit__names == 0:
1101 elif self.omit__names == 0:
1102 completion_filter = lambda x:x
1102 completion_filter = lambda x:x
1103 else:
1103 else:
1104 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1104 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1105
1105
1106 interpreter = jedi.Interpreter(
1106 interpreter = jedi.Interpreter(
1107 text, namespaces, column=cursor_column, line=cursor_line + 1)
1107 text, namespaces, column=cursor_column, line=cursor_line + 1)
1108
1109 try_jedi = False
1110
1111 try:
1112 # should we check the type of the node is Error ?
1113 from jedi.parser.tree import ErrorLeaf
1114 next_to_last_tree = interpreter._get_module().tree_node.children[-2]
1115 completing_string = False
1116 if isinstance(next_to_last_tree, ErrorLeaf):
1117 completing_string = interpreter._get_module().tree_node.children[-2].value[0] in {'"', "'"}
1118 # if we are in a string jedi is likely not the right candidate for
1119 # now. Skip it.
1120 try_jedi = not completing_string
1121 except Exception as e:
1122 # many of things can go wrong, we are using private API just don't crash.
1123 if self.debug:
1124 print("Error detecting if completing a non-finished string :", e, '|')
1125
1126 if not try_jedi:
1127 return []
1108 try:
1128 try:
1109 return filter(completion_filter, interpreter.completions())
1129 return filter(completion_filter, interpreter.completions())
1110 except Exception as e:
1130 except Exception as e:
1111 if self.debug:
1131 if self.debug:
1112 return [_FakeJediCompletion('Opps Jedi has crash please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1132 return [_FakeJediCompletion('Opps Jedi has crash please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1113 else:
1133 else:
1114 return []
1134 return []
1115
1135
1116 def python_matches(self, text):
1136 def python_matches(self, text):
1117 """Match attributes or global python names"""
1137 """Match attributes or global python names"""
1118 if "." in text:
1138 if "." in text:
1119 try:
1139 try:
1120 matches = self.attr_matches(text)
1140 matches = self.attr_matches(text)
1121 if text.endswith('.') and self.omit__names:
1141 if text.endswith('.') and self.omit__names:
1122 if self.omit__names == 1:
1142 if self.omit__names == 1:
1123 # true if txt is _not_ a __ name, false otherwise:
1143 # true if txt is _not_ a __ name, false otherwise:
1124 no__name = (lambda txt:
1144 no__name = (lambda txt:
1125 re.match(r'.*\.__.*?__',txt) is None)
1145 re.match(r'.*\.__.*?__',txt) is None)
1126 else:
1146 else:
1127 # true if txt is _not_ a _ name, false otherwise:
1147 # true if txt is _not_ a _ name, false otherwise:
1128 no__name = (lambda txt:
1148 no__name = (lambda txt:
1129 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1149 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1130 matches = filter(no__name, matches)
1150 matches = filter(no__name, matches)
1131 except NameError:
1151 except NameError:
1132 # catches <undefined attributes>.<tab>
1152 # catches <undefined attributes>.<tab>
1133 matches = []
1153 matches = []
1134 else:
1154 else:
1135 matches = self.global_matches(text)
1155 matches = self.global_matches(text)
1136 return matches
1156 return matches
1137
1157
1138 def _default_arguments_from_docstring(self, doc):
1158 def _default_arguments_from_docstring(self, doc):
1139 """Parse the first line of docstring for call signature.
1159 """Parse the first line of docstring for call signature.
1140
1160
1141 Docstring should be of the form 'min(iterable[, key=func])\n'.
1161 Docstring should be of the form 'min(iterable[, key=func])\n'.
1142 It can also parse cython docstring of the form
1162 It can also parse cython docstring of the form
1143 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1163 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1144 """
1164 """
1145 if doc is None:
1165 if doc is None:
1146 return []
1166 return []
1147
1167
1148 #care only the firstline
1168 #care only the firstline
1149 line = doc.lstrip().splitlines()[0]
1169 line = doc.lstrip().splitlines()[0]
1150
1170
1151 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1171 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1152 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1172 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1153 sig = self.docstring_sig_re.search(line)
1173 sig = self.docstring_sig_re.search(line)
1154 if sig is None:
1174 if sig is None:
1155 return []
1175 return []
1156 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1176 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1157 sig = sig.groups()[0].split(',')
1177 sig = sig.groups()[0].split(',')
1158 ret = []
1178 ret = []
1159 for s in sig:
1179 for s in sig:
1160 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1180 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1161 ret += self.docstring_kwd_re.findall(s)
1181 ret += self.docstring_kwd_re.findall(s)
1162 return ret
1182 return ret
1163
1183
1164 def _default_arguments(self, obj):
1184 def _default_arguments(self, obj):
1165 """Return the list of default arguments of obj if it is callable,
1185 """Return the list of default arguments of obj if it is callable,
1166 or empty list otherwise."""
1186 or empty list otherwise."""
1167 call_obj = obj
1187 call_obj = obj
1168 ret = []
1188 ret = []
1169 if inspect.isbuiltin(obj):
1189 if inspect.isbuiltin(obj):
1170 pass
1190 pass
1171 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1191 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1172 if inspect.isclass(obj):
1192 if inspect.isclass(obj):
1173 #for cython embededsignature=True the constructor docstring
1193 #for cython embededsignature=True the constructor docstring
1174 #belongs to the object itself not __init__
1194 #belongs to the object itself not __init__
1175 ret += self._default_arguments_from_docstring(
1195 ret += self._default_arguments_from_docstring(
1176 getattr(obj, '__doc__', ''))
1196 getattr(obj, '__doc__', ''))
1177 # for classes, check for __init__,__new__
1197 # for classes, check for __init__,__new__
1178 call_obj = (getattr(obj, '__init__', None) or
1198 call_obj = (getattr(obj, '__init__', None) or
1179 getattr(obj, '__new__', None))
1199 getattr(obj, '__new__', None))
1180 # for all others, check if they are __call__able
1200 # for all others, check if they are __call__able
1181 elif hasattr(obj, '__call__'):
1201 elif hasattr(obj, '__call__'):
1182 call_obj = obj.__call__
1202 call_obj = obj.__call__
1183 ret += self._default_arguments_from_docstring(
1203 ret += self._default_arguments_from_docstring(
1184 getattr(call_obj, '__doc__', ''))
1204 getattr(call_obj, '__doc__', ''))
1185
1205
1186 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1206 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1187 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1207 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1188
1208
1189 try:
1209 try:
1190 sig = inspect.signature(call_obj)
1210 sig = inspect.signature(call_obj)
1191 ret.extend(k for k, v in sig.parameters.items() if
1211 ret.extend(k for k, v in sig.parameters.items() if
1192 v.kind in _keeps)
1212 v.kind in _keeps)
1193 except ValueError:
1213 except ValueError:
1194 pass
1214 pass
1195
1215
1196 return list(set(ret))
1216 return list(set(ret))
1197
1217
1198 def python_func_kw_matches(self,text):
1218 def python_func_kw_matches(self,text):
1199 """Match named parameters (kwargs) of the last open function"""
1219 """Match named parameters (kwargs) of the last open function"""
1200
1220
1201 if "." in text: # a parameter cannot be dotted
1221 if "." in text: # a parameter cannot be dotted
1202 return []
1222 return []
1203 try: regexp = self.__funcParamsRegex
1223 try: regexp = self.__funcParamsRegex
1204 except AttributeError:
1224 except AttributeError:
1205 regexp = self.__funcParamsRegex = re.compile(r'''
1225 regexp = self.__funcParamsRegex = re.compile(r'''
1206 '.*?(?<!\\)' | # single quoted strings or
1226 '.*?(?<!\\)' | # single quoted strings or
1207 ".*?(?<!\\)" | # double quoted strings or
1227 ".*?(?<!\\)" | # double quoted strings or
1208 \w+ | # identifier
1228 \w+ | # identifier
1209 \S # other characters
1229 \S # other characters
1210 ''', re.VERBOSE | re.DOTALL)
1230 ''', re.VERBOSE | re.DOTALL)
1211 # 1. find the nearest identifier that comes before an unclosed
1231 # 1. find the nearest identifier that comes before an unclosed
1212 # parenthesis before the cursor
1232 # parenthesis before the cursor
1213 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1233 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1214 tokens = regexp.findall(self.text_until_cursor)
1234 tokens = regexp.findall(self.text_until_cursor)
1215 iterTokens = reversed(tokens); openPar = 0
1235 iterTokens = reversed(tokens); openPar = 0
1216
1236
1217 for token in iterTokens:
1237 for token in iterTokens:
1218 if token == ')':
1238 if token == ')':
1219 openPar -= 1
1239 openPar -= 1
1220 elif token == '(':
1240 elif token == '(':
1221 openPar += 1
1241 openPar += 1
1222 if openPar > 0:
1242 if openPar > 0:
1223 # found the last unclosed parenthesis
1243 # found the last unclosed parenthesis
1224 break
1244 break
1225 else:
1245 else:
1226 return []
1246 return []
1227 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1247 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1228 ids = []
1248 ids = []
1229 isId = re.compile(r'\w+$').match
1249 isId = re.compile(r'\w+$').match
1230
1250
1231 while True:
1251 while True:
1232 try:
1252 try:
1233 ids.append(next(iterTokens))
1253 ids.append(next(iterTokens))
1234 if not isId(ids[-1]):
1254 if not isId(ids[-1]):
1235 ids.pop(); break
1255 ids.pop(); break
1236 if not next(iterTokens) == '.':
1256 if not next(iterTokens) == '.':
1237 break
1257 break
1238 except StopIteration:
1258 except StopIteration:
1239 break
1259 break
1240
1260
1241 # Find all named arguments already assigned to, as to avoid suggesting
1261 # Find all named arguments already assigned to, as to avoid suggesting
1242 # them again
1262 # them again
1243 usedNamedArgs = set()
1263 usedNamedArgs = set()
1244 par_level = -1
1264 par_level = -1
1245 for token, next_token in zip(tokens, tokens[1:]):
1265 for token, next_token in zip(tokens, tokens[1:]):
1246 if token == '(':
1266 if token == '(':
1247 par_level += 1
1267 par_level += 1
1248 elif token == ')':
1268 elif token == ')':
1249 par_level -= 1
1269 par_level -= 1
1250
1270
1251 if par_level != 0:
1271 if par_level != 0:
1252 continue
1272 continue
1253
1273
1254 if next_token != '=':
1274 if next_token != '=':
1255 continue
1275 continue
1256
1276
1257 usedNamedArgs.add(token)
1277 usedNamedArgs.add(token)
1258
1278
1259 # lookup the candidate callable matches either using global_matches
1279 # lookup the candidate callable matches either using global_matches
1260 # or attr_matches for dotted names
1280 # or attr_matches for dotted names
1261 if len(ids) == 1:
1281 if len(ids) == 1:
1262 callableMatches = self.global_matches(ids[0])
1282 callableMatches = self.global_matches(ids[0])
1263 else:
1283 else:
1264 callableMatches = self.attr_matches('.'.join(ids[::-1]))
1284 callableMatches = self.attr_matches('.'.join(ids[::-1]))
1265 argMatches = []
1285 argMatches = []
1266 for callableMatch in callableMatches:
1286 for callableMatch in callableMatches:
1267 try:
1287 try:
1268 namedArgs = self._default_arguments(eval(callableMatch,
1288 namedArgs = self._default_arguments(eval(callableMatch,
1269 self.namespace))
1289 self.namespace))
1270 except:
1290 except:
1271 continue
1291 continue
1272
1292
1273 # Remove used named arguments from the list, no need to show twice
1293 # Remove used named arguments from the list, no need to show twice
1274 for namedArg in set(namedArgs) - usedNamedArgs:
1294 for namedArg in set(namedArgs) - usedNamedArgs:
1275 if namedArg.startswith(text):
1295 if namedArg.startswith(text):
1276 argMatches.append(u"%s=" %namedArg)
1296 argMatches.append(u"%s=" %namedArg)
1277 return argMatches
1297 return argMatches
1278
1298
1279 def dict_key_matches(self, text):
1299 def dict_key_matches(self, text):
1280 "Match string keys in a dictionary, after e.g. 'foo[' "
1300 "Match string keys in a dictionary, after e.g. 'foo[' "
1281 def get_keys(obj):
1301 def get_keys(obj):
1282 # Objects can define their own completions by defining an
1302 # Objects can define their own completions by defining an
1283 # _ipy_key_completions_() method.
1303 # _ipy_key_completions_() method.
1284 method = get_real_method(obj, '_ipython_key_completions_')
1304 method = get_real_method(obj, '_ipython_key_completions_')
1285 if method is not None:
1305 if method is not None:
1286 return method()
1306 return method()
1287
1307
1288 # Special case some common in-memory dict-like types
1308 # Special case some common in-memory dict-like types
1289 if isinstance(obj, dict) or\
1309 if isinstance(obj, dict) or\
1290 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1310 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1291 try:
1311 try:
1292 return list(obj.keys())
1312 return list(obj.keys())
1293 except Exception:
1313 except Exception:
1294 return []
1314 return []
1295 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1315 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1296 _safe_isinstance(obj, 'numpy', 'void'):
1316 _safe_isinstance(obj, 'numpy', 'void'):
1297 return obj.dtype.names or []
1317 return obj.dtype.names or []
1298 return []
1318 return []
1299
1319
1300 try:
1320 try:
1301 regexps = self.__dict_key_regexps
1321 regexps = self.__dict_key_regexps
1302 except AttributeError:
1322 except AttributeError:
1303 dict_key_re_fmt = r'''(?x)
1323 dict_key_re_fmt = r'''(?x)
1304 ( # match dict-referring expression wrt greedy setting
1324 ( # match dict-referring expression wrt greedy setting
1305 %s
1325 %s
1306 )
1326 )
1307 \[ # open bracket
1327 \[ # open bracket
1308 \s* # and optional whitespace
1328 \s* # and optional whitespace
1309 ([uUbB]? # string prefix (r not handled)
1329 ([uUbB]? # string prefix (r not handled)
1310 (?: # unclosed string
1330 (?: # unclosed string
1311 '(?:[^']|(?<!\\)\\')*
1331 '(?:[^']|(?<!\\)\\')*
1312 |
1332 |
1313 "(?:[^"]|(?<!\\)\\")*
1333 "(?:[^"]|(?<!\\)\\")*
1314 )
1334 )
1315 )?
1335 )?
1316 $
1336 $
1317 '''
1337 '''
1318 regexps = self.__dict_key_regexps = {
1338 regexps = self.__dict_key_regexps = {
1319 False: re.compile(dict_key_re_fmt % '''
1339 False: re.compile(dict_key_re_fmt % '''
1320 # identifiers separated by .
1340 # identifiers separated by .
1321 (?!\d)\w+
1341 (?!\d)\w+
1322 (?:\.(?!\d)\w+)*
1342 (?:\.(?!\d)\w+)*
1323 '''),
1343 '''),
1324 True: re.compile(dict_key_re_fmt % '''
1344 True: re.compile(dict_key_re_fmt % '''
1325 .+
1345 .+
1326 ''')
1346 ''')
1327 }
1347 }
1328
1348
1329 match = regexps[self.greedy].search(self.text_until_cursor)
1349 match = regexps[self.greedy].search(self.text_until_cursor)
1330 if match is None:
1350 if match is None:
1331 return []
1351 return []
1332
1352
1333 expr, prefix = match.groups()
1353 expr, prefix = match.groups()
1334 try:
1354 try:
1335 obj = eval(expr, self.namespace)
1355 obj = eval(expr, self.namespace)
1336 except Exception:
1356 except Exception:
1337 try:
1357 try:
1338 obj = eval(expr, self.global_namespace)
1358 obj = eval(expr, self.global_namespace)
1339 except Exception:
1359 except Exception:
1340 return []
1360 return []
1341
1361
1342 keys = get_keys(obj)
1362 keys = get_keys(obj)
1343 if not keys:
1363 if not keys:
1344 return keys
1364 return keys
1345 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1365 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1346 if not matches:
1366 if not matches:
1347 return matches
1367 return matches
1348
1368
1349 # get the cursor position of
1369 # get the cursor position of
1350 # - the text being completed
1370 # - the text being completed
1351 # - the start of the key text
1371 # - the start of the key text
1352 # - the start of the completion
1372 # - the start of the completion
1353 text_start = len(self.text_until_cursor) - len(text)
1373 text_start = len(self.text_until_cursor) - len(text)
1354 if prefix:
1374 if prefix:
1355 key_start = match.start(2)
1375 key_start = match.start(2)
1356 completion_start = key_start + token_offset
1376 completion_start = key_start + token_offset
1357 else:
1377 else:
1358 key_start = completion_start = match.end()
1378 key_start = completion_start = match.end()
1359
1379
1360 # grab the leading prefix, to make sure all completions start with `text`
1380 # grab the leading prefix, to make sure all completions start with `text`
1361 if text_start > key_start:
1381 if text_start > key_start:
1362 leading = ''
1382 leading = ''
1363 else:
1383 else:
1364 leading = text[text_start:completion_start]
1384 leading = text[text_start:completion_start]
1365
1385
1366 # the index of the `[` character
1386 # the index of the `[` character
1367 bracket_idx = match.end(1)
1387 bracket_idx = match.end(1)
1368
1388
1369 # append closing quote and bracket as appropriate
1389 # append closing quote and bracket as appropriate
1370 # this is *not* appropriate if the opening quote or bracket is outside
1390 # this is *not* appropriate if the opening quote or bracket is outside
1371 # the text given to this method
1391 # the text given to this method
1372 suf = ''
1392 suf = ''
1373 continuation = self.line_buffer[len(self.text_until_cursor):]
1393 continuation = self.line_buffer[len(self.text_until_cursor):]
1374 if key_start > text_start and closing_quote:
1394 if key_start > text_start and closing_quote:
1375 # quotes were opened inside text, maybe close them
1395 # quotes were opened inside text, maybe close them
1376 if continuation.startswith(closing_quote):
1396 if continuation.startswith(closing_quote):
1377 continuation = continuation[len(closing_quote):]
1397 continuation = continuation[len(closing_quote):]
1378 else:
1398 else:
1379 suf += closing_quote
1399 suf += closing_quote
1380 if bracket_idx > text_start:
1400 if bracket_idx > text_start:
1381 # brackets were opened inside text, maybe close them
1401 # brackets were opened inside text, maybe close them
1382 if not continuation.startswith(']'):
1402 if not continuation.startswith(']'):
1383 suf += ']'
1403 suf += ']'
1384
1404
1385 return [leading + k + suf for k in matches]
1405 return [leading + k + suf for k in matches]
1386
1406
1387 def unicode_name_matches(self, text):
1407 def unicode_name_matches(self, text):
1388 u"""Match Latex-like syntax for unicode characters base
1408 u"""Match Latex-like syntax for unicode characters base
1389 on the name of the character.
1409 on the name of the character.
1390
1410
1391 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1411 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1392
1412
1393 Works only on valid python 3 identifier, or on combining characters that
1413 Works only on valid python 3 identifier, or on combining characters that
1394 will combine to form a valid identifier.
1414 will combine to form a valid identifier.
1395
1415
1396 Used on Python 3 only.
1416 Used on Python 3 only.
1397 """
1417 """
1398 slashpos = text.rfind('\\')
1418 slashpos = text.rfind('\\')
1399 if slashpos > -1:
1419 if slashpos > -1:
1400 s = text[slashpos+1:]
1420 s = text[slashpos+1:]
1401 try :
1421 try :
1402 unic = unicodedata.lookup(s)
1422 unic = unicodedata.lookup(s)
1403 # allow combining chars
1423 # allow combining chars
1404 if ('a'+unic).isidentifier():
1424 if ('a'+unic).isidentifier():
1405 return '\\'+s,[unic]
1425 return '\\'+s,[unic]
1406 except KeyError:
1426 except KeyError:
1407 pass
1427 pass
1408 return u'', []
1428 return u'', []
1409
1429
1410
1430
1411 def latex_matches(self, text):
1431 def latex_matches(self, text):
1412 u"""Match Latex syntax for unicode characters.
1432 u"""Match Latex syntax for unicode characters.
1413
1433
1414 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1434 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1415
1435
1416 Used on Python 3 only.
1436 Used on Python 3 only.
1417 """
1437 """
1418 slashpos = text.rfind('\\')
1438 slashpos = text.rfind('\\')
1419 if slashpos > -1:
1439 if slashpos > -1:
1420 s = text[slashpos:]
1440 s = text[slashpos:]
1421 if s in latex_symbols:
1441 if s in latex_symbols:
1422 # Try to complete a full latex symbol to unicode
1442 # Try to complete a full latex symbol to unicode
1423 # \\alpha -> Ξ±
1443 # \\alpha -> Ξ±
1424 return s, [latex_symbols[s]]
1444 return s, [latex_symbols[s]]
1425 else:
1445 else:
1426 # If a user has partially typed a latex symbol, give them
1446 # If a user has partially typed a latex symbol, give them
1427 # a full list of options \al -> [\aleph, \alpha]
1447 # a full list of options \al -> [\aleph, \alpha]
1428 matches = [k for k in latex_symbols if k.startswith(s)]
1448 matches = [k for k in latex_symbols if k.startswith(s)]
1429 return s, matches
1449 return s, matches
1430 return u'', []
1450 return u'', []
1431
1451
1432 def dispatch_custom_completer(self, text):
1452 def dispatch_custom_completer(self, text):
1433 if not self.custom_completers:
1453 if not self.custom_completers:
1434 return
1454 return
1435
1455
1436 line = self.line_buffer
1456 line = self.line_buffer
1437 if not line.strip():
1457 if not line.strip():
1438 return None
1458 return None
1439
1459
1440 # Create a little structure to pass all the relevant information about
1460 # Create a little structure to pass all the relevant information about
1441 # the current completion to any custom completer.
1461 # the current completion to any custom completer.
1442 event = SimpleNamespace()
1462 event = SimpleNamespace()
1443 event.line = line
1463 event.line = line
1444 event.symbol = text
1464 event.symbol = text
1445 cmd = line.split(None,1)[0]
1465 cmd = line.split(None,1)[0]
1446 event.command = cmd
1466 event.command = cmd
1447 event.text_until_cursor = self.text_until_cursor
1467 event.text_until_cursor = self.text_until_cursor
1448
1468
1449 # for foo etc, try also to find completer for %foo
1469 # for foo etc, try also to find completer for %foo
1450 if not cmd.startswith(self.magic_escape):
1470 if not cmd.startswith(self.magic_escape):
1451 try_magic = self.custom_completers.s_matches(
1471 try_magic = self.custom_completers.s_matches(
1452 self.magic_escape + cmd)
1472 self.magic_escape + cmd)
1453 else:
1473 else:
1454 try_magic = []
1474 try_magic = []
1455
1475
1456 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1476 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1457 try_magic,
1477 try_magic,
1458 self.custom_completers.flat_matches(self.text_until_cursor)):
1478 self.custom_completers.flat_matches(self.text_until_cursor)):
1459 try:
1479 try:
1460 res = c(event)
1480 res = c(event)
1461 if res:
1481 if res:
1462 # first, try case sensitive match
1482 # first, try case sensitive match
1463 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1483 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1464 if withcase:
1484 if withcase:
1465 return withcase
1485 return withcase
1466 # if none, then case insensitive ones are ok too
1486 # if none, then case insensitive ones are ok too
1467 text_low = text.lower()
1487 text_low = text.lower()
1468 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1488 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1469 except TryNext:
1489 except TryNext:
1470 pass
1490 pass
1471
1491
1472 return None
1492 return None
1473
1493
1474 def completions(self, text: str, offset: int)->Iterator[Completion]:
1494 def completions(self, text: str, offset: int)->Iterator[Completion]:
1475 """
1495 """
1476 Returns an iterator over the possible completions
1496 Returns an iterator over the possible completions
1477
1497
1478 .. warning:: Unstable
1498 .. warning:: Unstable
1479
1499
1480 This function is unstable, API may change without warning.
1500 This function is unstable, API may change without warning.
1481 It will also raise unless use in proper context manager.
1501 It will also raise unless use in proper context manager.
1482
1502
1483 Parameters
1503 Parameters
1484 ----------
1504 ----------
1485
1505
1486 text:str
1506 text:str
1487 Full text of the current input, multi line string.
1507 Full text of the current input, multi line string.
1488 offset:int
1508 offset:int
1489 Integer representing the position of the cursor in ``text``. Offset
1509 Integer representing the position of the cursor in ``text``. Offset
1490 is 0-based indexed.
1510 is 0-based indexed.
1491
1511
1492 Yields
1512 Yields
1493 ------
1513 ------
1494 :any:`Completion` object
1514 :any:`Completion` object
1495
1515
1496
1516
1497 The cursor on a text can either be seen as being "in between"
1517 The cursor on a text can either be seen as being "in between"
1498 characters or "On" a character depending on the interface visible to
1518 characters or "On" a character depending on the interface visible to
1499 the user. For consistency the cursor being on "in between" characters X
1519 the user. For consistency the cursor being on "in between" characters X
1500 and Y is equivalent to the cursor being "on" character Y, that is to say
1520 and Y is equivalent to the cursor being "on" character Y, that is to say
1501 the character the cursor is on is considered as being after the cursor.
1521 the character the cursor is on is considered as being after the cursor.
1502
1522
1503 Combining characters may span more that one position in the
1523 Combining characters may span more that one position in the
1504 text.
1524 text.
1505
1525
1506
1526
1507 .. note::
1527 .. note::
1508
1528
1509 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1529 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1510 fake Completion token to distinguish completion returned by Jedi
1530 fake Completion token to distinguish completion returned by Jedi
1511 and usual IPython completion.
1531 and usual IPython completion.
1512
1532
1513 """
1533 """
1514 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1534 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1515 "It may change without warnings. "
1535 "It may change without warnings. "
1516 "Use in corresponding context manager.",
1536 "Use in corresponding context manager.",
1517 category=ProvisionalCompleterWarning, stacklevel=2)
1537 category=ProvisionalCompleterWarning, stacklevel=2)
1518
1538
1519 # Possible Improvements / Known limitation
1539 # Possible Improvements / Known limitation
1520 ##########################################
1540 ##########################################
1521 # Completions may be identical even if they have different ranges and
1541 # Completions may be identical even if they have different ranges and
1522 # text. For example:
1542 # text. For example:
1523 # >>> a=1
1543 # >>> a=1
1524 # >>> a.<tab>
1544 # >>> a.<tab>
1525 # May returns:
1545 # May returns:
1526 # - `a.real` from 0 to 2
1546 # - `a.real` from 0 to 2
1527 # - `.real` from 1 to 2
1547 # - `.real` from 1 to 2
1528 # the current code does not (yet) check for such equivalence
1548 # the current code does not (yet) check for such equivalence
1529 seen = set()
1549 seen = set()
1530 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1550 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1531 if c and (c in seen):
1551 if c and (c in seen):
1532 continue
1552 continue
1533 yield c
1553 yield c
1534 seen.add(c)
1554 seen.add(c)
1535
1555
1536 def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]:
1556 def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]:
1537 """
1557 """
1538 Core completion module.Same signature as :any:`completions`, with the
1558 Core completion module.Same signature as :any:`completions`, with the
1539 extra `timeout` parameter (in seconds).
1559 extra `timeout` parameter (in seconds).
1540
1560
1541
1561
1542 Computing jedi's completion ``.type`` can be quite expensive (it is a
1562 Computing jedi's completion ``.type`` can be quite expensive (it is a
1543 lazy property) and can require some warm-up, more warm up than just
1563 lazy property) and can require some warm-up, more warm up than just
1544 computing the ``name`` of a completion. The warm-up can be :
1564 computing the ``name`` of a completion. The warm-up can be :
1545
1565
1546 - Long warm-up the fisrt time a module is encountered after
1566 - Long warm-up the fisrt time a module is encountered after
1547 install/update: actually build parse/inference tree.
1567 install/update: actually build parse/inference tree.
1548
1568
1549 - first time the module is encountered in a session: load tree from
1569 - first time the module is encountered in a session: load tree from
1550 disk.
1570 disk.
1551
1571
1552 We don't want to block completions for tens of seconds so we give the
1572 We don't want to block completions for tens of seconds so we give the
1553 completer a "budget" of ``_timeout`` seconds per invocation to compute
1573 completer a "budget" of ``_timeout`` seconds per invocation to compute
1554 completions types, the completions that have not yet been computed will
1574 completions types, the completions that have not yet been computed will
1555 be marked as "unknown" an will have a chance to be computed next round
1575 be marked as "unknown" an will have a chance to be computed next round
1556 are things get cached.
1576 are things get cached.
1557
1577
1558 Keep in mind that Jedi is not the only thing treating the completion so
1578 Keep in mind that Jedi is not the only thing treating the completion so
1559 keep the timeout short-ish as if we take more than 0.3 second we still
1579 keep the timeout short-ish as if we take more than 0.3 second we still
1560 have lots of processing to do.
1580 have lots of processing to do.
1561
1581
1562 """
1582 """
1563 deadline = time.monotonic() + _timeout
1583 deadline = time.monotonic() + _timeout
1564
1584
1565
1585
1566 before = full_text[:offset]
1586 before = full_text[:offset]
1567 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1587 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1568
1588
1569 matched_text, matches, matches_origin, jedi_matches = self._complete(
1589 matched_text, matches, matches_origin, jedi_matches = self._complete(
1570 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1590 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1571
1591
1572 iter_jm = iter(jedi_matches)
1592 iter_jm = iter(jedi_matches)
1573 if _timeout:
1593 if _timeout:
1574 for jm in iter_jm:
1594 for jm in iter_jm:
1575 try:
1595 try:
1576 type_ = jm.type
1596 type_ = jm.type
1577 except Exception:
1597 except Exception:
1578 if self.debug:
1598 if self.debug:
1579 print("Error in Jedi getting type of ", jm)
1599 print("Error in Jedi getting type of ", jm)
1580 type_ = None
1600 type_ = None
1581 delta = len(jm.name_with_symbols) - len(jm.complete)
1601 delta = len(jm.name_with_symbols) - len(jm.complete)
1582 yield Completion(start=offset - delta,
1602 yield Completion(start=offset - delta,
1583 end=offset,
1603 end=offset,
1584 text=jm.name_with_symbols,
1604 text=jm.name_with_symbols,
1585 type=type_,
1605 type=type_,
1586 _origin='jedi')
1606 _origin='jedi')
1587
1607
1588 if time.monotonic() > deadline:
1608 if time.monotonic() > deadline:
1589 break
1609 break
1590
1610
1591 for jm in iter_jm:
1611 for jm in iter_jm:
1592 delta = len(jm.name_with_symbols) - len(jm.complete)
1612 delta = len(jm.name_with_symbols) - len(jm.complete)
1593 yield Completion(start=offset - delta,
1613 yield Completion(start=offset - delta,
1594 end=offset,
1614 end=offset,
1595 text=jm.name_with_symbols,
1615 text=jm.name_with_symbols,
1596 type='<unknown>', # don't compute type for speed
1616 type='<unknown>', # don't compute type for speed
1597 _origin='jedi')
1617 _origin='jedi')
1598
1618
1599
1619
1600 start_offset = before.rfind(matched_text)
1620 start_offset = before.rfind(matched_text)
1601
1621
1602 # TODO:
1622 # TODO:
1603 # Supress this, right now just for debug.
1623 # Supress this, right now just for debug.
1604 if jedi_matches and matches and self.debug:
1624 if jedi_matches and matches and self.debug:
1605 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', _origin='debug')
1625 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--', _origin='debug')
1606
1626
1607 # I'm unsure if this is always true, so let's assert and see if it
1627 # I'm unsure if this is always true, so let's assert and see if it
1608 # crash
1628 # crash
1609 assert before.endswith(matched_text)
1629 assert before.endswith(matched_text)
1610 for m, t in zip(matches, matches_origin):
1630 for m, t in zip(matches, matches_origin):
1611 yield Completion(start=start_offset, end=offset, text=m, _origin=t)
1631 yield Completion(start=start_offset, end=offset, text=m, _origin=t)
1612
1632
1613
1633
1614 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1634 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1615 """Find completions for the given text and line context.
1635 """Find completions for the given text and line context.
1616
1636
1617 Note that both the text and the line_buffer are optional, but at least
1637 Note that both the text and the line_buffer are optional, but at least
1618 one of them must be given.
1638 one of them must be given.
1619
1639
1620 Parameters
1640 Parameters
1621 ----------
1641 ----------
1622 text : string, optional
1642 text : string, optional
1623 Text to perform the completion on. If not given, the line buffer
1643 Text to perform the completion on. If not given, the line buffer
1624 is split using the instance's CompletionSplitter object.
1644 is split using the instance's CompletionSplitter object.
1625
1645
1626 line_buffer : string, optional
1646 line_buffer : string, optional
1627 If not given, the completer attempts to obtain the current line
1647 If not given, the completer attempts to obtain the current line
1628 buffer via readline. This keyword allows clients which are
1648 buffer via readline. This keyword allows clients which are
1629 requesting for text completions in non-readline contexts to inform
1649 requesting for text completions in non-readline contexts to inform
1630 the completer of the entire text.
1650 the completer of the entire text.
1631
1651
1632 cursor_pos : int, optional
1652 cursor_pos : int, optional
1633 Index of the cursor in the full line buffer. Should be provided by
1653 Index of the cursor in the full line buffer. Should be provided by
1634 remote frontends where kernel has no access to frontend state.
1654 remote frontends where kernel has no access to frontend state.
1635
1655
1636 Returns
1656 Returns
1637 -------
1657 -------
1638 text : str
1658 text : str
1639 Text that was actually used in the completion.
1659 Text that was actually used in the completion.
1640
1660
1641 matches : list
1661 matches : list
1642 A list of completion matches.
1662 A list of completion matches.
1643
1663
1644
1664
1645 .. note::
1665 .. note::
1646
1666
1647 This API is likely to be deprecated and replaced by
1667 This API is likely to be deprecated and replaced by
1648 :any:`IPCompleter.completions` in the future.
1668 :any:`IPCompleter.completions` in the future.
1649
1669
1650
1670
1651 """
1671 """
1652 warnings.warn('`Completer.complete` is pending deprecation since '
1672 warnings.warn('`Completer.complete` is pending deprecation since '
1653 'IPython 6.0 and will be replaced by `Completer.completions`.',
1673 'IPython 6.0 and will be replaced by `Completer.completions`.',
1654 PendingDeprecationWarning)
1674 PendingDeprecationWarning)
1655 # potential todo, FOLD the 3rd throw away argument of _complete
1675 # potential todo, FOLD the 3rd throw away argument of _complete
1656 # into the first 2 one.
1676 # into the first 2 one.
1657 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
1677 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
1658
1678
1659 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
1679 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
1660 full_text=None, return_jedi_results=True) -> (str, List[str], List[object]):
1680 full_text=None, return_jedi_results=True) -> (str, List[str], List[object]):
1661 """
1681 """
1662
1682
1663 Like complete but can also returns raw jedi completions as well as the
1683 Like complete but can also returns raw jedi completions as well as the
1664 origin of the completion text. This could (and should) be made much
1684 origin of the completion text. This could (and should) be made much
1665 cleaner but that will be simpler once we drop the old (and stateful)
1685 cleaner but that will be simpler once we drop the old (and stateful)
1666 :any:`complete` API.
1686 :any:`complete` API.
1667
1687
1668
1688
1669 With current provisional API, cursor_pos act both (depending on the
1689 With current provisional API, cursor_pos act both (depending on the
1670 caller) as the offset in the ``text`` or ``line_buffer``, or as the
1690 caller) as the offset in the ``text`` or ``line_buffer``, or as the
1671 ``column`` when passing multiline strings this could/should be renamed
1691 ``column`` when passing multiline strings this could/should be renamed
1672 but would add extra noise.
1692 but would add extra noise.
1673 """
1693 """
1674
1694
1675 # if the cursor position isn't given, the only sane assumption we can
1695 # if the cursor position isn't given, the only sane assumption we can
1676 # make is that it's at the end of the line (the common case)
1696 # make is that it's at the end of the line (the common case)
1677 if cursor_pos is None:
1697 if cursor_pos is None:
1678 cursor_pos = len(line_buffer) if text is None else len(text)
1698 cursor_pos = len(line_buffer) if text is None else len(text)
1679
1699
1680 if self.use_main_ns:
1700 if self.use_main_ns:
1681 self.namespace = __main__.__dict__
1701 self.namespace = __main__.__dict__
1682
1702
1683 # if text is either None or an empty string, rely on the line buffer
1703 # if text is either None or an empty string, rely on the line buffer
1684 if (not line_buffer) and full_text:
1704 if (not line_buffer) and full_text:
1685 line_buffer = full_text.split('\n')[cursor_line]
1705 line_buffer = full_text.split('\n')[cursor_line]
1686 if not text:
1706 if not text:
1687 text = self.splitter.split_line(line_buffer, cursor_pos)
1707 text = self.splitter.split_line(line_buffer, cursor_pos)
1688
1708
1689 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1709 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1690 latex_text, latex_matches = self.latex_matches(base_text)
1710 latex_text, latex_matches = self.latex_matches(base_text)
1691 if latex_matches:
1711 if latex_matches:
1692 return latex_text, latex_matches, ['latex_matches']*len(latex_matches), ()
1712 return latex_text, latex_matches, ['latex_matches']*len(latex_matches), ()
1693 name_text = ''
1713 name_text = ''
1694 name_matches = []
1714 name_matches = []
1695 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1715 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1696 name_text, name_matches = meth(base_text)
1716 name_text, name_matches = meth(base_text)
1697 if name_text:
1717 if name_text:
1698 return name_text, name_matches, [meth.__qualname__]*len(name_matches), {}
1718 return name_text, name_matches, [meth.__qualname__]*len(name_matches), {}
1699
1719
1700
1720
1701 # If no line buffer is given, assume the input text is all there was
1721 # If no line buffer is given, assume the input text is all there was
1702 if line_buffer is None:
1722 if line_buffer is None:
1703 line_buffer = text
1723 line_buffer = text
1704
1724
1705 self.line_buffer = line_buffer
1725 self.line_buffer = line_buffer
1706 self.text_until_cursor = self.line_buffer[:cursor_pos]
1726 self.text_until_cursor = self.line_buffer[:cursor_pos]
1707
1727
1708 # Start with a clean slate of completions
1728 # Start with a clean slate of completions
1709 matches = []
1729 matches = []
1710 custom_res = self.dispatch_custom_completer(text)
1730 custom_res = self.dispatch_custom_completer(text)
1711 # FIXME: we should extend our api to return a dict with completions for
1731 # FIXME: we should extend our api to return a dict with completions for
1712 # different types of objects. The rlcomplete() method could then
1732 # different types of objects. The rlcomplete() method could then
1713 # simply collapse the dict into a list for readline, but we'd have
1733 # simply collapse the dict into a list for readline, but we'd have
1714 # richer completion semantics in other evironments.
1734 # richer completion semantics in other evironments.
1715 completions = ()
1735 completions = ()
1716 if self.use_jedi and return_jedi_results:
1736 if self.use_jedi and return_jedi_results:
1717 if not full_text:
1737 if not full_text:
1718 full_text = line_buffer
1738 full_text = line_buffer
1719 completions = self._jedi_matches(
1739 completions = self._jedi_matches(
1720 cursor_pos, cursor_line, full_text)
1740 cursor_pos, cursor_line, full_text)
1721 if custom_res is not None:
1741 if custom_res is not None:
1722 # did custom completers produce something?
1742 # did custom completers produce something?
1723 matches = [(m, 'custom') for m in custom_res]
1743 matches = [(m, 'custom') for m in custom_res]
1724 else:
1744 else:
1725 # Extend the list of completions with the results of each
1745 # Extend the list of completions with the results of each
1726 # matcher, so we return results to the user from all
1746 # matcher, so we return results to the user from all
1727 # namespaces.
1747 # namespaces.
1728 if self.merge_completions:
1748 if self.merge_completions:
1729 matches = []
1749 matches = []
1730 for matcher in self.matchers:
1750 for matcher in self.matchers:
1731 try:
1751 try:
1732 matches.extend([(m, matcher.__qualname__)
1752 matches.extend([(m, matcher.__qualname__)
1733 for m in matcher(text)])
1753 for m in matcher(text)])
1734 except:
1754 except:
1735 # Show the ugly traceback if the matcher causes an
1755 # Show the ugly traceback if the matcher causes an
1736 # exception, but do NOT crash the kernel!
1756 # exception, but do NOT crash the kernel!
1737 sys.excepthook(*sys.exc_info())
1757 sys.excepthook(*sys.exc_info())
1738 else:
1758 else:
1739 for matcher in self.matchers:
1759 for matcher in self.matchers:
1740 matches = [(m, matcher.__qualname__)
1760 matches = [(m, matcher.__qualname__)
1741 for m in matcher(text)]
1761 for m in matcher(text)]
1742 if matches:
1762 if matches:
1743 break
1763 break
1744 seen = set()
1764 seen = set()
1745 filtered_matches = set()
1765 filtered_matches = set()
1746 for m in matches:
1766 for m in matches:
1747 t, c = m
1767 t, c = m
1748 if t not in seen:
1768 if t not in seen:
1749 filtered_matches.add(m)
1769 filtered_matches.add(m)
1750 seen.add(t)
1770 seen.add(t)
1751
1771
1752 filtered_matches = sorted(
1772 filtered_matches = sorted(
1753 set(filtered_matches), key=lambda x: completions_sorting_key(x[0]))
1773 set(filtered_matches), key=lambda x: completions_sorting_key(x[0]))
1754
1774
1755 matches = [m[0] for m in filtered_matches]
1775 matches = [m[0] for m in filtered_matches]
1756 origins = [m[1] for m in filtered_matches]
1776 origins = [m[1] for m in filtered_matches]
1757
1777
1758 self.matches = matches
1778 self.matches = matches
1759
1779
1760 return text, matches, origins, completions
1780 return text, matches, origins, completions
General Comments 0
You need to be logged in to leave comments. Login now