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