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