##// END OF EJS Templates
Remove deprecated banner parameter...
Matthias Bussonnier -
Show More
@@ -1,2266 +1,2266 b''
1 """Completion for IPython.
1 """Completion for IPython.
2
2
3 This module started as fork of the rlcompleter module in the Python standard
3 This module started as fork of the rlcompleter module in the Python standard
4 library. The original enhancements made to rlcompleter have been sent
4 library. The original enhancements made to rlcompleter have been sent
5 upstream and were accepted as of Python 2.3,
5 upstream and were accepted as of Python 2.3,
6
6
7 This module now support a wide variety of completion mechanism both available
7 This module now support a wide variety of completion mechanism both available
8 for normal classic Python code, as well as completer for IPython specific
8 for normal classic Python code, as well as completer for IPython specific
9 Syntax like magics.
9 Syntax like magics.
10
10
11 Latex and Unicode completion
11 Latex and Unicode completion
12 ============================
12 ============================
13
13
14 IPython and compatible frontends not only can complete your code, but can help
14 IPython and compatible frontends not only can complete your code, but can help
15 you to input a wide range of characters. In particular we allow you to insert
15 you to input a wide range of characters. In particular we allow you to insert
16 a unicode character using the tab completion mechanism.
16 a unicode character using the tab completion mechanism.
17
17
18 Forward latex/unicode completion
18 Forward latex/unicode completion
19 --------------------------------
19 --------------------------------
20
20
21 Forward completion allows you to easily type a unicode character using its latex
21 Forward completion allows you to easily type a unicode character using its latex
22 name, or unicode long description. To do so type a backslash follow by the
22 name, or unicode long description. To do so type a backslash follow by the
23 relevant name and press tab:
23 relevant name and press tab:
24
24
25
25
26 Using latex completion:
26 Using latex completion:
27
27
28 .. code::
28 .. code::
29
29
30 \\alpha<tab>
30 \\alpha<tab>
31 α
31 α
32
32
33 or using unicode completion:
33 or using unicode completion:
34
34
35
35
36 .. code::
36 .. code::
37
37
38 \\GREEK SMALL LETTER ALPHA<tab>
38 \\GREEK SMALL LETTER ALPHA<tab>
39 α
39 α
40
40
41
41
42 Only valid Python identifiers will complete. Combining characters (like arrow or
42 Only valid Python identifiers will complete. Combining characters (like arrow or
43 dots) are also available, unlike latex they need to be put after the their
43 dots) are also available, unlike latex they need to be put after the their
44 counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`.
44 counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`.
45
45
46 Some browsers are known to display combining characters incorrectly.
46 Some browsers are known to display combining characters incorrectly.
47
47
48 Backward latex completion
48 Backward latex completion
49 -------------------------
49 -------------------------
50
50
51 It is sometime challenging to know how to type a character, if you are using
51 It is sometime challenging to know how to type a character, if you are using
52 IPython, or any compatible frontend you can prepend backslash to the character
52 IPython, or any compatible frontend you can prepend backslash to the character
53 and press `<tab>` to expand it to its latex form.
53 and press `<tab>` to expand it to its latex form.
54
54
55 .. code::
55 .. code::
56
56
57 \\α<tab>
57 \\α<tab>
58 \\alpha
58 \\alpha
59
59
60
60
61 Both forward and backward completions can be deactivated by setting the
61 Both forward and backward completions can be deactivated by setting the
62 ``Completer.backslash_combining_completions`` option to ``False``.
62 ``Completer.backslash_combining_completions`` option to ``False``.
63
63
64
64
65 Experimental
65 Experimental
66 ============
66 ============
67
67
68 Starting with IPython 6.0, this module can make use of the Jedi library to
68 Starting with IPython 6.0, this module can make use of the Jedi library to
69 generate completions both using static analysis of the code, and dynamically
69 generate completions both using static analysis of the code, and dynamically
70 inspecting multiple namespaces. Jedi is an autocompletion and static analysis
70 inspecting multiple namespaces. Jedi is an autocompletion and static analysis
71 for Python. The APIs attached to this new mechanism is unstable and will
71 for Python. The APIs attached to this new mechanism is unstable and will
72 raise unless use in an :any:`provisionalcompleter` context manager.
72 raise unless use in an :any:`provisionalcompleter` context manager.
73
73
74 You will find that the following are experimental:
74 You will find that the following are experimental:
75
75
76 - :any:`provisionalcompleter`
76 - :any:`provisionalcompleter`
77 - :any:`IPCompleter.completions`
77 - :any:`IPCompleter.completions`
78 - :any:`Completion`
78 - :any:`Completion`
79 - :any:`rectify_completions`
79 - :any:`rectify_completions`
80
80
81 .. note::
81 .. note::
82
82
83 better name for :any:`rectify_completions` ?
83 better name for :any:`rectify_completions` ?
84
84
85 We welcome any feedback on these new API, and we also encourage you to try this
85 We welcome any feedback on these new API, and we also encourage you to try this
86 module in debug mode (start IPython with ``--Completer.debug=True``) in order
86 module in debug mode (start IPython with ``--Completer.debug=True``) in order
87 to have extra logging information if :any:`jedi` is crashing, or if current
87 to have extra logging information if :any:`jedi` is crashing, or if current
88 IPython completer pending deprecations are returning results not yet handled
88 IPython completer pending deprecations are returning results not yet handled
89 by :any:`jedi`
89 by :any:`jedi`
90
90
91 Using Jedi for tab completion allow snippets like the following to work without
91 Using Jedi for tab completion allow snippets like the following to work without
92 having to execute any code:
92 having to execute any code:
93
93
94 >>> myvar = ['hello', 42]
94 >>> myvar = ['hello', 42]
95 ... myvar[1].bi<tab>
95 ... myvar[1].bi<tab>
96
96
97 Tab completion will be able to infer that ``myvar[1]`` is a real number without
97 Tab completion will be able to infer that ``myvar[1]`` is a real number without
98 executing any code unlike the previously available ``IPCompleter.greedy``
98 executing any code unlike the previously available ``IPCompleter.greedy``
99 option.
99 option.
100
100
101 Be sure to update :any:`jedi` to the latest stable version or to try the
101 Be sure to update :any:`jedi` to the latest stable version or to try the
102 current development version to get better completions.
102 current development version to get better completions.
103 """
103 """
104
104
105
105
106 # Copyright (c) IPython Development Team.
106 # Copyright (c) IPython Development Team.
107 # Distributed under the terms of the Modified BSD License.
107 # Distributed under the terms of the Modified BSD License.
108 #
108 #
109 # Some of this code originated from rlcompleter in the Python standard library
109 # Some of this code originated from rlcompleter in the Python standard library
110 # Copyright (C) 2001 Python Software Foundation, www.python.org
110 # Copyright (C) 2001 Python Software Foundation, www.python.org
111
111
112
112
113 import builtins as builtin_mod
113 import builtins as builtin_mod
114 import glob
114 import glob
115 import inspect
115 import inspect
116 import itertools
116 import itertools
117 import keyword
117 import keyword
118 import os
118 import os
119 import re
119 import re
120 import string
120 import string
121 import sys
121 import sys
122 import time
122 import time
123 import unicodedata
123 import unicodedata
124 import uuid
124 import uuid
125 import warnings
125 import warnings
126 from contextlib import contextmanager
126 from contextlib import contextmanager
127 from importlib import import_module
127 from importlib import import_module
128 from types import SimpleNamespace
128 from types import SimpleNamespace
129 from typing import Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, NamedTuple, Pattern, Optional
129 from typing import Iterable, Iterator, List, Tuple, Union, Any, Sequence, Dict, NamedTuple, Pattern, Optional
130
130
131 from IPython.core.error import TryNext
131 from IPython.core.error import TryNext
132 from IPython.core.inputtransformer2 import ESC_MAGIC
132 from IPython.core.inputtransformer2 import ESC_MAGIC
133 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
133 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
134 from IPython.core.oinspect import InspectColors
134 from IPython.core.oinspect import InspectColors
135 from IPython.testing.skipdoctest import skip_doctest
135 from IPython.testing.skipdoctest import skip_doctest
136 from IPython.utils import generics
136 from IPython.utils import generics
137 from IPython.utils.dir2 import dir2, get_real_method
137 from IPython.utils.dir2 import dir2, get_real_method
138 from IPython.utils.path import ensure_dir_exists
138 from IPython.utils.path import ensure_dir_exists
139 from IPython.utils.process import arg_split
139 from IPython.utils.process import arg_split
140 from traitlets import Bool, Enum, Int, List as ListTrait, Unicode, default, observe
140 from traitlets import Bool, Enum, Int, List as ListTrait, Unicode, default, observe
141 from traitlets.config.configurable import Configurable
141 from traitlets.config.configurable import Configurable
142
142
143 import __main__
143 import __main__
144
144
145 # skip module docstests
145 # skip module docstests
146 __skip_doctest__ = True
146 __skip_doctest__ = True
147
147
148 try:
148 try:
149 import jedi
149 import jedi
150 jedi.settings.case_insensitive_completion = False
150 jedi.settings.case_insensitive_completion = False
151 import jedi.api.helpers
151 import jedi.api.helpers
152 import jedi.api.classes
152 import jedi.api.classes
153 JEDI_INSTALLED = True
153 JEDI_INSTALLED = True
154 except ImportError:
154 except ImportError:
155 JEDI_INSTALLED = False
155 JEDI_INSTALLED = False
156 #-----------------------------------------------------------------------------
156 #-----------------------------------------------------------------------------
157 # Globals
157 # Globals
158 #-----------------------------------------------------------------------------
158 #-----------------------------------------------------------------------------
159
159
160 # ranges where we have most of the valid unicode names. We could be more finer
160 # ranges where we have most of the valid unicode names. We could be more finer
161 # grained but is it worth it for performance While unicode have character in the
161 # grained but is it worth it for performance While unicode have character in the
162 # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
162 # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
163 # write this). With below range we cover them all, with a density of ~67%
163 # write this). With below range we cover them all, with a density of ~67%
164 # biggest next gap we consider only adds up about 1% density and there are 600
164 # biggest next gap we consider only adds up about 1% density and there are 600
165 # gaps that would need hard coding.
165 # gaps that would need hard coding.
166 _UNICODE_RANGES = [(32, 0x3134b), (0xe0001, 0xe01f0)]
166 _UNICODE_RANGES = [(32, 0x3134b), (0xe0001, 0xe01f0)]
167
167
168 # Public API
168 # Public API
169 __all__ = ['Completer','IPCompleter']
169 __all__ = ['Completer','IPCompleter']
170
170
171 if sys.platform == 'win32':
171 if sys.platform == 'win32':
172 PROTECTABLES = ' '
172 PROTECTABLES = ' '
173 else:
173 else:
174 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
174 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
175
175
176 # Protect against returning an enormous number of completions which the frontend
176 # Protect against returning an enormous number of completions which the frontend
177 # may have trouble processing.
177 # may have trouble processing.
178 MATCHES_LIMIT = 500
178 MATCHES_LIMIT = 500
179
179
180
180
181 class Sentinel:
181 class Sentinel:
182 def __repr__(self):
182 def __repr__(self):
183 return "<deprecated sentinel>"
183 return "<deprecated sentinel>"
184
184
185
185
186 _deprecation_readline_sentinel = Sentinel()
186 _deprecation_readline_sentinel = Sentinel()
187
187
188
188
189 class ProvisionalCompleterWarning(FutureWarning):
189 class ProvisionalCompleterWarning(FutureWarning):
190 """
190 """
191 Exception raise by an experimental feature in this module.
191 Exception raise by an experimental feature in this module.
192
192
193 Wrap code in :any:`provisionalcompleter` context manager if you
193 Wrap code in :any:`provisionalcompleter` context manager if you
194 are certain you want to use an unstable feature.
194 are certain you want to use an unstable feature.
195 """
195 """
196 pass
196 pass
197
197
198 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
198 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
199
199
200
200
201 @skip_doctest
201 @skip_doctest
202 @contextmanager
202 @contextmanager
203 def provisionalcompleter(action='ignore'):
203 def provisionalcompleter(action='ignore'):
204 """
204 """
205 This context manager has to be used in any place where unstable completer
205 This context manager has to be used in any place where unstable completer
206 behavior and API may be called.
206 behavior and API may be called.
207
207
208 >>> with provisionalcompleter():
208 >>> with provisionalcompleter():
209 ... completer.do_experimental_things() # works
209 ... completer.do_experimental_things() # works
210
210
211 >>> completer.do_experimental_things() # raises.
211 >>> completer.do_experimental_things() # raises.
212
212
213 .. note::
213 .. note::
214
214
215 Unstable
215 Unstable
216
216
217 By using this context manager you agree that the API in use may change
217 By using this context manager you agree that the API in use may change
218 without warning, and that you won't complain if they do so.
218 without warning, and that you won't complain if they do so.
219
219
220 You also understand that, if the API is not to your liking, you should report
220 You also understand that, if the API is not to your liking, you should report
221 a bug to explain your use case upstream.
221 a bug to explain your use case upstream.
222
222
223 We'll be happy to get your feedback, feature requests, and improvements on
223 We'll be happy to get your feedback, feature requests, and improvements on
224 any of the unstable APIs!
224 any of the unstable APIs!
225 """
225 """
226 with warnings.catch_warnings():
226 with warnings.catch_warnings():
227 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
227 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
228 yield
228 yield
229
229
230
230
231 def has_open_quotes(s):
231 def has_open_quotes(s):
232 """Return whether a string has open quotes.
232 """Return whether a string has open quotes.
233
233
234 This simply counts whether the number of quote characters of either type in
234 This simply counts whether the number of quote characters of either type in
235 the string is odd.
235 the string is odd.
236
236
237 Returns
237 Returns
238 -------
238 -------
239 If there is an open quote, the quote character is returned. Else, return
239 If there is an open quote, the quote character is returned. Else, return
240 False.
240 False.
241 """
241 """
242 # We check " first, then ', so complex cases with nested quotes will get
242 # We check " first, then ', so complex cases with nested quotes will get
243 # the " to take precedence.
243 # the " to take precedence.
244 if s.count('"') % 2:
244 if s.count('"') % 2:
245 return '"'
245 return '"'
246 elif s.count("'") % 2:
246 elif s.count("'") % 2:
247 return "'"
247 return "'"
248 else:
248 else:
249 return False
249 return False
250
250
251
251
252 def protect_filename(s, protectables=PROTECTABLES):
252 def protect_filename(s, protectables=PROTECTABLES):
253 """Escape a string to protect certain characters."""
253 """Escape a string to protect certain characters."""
254 if set(s) & set(protectables):
254 if set(s) & set(protectables):
255 if sys.platform == "win32":
255 if sys.platform == "win32":
256 return '"' + s + '"'
256 return '"' + s + '"'
257 else:
257 else:
258 return "".join(("\\" + c if c in protectables else c) for c in s)
258 return "".join(("\\" + c if c in protectables else c) for c in s)
259 else:
259 else:
260 return s
260 return s
261
261
262
262
263 def expand_user(path:str) -> Tuple[str, bool, str]:
263 def expand_user(path:str) -> Tuple[str, bool, str]:
264 """Expand ``~``-style usernames in strings.
264 """Expand ``~``-style usernames in strings.
265
265
266 This is similar to :func:`os.path.expanduser`, but it computes and returns
266 This is similar to :func:`os.path.expanduser`, but it computes and returns
267 extra information that will be useful if the input was being used in
267 extra information that will be useful if the input was being used in
268 computing completions, and you wish to return the completions with the
268 computing completions, and you wish to return the completions with the
269 original '~' instead of its expanded value.
269 original '~' instead of its expanded value.
270
270
271 Parameters
271 Parameters
272 ----------
272 ----------
273 path : str
273 path : str
274 String to be expanded. If no ~ is present, the output is the same as the
274 String to be expanded. If no ~ is present, the output is the same as the
275 input.
275 input.
276
276
277 Returns
277 Returns
278 -------
278 -------
279 newpath : str
279 newpath : str
280 Result of ~ expansion in the input path.
280 Result of ~ expansion in the input path.
281 tilde_expand : bool
281 tilde_expand : bool
282 Whether any expansion was performed or not.
282 Whether any expansion was performed or not.
283 tilde_val : str
283 tilde_val : str
284 The value that ~ was replaced with.
284 The value that ~ was replaced with.
285 """
285 """
286 # Default values
286 # Default values
287 tilde_expand = False
287 tilde_expand = False
288 tilde_val = ''
288 tilde_val = ''
289 newpath = path
289 newpath = path
290
290
291 if path.startswith('~'):
291 if path.startswith('~'):
292 tilde_expand = True
292 tilde_expand = True
293 rest = len(path)-1
293 rest = len(path)-1
294 newpath = os.path.expanduser(path)
294 newpath = os.path.expanduser(path)
295 if rest:
295 if rest:
296 tilde_val = newpath[:-rest]
296 tilde_val = newpath[:-rest]
297 else:
297 else:
298 tilde_val = newpath
298 tilde_val = newpath
299
299
300 return newpath, tilde_expand, tilde_val
300 return newpath, tilde_expand, tilde_val
301
301
302
302
303 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
303 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
304 """Does the opposite of expand_user, with its outputs.
304 """Does the opposite of expand_user, with its outputs.
305 """
305 """
306 if tilde_expand:
306 if tilde_expand:
307 return path.replace(tilde_val, '~')
307 return path.replace(tilde_val, '~')
308 else:
308 else:
309 return path
309 return path
310
310
311
311
312 def completions_sorting_key(word):
312 def completions_sorting_key(word):
313 """key for sorting completions
313 """key for sorting completions
314
314
315 This does several things:
315 This does several things:
316
316
317 - Demote any completions starting with underscores to the end
317 - Demote any completions starting with underscores to the end
318 - Insert any %magic and %%cellmagic completions in the alphabetical order
318 - Insert any %magic and %%cellmagic completions in the alphabetical order
319 by their name
319 by their name
320 """
320 """
321 prio1, prio2 = 0, 0
321 prio1, prio2 = 0, 0
322
322
323 if word.startswith('__'):
323 if word.startswith('__'):
324 prio1 = 2
324 prio1 = 2
325 elif word.startswith('_'):
325 elif word.startswith('_'):
326 prio1 = 1
326 prio1 = 1
327
327
328 if word.endswith('='):
328 if word.endswith('='):
329 prio1 = -1
329 prio1 = -1
330
330
331 if word.startswith('%%'):
331 if word.startswith('%%'):
332 # If there's another % in there, this is something else, so leave it alone
332 # If there's another % in there, this is something else, so leave it alone
333 if not "%" in word[2:]:
333 if not "%" in word[2:]:
334 word = word[2:]
334 word = word[2:]
335 prio2 = 2
335 prio2 = 2
336 elif word.startswith('%'):
336 elif word.startswith('%'):
337 if not "%" in word[1:]:
337 if not "%" in word[1:]:
338 word = word[1:]
338 word = word[1:]
339 prio2 = 1
339 prio2 = 1
340
340
341 return prio1, word, prio2
341 return prio1, word, prio2
342
342
343
343
344 class _FakeJediCompletion:
344 class _FakeJediCompletion:
345 """
345 """
346 This is a workaround to communicate to the UI that Jedi has crashed and to
346 This is a workaround to communicate to the UI that Jedi has crashed and to
347 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
347 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
348
348
349 Added in IPython 6.0 so should likely be removed for 7.0
349 Added in IPython 6.0 so should likely be removed for 7.0
350
350
351 """
351 """
352
352
353 def __init__(self, name):
353 def __init__(self, name):
354
354
355 self.name = name
355 self.name = name
356 self.complete = name
356 self.complete = name
357 self.type = 'crashed'
357 self.type = 'crashed'
358 self.name_with_symbols = name
358 self.name_with_symbols = name
359 self.signature = ''
359 self.signature = ''
360 self._origin = 'fake'
360 self._origin = 'fake'
361
361
362 def __repr__(self):
362 def __repr__(self):
363 return '<Fake completion object jedi has crashed>'
363 return '<Fake completion object jedi has crashed>'
364
364
365
365
366 class Completion:
366 class Completion:
367 """
367 """
368 Completion object used and return by IPython completers.
368 Completion object used and return by IPython completers.
369
369
370 .. warning::
370 .. warning::
371
371
372 Unstable
372 Unstable
373
373
374 This function is unstable, API may change without warning.
374 This function is unstable, API may change without warning.
375 It will also raise unless use in proper context manager.
375 It will also raise unless use in proper context manager.
376
376
377 This act as a middle ground :any:`Completion` object between the
377 This act as a middle ground :any:`Completion` object between the
378 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
378 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
379 object. While Jedi need a lot of information about evaluator and how the
379 object. While Jedi need a lot of information about evaluator and how the
380 code should be ran/inspected, PromptToolkit (and other frontend) mostly
380 code should be ran/inspected, PromptToolkit (and other frontend) mostly
381 need user facing information.
381 need user facing information.
382
382
383 - Which range should be replaced replaced by what.
383 - Which range should be replaced replaced by what.
384 - Some metadata (like completion type), or meta information to displayed to
384 - Some metadata (like completion type), or meta information to displayed to
385 the use user.
385 the use user.
386
386
387 For debugging purpose we can also store the origin of the completion (``jedi``,
387 For debugging purpose we can also store the origin of the completion (``jedi``,
388 ``IPython.python_matches``, ``IPython.magics_matches``...).
388 ``IPython.python_matches``, ``IPython.magics_matches``...).
389 """
389 """
390
390
391 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
391 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
392
392
393 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
393 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
394 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
394 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
395 "It may change without warnings. "
395 "It may change without warnings. "
396 "Use in corresponding context manager.",
396 "Use in corresponding context manager.",
397 category=ProvisionalCompleterWarning, stacklevel=2)
397 category=ProvisionalCompleterWarning, stacklevel=2)
398
398
399 self.start = start
399 self.start = start
400 self.end = end
400 self.end = end
401 self.text = text
401 self.text = text
402 self.type = type
402 self.type = type
403 self.signature = signature
403 self.signature = signature
404 self._origin = _origin
404 self._origin = _origin
405
405
406 def __repr__(self):
406 def __repr__(self):
407 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
407 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
408 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
408 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
409
409
410 def __eq__(self, other)->Bool:
410 def __eq__(self, other)->Bool:
411 """
411 """
412 Equality and hash do not hash the type (as some completer may not be
412 Equality and hash do not hash the type (as some completer may not be
413 able to infer the type), but are use to (partially) de-duplicate
413 able to infer the type), but are use to (partially) de-duplicate
414 completion.
414 completion.
415
415
416 Completely de-duplicating completion is a bit tricker that just
416 Completely de-duplicating completion is a bit tricker that just
417 comparing as it depends on surrounding text, which Completions are not
417 comparing as it depends on surrounding text, which Completions are not
418 aware of.
418 aware of.
419 """
419 """
420 return self.start == other.start and \
420 return self.start == other.start and \
421 self.end == other.end and \
421 self.end == other.end and \
422 self.text == other.text
422 self.text == other.text
423
423
424 def __hash__(self):
424 def __hash__(self):
425 return hash((self.start, self.end, self.text))
425 return hash((self.start, self.end, self.text))
426
426
427
427
428 _IC = Iterable[Completion]
428 _IC = Iterable[Completion]
429
429
430
430
431 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
431 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
432 """
432 """
433 Deduplicate a set of completions.
433 Deduplicate a set of completions.
434
434
435 .. warning::
435 .. warning::
436
436
437 Unstable
437 Unstable
438
438
439 This function is unstable, API may change without warning.
439 This function is unstable, API may change without warning.
440
440
441 Parameters
441 Parameters
442 ----------
442 ----------
443 text : str
443 text : str
444 text that should be completed.
444 text that should be completed.
445 completions : Iterator[Completion]
445 completions : Iterator[Completion]
446 iterator over the completions to deduplicate
446 iterator over the completions to deduplicate
447
447
448 Yields
448 Yields
449 ------
449 ------
450 `Completions` objects
450 `Completions` objects
451 Completions coming from multiple sources, may be different but end up having
451 Completions coming from multiple sources, may be different but end up having
452 the same effect when applied to ``text``. If this is the case, this will
452 the same effect when applied to ``text``. If this is the case, this will
453 consider completions as equal and only emit the first encountered.
453 consider completions as equal and only emit the first encountered.
454 Not folded in `completions()` yet for debugging purpose, and to detect when
454 Not folded in `completions()` yet for debugging purpose, and to detect when
455 the IPython completer does return things that Jedi does not, but should be
455 the IPython completer does return things that Jedi does not, but should be
456 at some point.
456 at some point.
457 """
457 """
458 completions = list(completions)
458 completions = list(completions)
459 if not completions:
459 if not completions:
460 return
460 return
461
461
462 new_start = min(c.start for c in completions)
462 new_start = min(c.start for c in completions)
463 new_end = max(c.end for c in completions)
463 new_end = max(c.end for c in completions)
464
464
465 seen = set()
465 seen = set()
466 for c in completions:
466 for c in completions:
467 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
467 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
468 if new_text not in seen:
468 if new_text not in seen:
469 yield c
469 yield c
470 seen.add(new_text)
470 seen.add(new_text)
471
471
472
472
473 def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC:
473 def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC:
474 """
474 """
475 Rectify a set of completions to all have the same ``start`` and ``end``
475 Rectify a set of completions to all have the same ``start`` and ``end``
476
476
477 .. warning::
477 .. warning::
478
478
479 Unstable
479 Unstable
480
480
481 This function is unstable, API may change without warning.
481 This function is unstable, API may change without warning.
482 It will also raise unless use in proper context manager.
482 It will also raise unless use in proper context manager.
483
483
484 Parameters
484 Parameters
485 ----------
485 ----------
486 text : str
486 text : str
487 text that should be completed.
487 text that should be completed.
488 completions : Iterator[Completion]
488 completions : Iterator[Completion]
489 iterator over the completions to rectify
489 iterator over the completions to rectify
490
490
491 Notes
491 Notes
492 -----
492 -----
493 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
493 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
494 the Jupyter Protocol requires them to behave like so. This will readjust
494 the Jupyter Protocol requires them to behave like so. This will readjust
495 the completion to have the same ``start`` and ``end`` by padding both
495 the completion to have the same ``start`` and ``end`` by padding both
496 extremities with surrounding text.
496 extremities with surrounding text.
497
497
498 During stabilisation should support a ``_debug`` option to log which
498 During stabilisation should support a ``_debug`` option to log which
499 completion are return by the IPython completer and not found in Jedi in
499 completion are return by the IPython completer and not found in Jedi in
500 order to make upstream bug report.
500 order to make upstream bug report.
501 """
501 """
502 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
502 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
503 "It may change without warnings. "
503 "It may change without warnings. "
504 "Use in corresponding context manager.",
504 "Use in corresponding context manager.",
505 category=ProvisionalCompleterWarning, stacklevel=2)
505 category=ProvisionalCompleterWarning, stacklevel=2)
506
506
507 completions = list(completions)
507 completions = list(completions)
508 if not completions:
508 if not completions:
509 return
509 return
510 starts = (c.start for c in completions)
510 starts = (c.start for c in completions)
511 ends = (c.end for c in completions)
511 ends = (c.end for c in completions)
512
512
513 new_start = min(starts)
513 new_start = min(starts)
514 new_end = max(ends)
514 new_end = max(ends)
515
515
516 seen_jedi = set()
516 seen_jedi = set()
517 seen_python_matches = set()
517 seen_python_matches = set()
518 for c in completions:
518 for c in completions:
519 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
519 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
520 if c._origin == 'jedi':
520 if c._origin == 'jedi':
521 seen_jedi.add(new_text)
521 seen_jedi.add(new_text)
522 elif c._origin == 'IPCompleter.python_matches':
522 elif c._origin == 'IPCompleter.python_matches':
523 seen_python_matches.add(new_text)
523 seen_python_matches.add(new_text)
524 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
524 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
525 diff = seen_python_matches.difference(seen_jedi)
525 diff = seen_python_matches.difference(seen_jedi)
526 if diff and _debug:
526 if diff and _debug:
527 print('IPython.python matches have extras:', diff)
527 print('IPython.python matches have extras:', diff)
528
528
529
529
530 if sys.platform == 'win32':
530 if sys.platform == 'win32':
531 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
531 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
532 else:
532 else:
533 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
533 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
534
534
535 GREEDY_DELIMS = ' =\r\n'
535 GREEDY_DELIMS = ' =\r\n'
536
536
537
537
538 class CompletionSplitter(object):
538 class CompletionSplitter(object):
539 """An object to split an input line in a manner similar to readline.
539 """An object to split an input line in a manner similar to readline.
540
540
541 By having our own implementation, we can expose readline-like completion in
541 By having our own implementation, we can expose readline-like completion in
542 a uniform manner to all frontends. This object only needs to be given the
542 a uniform manner to all frontends. This object only needs to be given the
543 line of text to be split and the cursor position on said line, and it
543 line of text to be split and the cursor position on said line, and it
544 returns the 'word' to be completed on at the cursor after splitting the
544 returns the 'word' to be completed on at the cursor after splitting the
545 entire line.
545 entire line.
546
546
547 What characters are used as splitting delimiters can be controlled by
547 What characters are used as splitting delimiters can be controlled by
548 setting the ``delims`` attribute (this is a property that internally
548 setting the ``delims`` attribute (this is a property that internally
549 automatically builds the necessary regular expression)"""
549 automatically builds the necessary regular expression)"""
550
550
551 # Private interface
551 # Private interface
552
552
553 # A string of delimiter characters. The default value makes sense for
553 # A string of delimiter characters. The default value makes sense for
554 # IPython's most typical usage patterns.
554 # IPython's most typical usage patterns.
555 _delims = DELIMS
555 _delims = DELIMS
556
556
557 # The expression (a normal string) to be compiled into a regular expression
557 # The expression (a normal string) to be compiled into a regular expression
558 # for actual splitting. We store it as an attribute mostly for ease of
558 # for actual splitting. We store it as an attribute mostly for ease of
559 # debugging, since this type of code can be so tricky to debug.
559 # debugging, since this type of code can be so tricky to debug.
560 _delim_expr = None
560 _delim_expr = None
561
561
562 # The regular expression that does the actual splitting
562 # The regular expression that does the actual splitting
563 _delim_re = None
563 _delim_re = None
564
564
565 def __init__(self, delims=None):
565 def __init__(self, delims=None):
566 delims = CompletionSplitter._delims if delims is None else delims
566 delims = CompletionSplitter._delims if delims is None else delims
567 self.delims = delims
567 self.delims = delims
568
568
569 @property
569 @property
570 def delims(self):
570 def delims(self):
571 """Return the string of delimiter characters."""
571 """Return the string of delimiter characters."""
572 return self._delims
572 return self._delims
573
573
574 @delims.setter
574 @delims.setter
575 def delims(self, delims):
575 def delims(self, delims):
576 """Set the delimiters for line splitting."""
576 """Set the delimiters for line splitting."""
577 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
577 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
578 self._delim_re = re.compile(expr)
578 self._delim_re = re.compile(expr)
579 self._delims = delims
579 self._delims = delims
580 self._delim_expr = expr
580 self._delim_expr = expr
581
581
582 def split_line(self, line, cursor_pos=None):
582 def split_line(self, line, cursor_pos=None):
583 """Split a line of text with a cursor at the given position.
583 """Split a line of text with a cursor at the given position.
584 """
584 """
585 l = line if cursor_pos is None else line[:cursor_pos]
585 l = line if cursor_pos is None else line[:cursor_pos]
586 return self._delim_re.split(l)[-1]
586 return self._delim_re.split(l)[-1]
587
587
588
588
589
589
590 class Completer(Configurable):
590 class Completer(Configurable):
591
591
592 greedy = Bool(False,
592 greedy = Bool(False,
593 help="""Activate greedy completion
593 help="""Activate greedy completion
594 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
594 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
595
595
596 This will enable completion on elements of lists, results of function calls, etc.,
596 This will enable completion on elements of lists, results of function calls, etc.,
597 but can be unsafe because the code is actually evaluated on TAB.
597 but can be unsafe because the code is actually evaluated on TAB.
598 """
598 """
599 ).tag(config=True)
599 ).tag(config=True)
600
600
601 use_jedi = Bool(default_value=JEDI_INSTALLED,
601 use_jedi = Bool(default_value=JEDI_INSTALLED,
602 help="Experimental: Use Jedi to generate autocompletions. "
602 help="Experimental: Use Jedi to generate autocompletions. "
603 "Default to True if jedi is installed.").tag(config=True)
603 "Default to True if jedi is installed.").tag(config=True)
604
604
605 jedi_compute_type_timeout = Int(default_value=400,
605 jedi_compute_type_timeout = Int(default_value=400,
606 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
606 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
607 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
607 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
608 performance by preventing jedi to build its cache.
608 performance by preventing jedi to build its cache.
609 """).tag(config=True)
609 """).tag(config=True)
610
610
611 debug = Bool(default_value=False,
611 debug = Bool(default_value=False,
612 help='Enable debug for the Completer. Mostly print extra '
612 help='Enable debug for the Completer. Mostly print extra '
613 'information for experimental jedi integration.')\
613 'information for experimental jedi integration.')\
614 .tag(config=True)
614 .tag(config=True)
615
615
616 backslash_combining_completions = Bool(True,
616 backslash_combining_completions = Bool(True,
617 help="Enable unicode completions, e.g. \\alpha<tab> . "
617 help="Enable unicode completions, e.g. \\alpha<tab> . "
618 "Includes completion of latex commands, unicode names, and expanding "
618 "Includes completion of latex commands, unicode names, and expanding "
619 "unicode characters back to latex commands.").tag(config=True)
619 "unicode characters back to latex commands.").tag(config=True)
620
620
621
621
622
622
623 def __init__(self, namespace=None, global_namespace=None, **kwargs):
623 def __init__(self, namespace=None, global_namespace=None, **kwargs):
624 """Create a new completer for the command line.
624 """Create a new completer for the command line.
625
625
626 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
626 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
627
627
628 If unspecified, the default namespace where completions are performed
628 If unspecified, the default namespace where completions are performed
629 is __main__ (technically, __main__.__dict__). Namespaces should be
629 is __main__ (technically, __main__.__dict__). Namespaces should be
630 given as dictionaries.
630 given as dictionaries.
631
631
632 An optional second namespace can be given. This allows the completer
632 An optional second namespace can be given. This allows the completer
633 to handle cases where both the local and global scopes need to be
633 to handle cases where both the local and global scopes need to be
634 distinguished.
634 distinguished.
635 """
635 """
636
636
637 # Don't bind to namespace quite yet, but flag whether the user wants a
637 # Don't bind to namespace quite yet, but flag whether the user wants a
638 # specific namespace or to use __main__.__dict__. This will allow us
638 # specific namespace or to use __main__.__dict__. This will allow us
639 # to bind to __main__.__dict__ at completion time, not now.
639 # to bind to __main__.__dict__ at completion time, not now.
640 if namespace is None:
640 if namespace is None:
641 self.use_main_ns = True
641 self.use_main_ns = True
642 else:
642 else:
643 self.use_main_ns = False
643 self.use_main_ns = False
644 self.namespace = namespace
644 self.namespace = namespace
645
645
646 # The global namespace, if given, can be bound directly
646 # The global namespace, if given, can be bound directly
647 if global_namespace is None:
647 if global_namespace is None:
648 self.global_namespace = {}
648 self.global_namespace = {}
649 else:
649 else:
650 self.global_namespace = global_namespace
650 self.global_namespace = global_namespace
651
651
652 self.custom_matchers = []
652 self.custom_matchers = []
653
653
654 super(Completer, self).__init__(**kwargs)
654 super(Completer, self).__init__(**kwargs)
655
655
656 def complete(self, text, state):
656 def complete(self, text, state):
657 """Return the next possible completion for 'text'.
657 """Return the next possible completion for 'text'.
658
658
659 This is called successively with state == 0, 1, 2, ... until it
659 This is called successively with state == 0, 1, 2, ... until it
660 returns None. The completion should begin with 'text'.
660 returns None. The completion should begin with 'text'.
661
661
662 """
662 """
663 if self.use_main_ns:
663 if self.use_main_ns:
664 self.namespace = __main__.__dict__
664 self.namespace = __main__.__dict__
665
665
666 if state == 0:
666 if state == 0:
667 if "." in text:
667 if "." in text:
668 self.matches = self.attr_matches(text)
668 self.matches = self.attr_matches(text)
669 else:
669 else:
670 self.matches = self.global_matches(text)
670 self.matches = self.global_matches(text)
671 try:
671 try:
672 return self.matches[state]
672 return self.matches[state]
673 except IndexError:
673 except IndexError:
674 return None
674 return None
675
675
676 def global_matches(self, text):
676 def global_matches(self, text):
677 """Compute matches when text is a simple name.
677 """Compute matches when text is a simple name.
678
678
679 Return a list of all keywords, built-in functions and names currently
679 Return a list of all keywords, built-in functions and names currently
680 defined in self.namespace or self.global_namespace that match.
680 defined in self.namespace or self.global_namespace that match.
681
681
682 """
682 """
683 matches = []
683 matches = []
684 match_append = matches.append
684 match_append = matches.append
685 n = len(text)
685 n = len(text)
686 for lst in [keyword.kwlist,
686 for lst in [keyword.kwlist,
687 builtin_mod.__dict__.keys(),
687 builtin_mod.__dict__.keys(),
688 self.namespace.keys(),
688 self.namespace.keys(),
689 self.global_namespace.keys()]:
689 self.global_namespace.keys()]:
690 for word in lst:
690 for word in lst:
691 if word[:n] == text and word != "__builtins__":
691 if word[:n] == text and word != "__builtins__":
692 match_append(word)
692 match_append(word)
693
693
694 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
694 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
695 for lst in [self.namespace.keys(),
695 for lst in [self.namespace.keys(),
696 self.global_namespace.keys()]:
696 self.global_namespace.keys()]:
697 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
697 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
698 for word in lst if snake_case_re.match(word)}
698 for word in lst if snake_case_re.match(word)}
699 for word in shortened.keys():
699 for word in shortened.keys():
700 if word[:n] == text and word != "__builtins__":
700 if word[:n] == text and word != "__builtins__":
701 match_append(shortened[word])
701 match_append(shortened[word])
702 return matches
702 return matches
703
703
704 def attr_matches(self, text):
704 def attr_matches(self, text):
705 """Compute matches when text contains a dot.
705 """Compute matches when text contains a dot.
706
706
707 Assuming the text is of the form NAME.NAME....[NAME], and is
707 Assuming the text is of the form NAME.NAME....[NAME], and is
708 evaluatable in self.namespace or self.global_namespace, it will be
708 evaluatable in self.namespace or self.global_namespace, it will be
709 evaluated and its attributes (as revealed by dir()) are used as
709 evaluated and its attributes (as revealed by dir()) are used as
710 possible completions. (For class instances, class members are
710 possible completions. (For class instances, class members are
711 also considered.)
711 also considered.)
712
712
713 WARNING: this can still invoke arbitrary C code, if an object
713 WARNING: this can still invoke arbitrary C code, if an object
714 with a __getattr__ hook is evaluated.
714 with a __getattr__ hook is evaluated.
715
715
716 """
716 """
717
717
718 # Another option, seems to work great. Catches things like ''.<tab>
718 # Another option, seems to work great. Catches things like ''.<tab>
719 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
719 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
720
720
721 if m:
721 if m:
722 expr, attr = m.group(1, 3)
722 expr, attr = m.group(1, 3)
723 elif self.greedy:
723 elif self.greedy:
724 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
724 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
725 if not m2:
725 if not m2:
726 return []
726 return []
727 expr, attr = m2.group(1,2)
727 expr, attr = m2.group(1,2)
728 else:
728 else:
729 return []
729 return []
730
730
731 try:
731 try:
732 obj = eval(expr, self.namespace)
732 obj = eval(expr, self.namespace)
733 except:
733 except:
734 try:
734 try:
735 obj = eval(expr, self.global_namespace)
735 obj = eval(expr, self.global_namespace)
736 except:
736 except:
737 return []
737 return []
738
738
739 if self.limit_to__all__ and hasattr(obj, '__all__'):
739 if self.limit_to__all__ and hasattr(obj, '__all__'):
740 words = get__all__entries(obj)
740 words = get__all__entries(obj)
741 else:
741 else:
742 words = dir2(obj)
742 words = dir2(obj)
743
743
744 try:
744 try:
745 words = generics.complete_object(obj, words)
745 words = generics.complete_object(obj, words)
746 except TryNext:
746 except TryNext:
747 pass
747 pass
748 except AssertionError:
748 except AssertionError:
749 raise
749 raise
750 except Exception:
750 except Exception:
751 # Silence errors from completion function
751 # Silence errors from completion function
752 #raise # dbg
752 #raise # dbg
753 pass
753 pass
754 # Build match list to return
754 # Build match list to return
755 n = len(attr)
755 n = len(attr)
756 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
756 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
757
757
758
758
759 def get__all__entries(obj):
759 def get__all__entries(obj):
760 """returns the strings in the __all__ attribute"""
760 """returns the strings in the __all__ attribute"""
761 try:
761 try:
762 words = getattr(obj, '__all__')
762 words = getattr(obj, '__all__')
763 except:
763 except:
764 return []
764 return []
765
765
766 return [w for w in words if isinstance(w, str)]
766 return [w for w in words if isinstance(w, str)]
767
767
768
768
769 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
769 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
770 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
770 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
771 """Used by dict_key_matches, matching the prefix to a list of keys
771 """Used by dict_key_matches, matching the prefix to a list of keys
772
772
773 Parameters
773 Parameters
774 ----------
774 ----------
775 keys
775 keys
776 list of keys in dictionary currently being completed.
776 list of keys in dictionary currently being completed.
777 prefix
777 prefix
778 Part of the text already typed by the user. E.g. `mydict[b'fo`
778 Part of the text already typed by the user. E.g. `mydict[b'fo`
779 delims
779 delims
780 String of delimiters to consider when finding the current key.
780 String of delimiters to consider when finding the current key.
781 extra_prefix : optional
781 extra_prefix : optional
782 Part of the text already typed in multi-key index cases. E.g. for
782 Part of the text already typed in multi-key index cases. E.g. for
783 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
783 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
784
784
785 Returns
785 Returns
786 -------
786 -------
787 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
787 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
788 ``quote`` being the quote that need to be used to close current string.
788 ``quote`` being the quote that need to be used to close current string.
789 ``token_start`` the position where the replacement should start occurring,
789 ``token_start`` the position where the replacement should start occurring,
790 ``matches`` a list of replacement/completion
790 ``matches`` a list of replacement/completion
791
791
792 """
792 """
793 prefix_tuple = extra_prefix if extra_prefix else ()
793 prefix_tuple = extra_prefix if extra_prefix else ()
794 Nprefix = len(prefix_tuple)
794 Nprefix = len(prefix_tuple)
795 def filter_prefix_tuple(key):
795 def filter_prefix_tuple(key):
796 # Reject too short keys
796 # Reject too short keys
797 if len(key) <= Nprefix:
797 if len(key) <= Nprefix:
798 return False
798 return False
799 # Reject keys with non str/bytes in it
799 # Reject keys with non str/bytes in it
800 for k in key:
800 for k in key:
801 if not isinstance(k, (str, bytes)):
801 if not isinstance(k, (str, bytes)):
802 return False
802 return False
803 # Reject keys that do not match the prefix
803 # Reject keys that do not match the prefix
804 for k, pt in zip(key, prefix_tuple):
804 for k, pt in zip(key, prefix_tuple):
805 if k != pt:
805 if k != pt:
806 return False
806 return False
807 # All checks passed!
807 # All checks passed!
808 return True
808 return True
809
809
810 filtered_keys:List[Union[str,bytes]] = []
810 filtered_keys:List[Union[str,bytes]] = []
811 def _add_to_filtered_keys(key):
811 def _add_to_filtered_keys(key):
812 if isinstance(key, (str, bytes)):
812 if isinstance(key, (str, bytes)):
813 filtered_keys.append(key)
813 filtered_keys.append(key)
814
814
815 for k in keys:
815 for k in keys:
816 if isinstance(k, tuple):
816 if isinstance(k, tuple):
817 if filter_prefix_tuple(k):
817 if filter_prefix_tuple(k):
818 _add_to_filtered_keys(k[Nprefix])
818 _add_to_filtered_keys(k[Nprefix])
819 else:
819 else:
820 _add_to_filtered_keys(k)
820 _add_to_filtered_keys(k)
821
821
822 if not prefix:
822 if not prefix:
823 return '', 0, [repr(k) for k in filtered_keys]
823 return '', 0, [repr(k) for k in filtered_keys]
824 quote_match = re.search('["\']', prefix)
824 quote_match = re.search('["\']', prefix)
825 assert quote_match is not None # silence mypy
825 assert quote_match is not None # silence mypy
826 quote = quote_match.group()
826 quote = quote_match.group()
827 try:
827 try:
828 prefix_str = eval(prefix + quote, {})
828 prefix_str = eval(prefix + quote, {})
829 except Exception:
829 except Exception:
830 return '', 0, []
830 return '', 0, []
831
831
832 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
832 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
833 token_match = re.search(pattern, prefix, re.UNICODE)
833 token_match = re.search(pattern, prefix, re.UNICODE)
834 assert token_match is not None # silence mypy
834 assert token_match is not None # silence mypy
835 token_start = token_match.start()
835 token_start = token_match.start()
836 token_prefix = token_match.group()
836 token_prefix = token_match.group()
837
837
838 matched:List[str] = []
838 matched:List[str] = []
839 for key in filtered_keys:
839 for key in filtered_keys:
840 try:
840 try:
841 if not key.startswith(prefix_str):
841 if not key.startswith(prefix_str):
842 continue
842 continue
843 except (AttributeError, TypeError, UnicodeError):
843 except (AttributeError, TypeError, UnicodeError):
844 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
844 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
845 continue
845 continue
846
846
847 # reformat remainder of key to begin with prefix
847 # reformat remainder of key to begin with prefix
848 rem = key[len(prefix_str):]
848 rem = key[len(prefix_str):]
849 # force repr wrapped in '
849 # force repr wrapped in '
850 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
850 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
851 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
851 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
852 if quote == '"':
852 if quote == '"':
853 # The entered prefix is quoted with ",
853 # The entered prefix is quoted with ",
854 # but the match is quoted with '.
854 # but the match is quoted with '.
855 # A contained " hence needs escaping for comparison:
855 # A contained " hence needs escaping for comparison:
856 rem_repr = rem_repr.replace('"', '\\"')
856 rem_repr = rem_repr.replace('"', '\\"')
857
857
858 # then reinsert prefix from start of token
858 # then reinsert prefix from start of token
859 matched.append('%s%s' % (token_prefix, rem_repr))
859 matched.append('%s%s' % (token_prefix, rem_repr))
860 return quote, token_start, matched
860 return quote, token_start, matched
861
861
862
862
863 def cursor_to_position(text:str, line:int, column:int)->int:
863 def cursor_to_position(text:str, line:int, column:int)->int:
864 """
864 """
865 Convert the (line,column) position of the cursor in text to an offset in a
865 Convert the (line,column) position of the cursor in text to an offset in a
866 string.
866 string.
867
867
868 Parameters
868 Parameters
869 ----------
869 ----------
870 text : str
870 text : str
871 The text in which to calculate the cursor offset
871 The text in which to calculate the cursor offset
872 line : int
872 line : int
873 Line of the cursor; 0-indexed
873 Line of the cursor; 0-indexed
874 column : int
874 column : int
875 Column of the cursor 0-indexed
875 Column of the cursor 0-indexed
876
876
877 Returns
877 Returns
878 -------
878 -------
879 Position of the cursor in ``text``, 0-indexed.
879 Position of the cursor in ``text``, 0-indexed.
880
880
881 See Also
881 See Also
882 --------
882 --------
883 position_to_cursor : reciprocal of this function
883 position_to_cursor : reciprocal of this function
884
884
885 """
885 """
886 lines = text.split('\n')
886 lines = text.split('\n')
887 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
887 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
888
888
889 return sum(len(l) + 1 for l in lines[:line]) + column
889 return sum(len(l) + 1 for l in lines[:line]) + column
890
890
891 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
891 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
892 """
892 """
893 Convert the position of the cursor in text (0 indexed) to a line
893 Convert the position of the cursor in text (0 indexed) to a line
894 number(0-indexed) and a column number (0-indexed) pair
894 number(0-indexed) and a column number (0-indexed) pair
895
895
896 Position should be a valid position in ``text``.
896 Position should be a valid position in ``text``.
897
897
898 Parameters
898 Parameters
899 ----------
899 ----------
900 text : str
900 text : str
901 The text in which to calculate the cursor offset
901 The text in which to calculate the cursor offset
902 offset : int
902 offset : int
903 Position of the cursor in ``text``, 0-indexed.
903 Position of the cursor in ``text``, 0-indexed.
904
904
905 Returns
905 Returns
906 -------
906 -------
907 (line, column) : (int, int)
907 (line, column) : (int, int)
908 Line of the cursor; 0-indexed, column of the cursor 0-indexed
908 Line of the cursor; 0-indexed, column of the cursor 0-indexed
909
909
910 See Also
910 See Also
911 --------
911 --------
912 cursor_to_position : reciprocal of this function
912 cursor_to_position : reciprocal of this function
913
913
914 """
914 """
915
915
916 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
916 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
917
917
918 before = text[:offset]
918 before = text[:offset]
919 blines = before.split('\n') # ! splitnes trim trailing \n
919 blines = before.split('\n') # ! splitnes trim trailing \n
920 line = before.count('\n')
920 line = before.count('\n')
921 col = len(blines[-1])
921 col = len(blines[-1])
922 return line, col
922 return line, col
923
923
924
924
925 def _safe_isinstance(obj, module, class_name):
925 def _safe_isinstance(obj, module, class_name):
926 """Checks if obj is an instance of module.class_name if loaded
926 """Checks if obj is an instance of module.class_name if loaded
927 """
927 """
928 return (module in sys.modules and
928 return (module in sys.modules and
929 isinstance(obj, getattr(import_module(module), class_name)))
929 isinstance(obj, getattr(import_module(module), class_name)))
930
930
931 def back_unicode_name_matches(text:str) -> Tuple[str, Sequence[str]]:
931 def back_unicode_name_matches(text:str) -> Tuple[str, Sequence[str]]:
932 """Match Unicode characters back to Unicode name
932 """Match Unicode characters back to Unicode name
933
933
934 This does ``☃`` -> ``\\snowman``
934 This does ``☃`` -> ``\\snowman``
935
935
936 Note that snowman is not a valid python3 combining character but will be expanded.
936 Note that snowman is not a valid python3 combining character but will be expanded.
937 Though it will not recombine back to the snowman character by the completion machinery.
937 Though it will not recombine back to the snowman character by the completion machinery.
938
938
939 This will not either back-complete standard sequences like \\n, \\b ...
939 This will not either back-complete standard sequences like \\n, \\b ...
940
940
941 Returns
941 Returns
942 =======
942 =======
943
943
944 Return a tuple with two elements:
944 Return a tuple with two elements:
945
945
946 - The Unicode character that was matched (preceded with a backslash), or
946 - The Unicode character that was matched (preceded with a backslash), or
947 empty string,
947 empty string,
948 - a sequence (of 1), name for the match Unicode character, preceded by
948 - a sequence (of 1), name for the match Unicode character, preceded by
949 backslash, or empty if no match.
949 backslash, or empty if no match.
950
950
951 """
951 """
952 if len(text)<2:
952 if len(text)<2:
953 return '', ()
953 return '', ()
954 maybe_slash = text[-2]
954 maybe_slash = text[-2]
955 if maybe_slash != '\\':
955 if maybe_slash != '\\':
956 return '', ()
956 return '', ()
957
957
958 char = text[-1]
958 char = text[-1]
959 # no expand on quote for completion in strings.
959 # no expand on quote for completion in strings.
960 # nor backcomplete standard ascii keys
960 # nor backcomplete standard ascii keys
961 if char in string.ascii_letters or char in ('"',"'"):
961 if char in string.ascii_letters or char in ('"',"'"):
962 return '', ()
962 return '', ()
963 try :
963 try :
964 unic = unicodedata.name(char)
964 unic = unicodedata.name(char)
965 return '\\'+char,('\\'+unic,)
965 return '\\'+char,('\\'+unic,)
966 except KeyError:
966 except KeyError:
967 pass
967 pass
968 return '', ()
968 return '', ()
969
969
970 def back_latex_name_matches(text:str) -> Tuple[str, Sequence[str]] :
970 def back_latex_name_matches(text:str) -> Tuple[str, Sequence[str]] :
971 """Match latex characters back to unicode name
971 """Match latex characters back to unicode name
972
972
973 This does ``\\ℵ`` -> ``\\aleph``
973 This does ``\\ℵ`` -> ``\\aleph``
974
974
975 """
975 """
976 if len(text)<2:
976 if len(text)<2:
977 return '', ()
977 return '', ()
978 maybe_slash = text[-2]
978 maybe_slash = text[-2]
979 if maybe_slash != '\\':
979 if maybe_slash != '\\':
980 return '', ()
980 return '', ()
981
981
982
982
983 char = text[-1]
983 char = text[-1]
984 # no expand on quote for completion in strings.
984 # no expand on quote for completion in strings.
985 # nor backcomplete standard ascii keys
985 # nor backcomplete standard ascii keys
986 if char in string.ascii_letters or char in ('"',"'"):
986 if char in string.ascii_letters or char in ('"',"'"):
987 return '', ()
987 return '', ()
988 try :
988 try :
989 latex = reverse_latex_symbol[char]
989 latex = reverse_latex_symbol[char]
990 # '\\' replace the \ as well
990 # '\\' replace the \ as well
991 return '\\'+char,[latex]
991 return '\\'+char,[latex]
992 except KeyError:
992 except KeyError:
993 pass
993 pass
994 return '', ()
994 return '', ()
995
995
996
996
997 def _formatparamchildren(parameter) -> str:
997 def _formatparamchildren(parameter) -> str:
998 """
998 """
999 Get parameter name and value from Jedi Private API
999 Get parameter name and value from Jedi Private API
1000
1000
1001 Jedi does not expose a simple way to get `param=value` from its API.
1001 Jedi does not expose a simple way to get `param=value` from its API.
1002
1002
1003 Parameters
1003 Parameters
1004 ----------
1004 ----------
1005 parameter
1005 parameter
1006 Jedi's function `Param`
1006 Jedi's function `Param`
1007
1007
1008 Returns
1008 Returns
1009 -------
1009 -------
1010 A string like 'a', 'b=1', '*args', '**kwargs'
1010 A string like 'a', 'b=1', '*args', '**kwargs'
1011
1011
1012 """
1012 """
1013 description = parameter.description
1013 description = parameter.description
1014 if not description.startswith('param '):
1014 if not description.startswith('param '):
1015 raise ValueError('Jedi function parameter description have change format.'
1015 raise ValueError('Jedi function parameter description have change format.'
1016 'Expected "param ...", found %r".' % description)
1016 'Expected "param ...", found %r".' % description)
1017 return description[6:]
1017 return description[6:]
1018
1018
1019 def _make_signature(completion)-> str:
1019 def _make_signature(completion)-> str:
1020 """
1020 """
1021 Make the signature from a jedi completion
1021 Make the signature from a jedi completion
1022
1022
1023 Parameters
1023 Parameters
1024 ----------
1024 ----------
1025 completion : jedi.Completion
1025 completion : jedi.Completion
1026 object does not complete a function type
1026 object does not complete a function type
1027
1027
1028 Returns
1028 Returns
1029 -------
1029 -------
1030 a string consisting of the function signature, with the parenthesis but
1030 a string consisting of the function signature, with the parenthesis but
1031 without the function name. example:
1031 without the function name. example:
1032 `(a, *args, b=1, **kwargs)`
1032 `(a, *args, b=1, **kwargs)`
1033
1033
1034 """
1034 """
1035
1035
1036 # it looks like this might work on jedi 0.17
1036 # it looks like this might work on jedi 0.17
1037 if hasattr(completion, 'get_signatures'):
1037 if hasattr(completion, 'get_signatures'):
1038 signatures = completion.get_signatures()
1038 signatures = completion.get_signatures()
1039 if not signatures:
1039 if not signatures:
1040 return '(?)'
1040 return '(?)'
1041
1041
1042 c0 = completion.get_signatures()[0]
1042 c0 = completion.get_signatures()[0]
1043 return '('+c0.to_string().split('(', maxsplit=1)[1]
1043 return '('+c0.to_string().split('(', maxsplit=1)[1]
1044
1044
1045 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1045 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1046 for p in signature.defined_names()) if f])
1046 for p in signature.defined_names()) if f])
1047
1047
1048
1048
1049 class _CompleteResult(NamedTuple):
1049 class _CompleteResult(NamedTuple):
1050 matched_text : str
1050 matched_text : str
1051 matches: Sequence[str]
1051 matches: Sequence[str]
1052 matches_origin: Sequence[str]
1052 matches_origin: Sequence[str]
1053 jedi_matches: Any
1053 jedi_matches: Any
1054
1054
1055
1055
1056 class IPCompleter(Completer):
1056 class IPCompleter(Completer):
1057 """Extension of the completer class with IPython-specific features"""
1057 """Extension of the completer class with IPython-specific features"""
1058
1058
1059 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1059 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1060
1060
1061 @observe('greedy')
1061 @observe('greedy')
1062 def _greedy_changed(self, change):
1062 def _greedy_changed(self, change):
1063 """update the splitter and readline delims when greedy is changed"""
1063 """update the splitter and readline delims when greedy is changed"""
1064 if change['new']:
1064 if change['new']:
1065 self.splitter.delims = GREEDY_DELIMS
1065 self.splitter.delims = GREEDY_DELIMS
1066 else:
1066 else:
1067 self.splitter.delims = DELIMS
1067 self.splitter.delims = DELIMS
1068
1068
1069 dict_keys_only = Bool(False,
1069 dict_keys_only = Bool(False,
1070 help="""Whether to show dict key matches only""")
1070 help="""Whether to show dict key matches only""")
1071
1071
1072 merge_completions = Bool(True,
1072 merge_completions = Bool(True,
1073 help="""Whether to merge completion results into a single list
1073 help="""Whether to merge completion results into a single list
1074
1074
1075 If False, only the completion results from the first non-empty
1075 If False, only the completion results from the first non-empty
1076 completer will be returned.
1076 completer will be returned.
1077 """
1077 """
1078 ).tag(config=True)
1078 ).tag(config=True)
1079 omit__names = Enum((0,1,2), default_value=2,
1079 omit__names = Enum((0,1,2), default_value=2,
1080 help="""Instruct the completer to omit private method names
1080 help="""Instruct the completer to omit private method names
1081
1081
1082 Specifically, when completing on ``object.<tab>``.
1082 Specifically, when completing on ``object.<tab>``.
1083
1083
1084 When 2 [default]: all names that start with '_' will be excluded.
1084 When 2 [default]: all names that start with '_' will be excluded.
1085
1085
1086 When 1: all 'magic' names (``__foo__``) will be excluded.
1086 When 1: all 'magic' names (``__foo__``) will be excluded.
1087
1087
1088 When 0: nothing will be excluded.
1088 When 0: nothing will be excluded.
1089 """
1089 """
1090 ).tag(config=True)
1090 ).tag(config=True)
1091 limit_to__all__ = Bool(False,
1091 limit_to__all__ = Bool(False,
1092 help="""
1092 help="""
1093 DEPRECATED as of version 5.0.
1093 DEPRECATED as of version 5.0.
1094
1094
1095 Instruct the completer to use __all__ for the completion
1095 Instruct the completer to use __all__ for the completion
1096
1096
1097 Specifically, when completing on ``object.<tab>``.
1097 Specifically, when completing on ``object.<tab>``.
1098
1098
1099 When True: only those names in obj.__all__ will be included.
1099 When True: only those names in obj.__all__ will be included.
1100
1100
1101 When False [default]: the __all__ attribute is ignored
1101 When False [default]: the __all__ attribute is ignored
1102 """,
1102 """,
1103 ).tag(config=True)
1103 ).tag(config=True)
1104
1104
1105 profile_completions = Bool(
1105 profile_completions = Bool(
1106 default_value=False,
1106 default_value=False,
1107 help="If True, emit profiling data for completion subsystem using cProfile."
1107 help="If True, emit profiling data for completion subsystem using cProfile."
1108 ).tag(config=True)
1108 ).tag(config=True)
1109
1109
1110 profiler_output_dir = Unicode(
1110 profiler_output_dir = Unicode(
1111 default_value=".completion_profiles",
1111 default_value=".completion_profiles",
1112 help="Template for path at which to output profile data for completions."
1112 help="Template for path at which to output profile data for completions."
1113 ).tag(config=True)
1113 ).tag(config=True)
1114
1114
1115 @observe('limit_to__all__')
1115 @observe('limit_to__all__')
1116 def _limit_to_all_changed(self, change):
1116 def _limit_to_all_changed(self, change):
1117 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1117 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1118 'value has been deprecated since IPython 5.0, will be made to have '
1118 'value has been deprecated since IPython 5.0, will be made to have '
1119 'no effects and then removed in future version of IPython.',
1119 'no effects and then removed in future version of IPython.',
1120 UserWarning)
1120 UserWarning)
1121
1121
1122 def __init__(self, shell=None, namespace=None, global_namespace=None,
1122 def __init__(self, shell=None, namespace=None, global_namespace=None,
1123 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
1123 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
1124 """IPCompleter() -> completer
1124 """IPCompleter() -> completer
1125
1125
1126 Return a completer object.
1126 Return a completer object.
1127
1127
1128 Parameters
1128 Parameters
1129 ----------
1129 ----------
1130 shell
1130 shell
1131 a pointer to the ipython shell itself. This is needed
1131 a pointer to the ipython shell itself. This is needed
1132 because this completer knows about magic functions, and those can
1132 because this completer knows about magic functions, and those can
1133 only be accessed via the ipython instance.
1133 only be accessed via the ipython instance.
1134 namespace : dict, optional
1134 namespace : dict, optional
1135 an optional dict where completions are performed.
1135 an optional dict where completions are performed.
1136 global_namespace : dict, optional
1136 global_namespace : dict, optional
1137 secondary optional dict for completions, to
1137 secondary optional dict for completions, to
1138 handle cases (such as IPython embedded inside functions) where
1138 handle cases (such as IPython embedded inside functions) where
1139 both Python scopes are visible.
1139 both Python scopes are visible.
1140 use_readline : bool, optional
1140 use_readline : bool, optional
1141 DEPRECATED, ignored since IPython 6.0, will have no effects
1141 DEPRECATED, ignored since IPython 6.0, will have no effects
1142 """
1142 """
1143
1143
1144 self.magic_escape = ESC_MAGIC
1144 self.magic_escape = ESC_MAGIC
1145 self.splitter = CompletionSplitter()
1145 self.splitter = CompletionSplitter()
1146
1146
1147 if use_readline is not _deprecation_readline_sentinel:
1147 if use_readline is not _deprecation_readline_sentinel:
1148 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
1148 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
1149 DeprecationWarning, stacklevel=2)
1149 DeprecationWarning, stacklevel=2)
1150
1150
1151 # _greedy_changed() depends on splitter and readline being defined:
1151 # _greedy_changed() depends on splitter and readline being defined:
1152 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
1152 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
1153 config=config, **kwargs)
1153 config=config, **kwargs)
1154
1154
1155 # List where completion matches will be stored
1155 # List where completion matches will be stored
1156 self.matches = []
1156 self.matches = []
1157 self.shell = shell
1157 self.shell = shell
1158 # Regexp to split filenames with spaces in them
1158 # Regexp to split filenames with spaces in them
1159 self.space_name_re = re.compile(r'([^\\] )')
1159 self.space_name_re = re.compile(r'([^\\] )')
1160 # Hold a local ref. to glob.glob for speed
1160 # Hold a local ref. to glob.glob for speed
1161 self.glob = glob.glob
1161 self.glob = glob.glob
1162
1162
1163 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1163 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1164 # buffers, to avoid completion problems.
1164 # buffers, to avoid completion problems.
1165 term = os.environ.get('TERM','xterm')
1165 term = os.environ.get('TERM','xterm')
1166 self.dumb_terminal = term in ['dumb','emacs']
1166 self.dumb_terminal = term in ['dumb','emacs']
1167
1167
1168 # Special handling of backslashes needed in win32 platforms
1168 # Special handling of backslashes needed in win32 platforms
1169 if sys.platform == "win32":
1169 if sys.platform == "win32":
1170 self.clean_glob = self._clean_glob_win32
1170 self.clean_glob = self._clean_glob_win32
1171 else:
1171 else:
1172 self.clean_glob = self._clean_glob
1172 self.clean_glob = self._clean_glob
1173
1173
1174 #regexp to parse docstring for function signature
1174 #regexp to parse docstring for function signature
1175 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1175 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1176 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1176 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1177 #use this if positional argument name is also needed
1177 #use this if positional argument name is also needed
1178 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1178 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1179
1179
1180 self.magic_arg_matchers = [
1180 self.magic_arg_matchers = [
1181 self.magic_config_matches,
1181 self.magic_config_matches,
1182 self.magic_color_matches,
1182 self.magic_color_matches,
1183 ]
1183 ]
1184
1184
1185 # This is set externally by InteractiveShell
1185 # This is set externally by InteractiveShell
1186 self.custom_completers = None
1186 self.custom_completers = None
1187
1187
1188 # This is a list of names of unicode characters that can be completed
1188 # This is a list of names of unicode characters that can be completed
1189 # into their corresponding unicode value. The list is large, so we
1189 # into their corresponding unicode value. The list is large, so we
1190 # laziliy initialize it on first use. Consuming code should access this
1190 # laziliy initialize it on first use. Consuming code should access this
1191 # attribute through the `@unicode_names` property.
1191 # attribute through the `@unicode_names` property.
1192 self._unicode_names = None
1192 self._unicode_names = None
1193
1193
1194 @property
1194 @property
1195 def matchers(self) -> List[Any]:
1195 def matchers(self) -> List[Any]:
1196 """All active matcher routines for completion"""
1196 """All active matcher routines for completion"""
1197 if self.dict_keys_only:
1197 if self.dict_keys_only:
1198 return [self.dict_key_matches]
1198 return [self.dict_key_matches]
1199
1199
1200 if self.use_jedi:
1200 if self.use_jedi:
1201 return [
1201 return [
1202 *self.custom_matchers,
1202 *self.custom_matchers,
1203 self.dict_key_matches,
1203 self.dict_key_matches,
1204 self.file_matches,
1204 self.file_matches,
1205 self.magic_matches,
1205 self.magic_matches,
1206 ]
1206 ]
1207 else:
1207 else:
1208 return [
1208 return [
1209 *self.custom_matchers,
1209 *self.custom_matchers,
1210 self.dict_key_matches,
1210 self.dict_key_matches,
1211 self.python_matches,
1211 self.python_matches,
1212 self.file_matches,
1212 self.file_matches,
1213 self.magic_matches,
1213 self.magic_matches,
1214 self.python_func_kw_matches,
1214 self.python_func_kw_matches,
1215 ]
1215 ]
1216
1216
1217 def all_completions(self, text:str) -> List[str]:
1217 def all_completions(self, text:str) -> List[str]:
1218 """
1218 """
1219 Wrapper around the completion methods for the benefit of emacs.
1219 Wrapper around the completion methods for the benefit of emacs.
1220 """
1220 """
1221 prefix = text.rpartition('.')[0]
1221 prefix = text.rpartition('.')[0]
1222 with provisionalcompleter():
1222 with provisionalcompleter():
1223 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1223 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1224 for c in self.completions(text, len(text))]
1224 for c in self.completions(text, len(text))]
1225
1225
1226 return self.complete(text)[1]
1226 return self.complete(text)[1]
1227
1227
1228 def _clean_glob(self, text:str):
1228 def _clean_glob(self, text:str):
1229 return self.glob("%s*" % text)
1229 return self.glob("%s*" % text)
1230
1230
1231 def _clean_glob_win32(self, text:str):
1231 def _clean_glob_win32(self, text:str):
1232 return [f.replace("\\","/")
1232 return [f.replace("\\","/")
1233 for f in self.glob("%s*" % text)]
1233 for f in self.glob("%s*" % text)]
1234
1234
1235 def file_matches(self, text:str)->List[str]:
1235 def file_matches(self, text:str)->List[str]:
1236 """Match filenames, expanding ~USER type strings.
1236 """Match filenames, expanding ~USER type strings.
1237
1237
1238 Most of the seemingly convoluted logic in this completer is an
1238 Most of the seemingly convoluted logic in this completer is an
1239 attempt to handle filenames with spaces in them. And yet it's not
1239 attempt to handle filenames with spaces in them. And yet it's not
1240 quite perfect, because Python's readline doesn't expose all of the
1240 quite perfect, because Python's readline doesn't expose all of the
1241 GNU readline details needed for this to be done correctly.
1241 GNU readline details needed for this to be done correctly.
1242
1242
1243 For a filename with a space in it, the printed completions will be
1243 For a filename with a space in it, the printed completions will be
1244 only the parts after what's already been typed (instead of the
1244 only the parts after what's already been typed (instead of the
1245 full completions, as is normally done). I don't think with the
1245 full completions, as is normally done). I don't think with the
1246 current (as of Python 2.3) Python readline it's possible to do
1246 current (as of Python 2.3) Python readline it's possible to do
1247 better."""
1247 better."""
1248
1248
1249 # chars that require escaping with backslash - i.e. chars
1249 # chars that require escaping with backslash - i.e. chars
1250 # that readline treats incorrectly as delimiters, but we
1250 # that readline treats incorrectly as delimiters, but we
1251 # don't want to treat as delimiters in filename matching
1251 # don't want to treat as delimiters in filename matching
1252 # when escaped with backslash
1252 # when escaped with backslash
1253 if text.startswith('!'):
1253 if text.startswith('!'):
1254 text = text[1:]
1254 text = text[1:]
1255 text_prefix = u'!'
1255 text_prefix = u'!'
1256 else:
1256 else:
1257 text_prefix = u''
1257 text_prefix = u''
1258
1258
1259 text_until_cursor = self.text_until_cursor
1259 text_until_cursor = self.text_until_cursor
1260 # track strings with open quotes
1260 # track strings with open quotes
1261 open_quotes = has_open_quotes(text_until_cursor)
1261 open_quotes = has_open_quotes(text_until_cursor)
1262
1262
1263 if '(' in text_until_cursor or '[' in text_until_cursor:
1263 if '(' in text_until_cursor or '[' in text_until_cursor:
1264 lsplit = text
1264 lsplit = text
1265 else:
1265 else:
1266 try:
1266 try:
1267 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1267 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1268 lsplit = arg_split(text_until_cursor)[-1]
1268 lsplit = arg_split(text_until_cursor)[-1]
1269 except ValueError:
1269 except ValueError:
1270 # typically an unmatched ", or backslash without escaped char.
1270 # typically an unmatched ", or backslash without escaped char.
1271 if open_quotes:
1271 if open_quotes:
1272 lsplit = text_until_cursor.split(open_quotes)[-1]
1272 lsplit = text_until_cursor.split(open_quotes)[-1]
1273 else:
1273 else:
1274 return []
1274 return []
1275 except IndexError:
1275 except IndexError:
1276 # tab pressed on empty line
1276 # tab pressed on empty line
1277 lsplit = ""
1277 lsplit = ""
1278
1278
1279 if not open_quotes and lsplit != protect_filename(lsplit):
1279 if not open_quotes and lsplit != protect_filename(lsplit):
1280 # if protectables are found, do matching on the whole escaped name
1280 # if protectables are found, do matching on the whole escaped name
1281 has_protectables = True
1281 has_protectables = True
1282 text0,text = text,lsplit
1282 text0,text = text,lsplit
1283 else:
1283 else:
1284 has_protectables = False
1284 has_protectables = False
1285 text = os.path.expanduser(text)
1285 text = os.path.expanduser(text)
1286
1286
1287 if text == "":
1287 if text == "":
1288 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1288 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1289
1289
1290 # Compute the matches from the filesystem
1290 # Compute the matches from the filesystem
1291 if sys.platform == 'win32':
1291 if sys.platform == 'win32':
1292 m0 = self.clean_glob(text)
1292 m0 = self.clean_glob(text)
1293 else:
1293 else:
1294 m0 = self.clean_glob(text.replace('\\', ''))
1294 m0 = self.clean_glob(text.replace('\\', ''))
1295
1295
1296 if has_protectables:
1296 if has_protectables:
1297 # If we had protectables, we need to revert our changes to the
1297 # If we had protectables, we need to revert our changes to the
1298 # beginning of filename so that we don't double-write the part
1298 # beginning of filename so that we don't double-write the part
1299 # of the filename we have so far
1299 # of the filename we have so far
1300 len_lsplit = len(lsplit)
1300 len_lsplit = len(lsplit)
1301 matches = [text_prefix + text0 +
1301 matches = [text_prefix + text0 +
1302 protect_filename(f[len_lsplit:]) for f in m0]
1302 protect_filename(f[len_lsplit:]) for f in m0]
1303 else:
1303 else:
1304 if open_quotes:
1304 if open_quotes:
1305 # if we have a string with an open quote, we don't need to
1305 # if we have a string with an open quote, we don't need to
1306 # protect the names beyond the quote (and we _shouldn't_, as
1306 # protect the names beyond the quote (and we _shouldn't_, as
1307 # it would cause bugs when the filesystem call is made).
1307 # it would cause bugs when the filesystem call is made).
1308 matches = m0 if sys.platform == "win32" else\
1308 matches = m0 if sys.platform == "win32" else\
1309 [protect_filename(f, open_quotes) for f in m0]
1309 [protect_filename(f, open_quotes) for f in m0]
1310 else:
1310 else:
1311 matches = [text_prefix +
1311 matches = [text_prefix +
1312 protect_filename(f) for f in m0]
1312 protect_filename(f) for f in m0]
1313
1313
1314 # Mark directories in input list by appending '/' to their names.
1314 # Mark directories in input list by appending '/' to their names.
1315 return [x+'/' if os.path.isdir(x) else x for x in matches]
1315 return [x+'/' if os.path.isdir(x) else x for x in matches]
1316
1316
1317 def magic_matches(self, text:str):
1317 def magic_matches(self, text:str):
1318 """Match magics"""
1318 """Match magics"""
1319 # Get all shell magics now rather than statically, so magics loaded at
1319 # Get all shell magics now rather than statically, so magics loaded at
1320 # runtime show up too.
1320 # runtime show up too.
1321 lsm = self.shell.magics_manager.lsmagic()
1321 lsm = self.shell.magics_manager.lsmagic()
1322 line_magics = lsm['line']
1322 line_magics = lsm['line']
1323 cell_magics = lsm['cell']
1323 cell_magics = lsm['cell']
1324 pre = self.magic_escape
1324 pre = self.magic_escape
1325 pre2 = pre+pre
1325 pre2 = pre+pre
1326
1326
1327 explicit_magic = text.startswith(pre)
1327 explicit_magic = text.startswith(pre)
1328
1328
1329 # Completion logic:
1329 # Completion logic:
1330 # - user gives %%: only do cell magics
1330 # - user gives %%: only do cell magics
1331 # - user gives %: do both line and cell magics
1331 # - user gives %: do both line and cell magics
1332 # - no prefix: do both
1332 # - no prefix: do both
1333 # In other words, line magics are skipped if the user gives %% explicitly
1333 # In other words, line magics are skipped if the user gives %% explicitly
1334 #
1334 #
1335 # We also exclude magics that match any currently visible names:
1335 # We also exclude magics that match any currently visible names:
1336 # https://github.com/ipython/ipython/issues/4877, unless the user has
1336 # https://github.com/ipython/ipython/issues/4877, unless the user has
1337 # typed a %:
1337 # typed a %:
1338 # https://github.com/ipython/ipython/issues/10754
1338 # https://github.com/ipython/ipython/issues/10754
1339 bare_text = text.lstrip(pre)
1339 bare_text = text.lstrip(pre)
1340 global_matches = self.global_matches(bare_text)
1340 global_matches = self.global_matches(bare_text)
1341 if not explicit_magic:
1341 if not explicit_magic:
1342 def matches(magic):
1342 def matches(magic):
1343 """
1343 """
1344 Filter magics, in particular remove magics that match
1344 Filter magics, in particular remove magics that match
1345 a name present in global namespace.
1345 a name present in global namespace.
1346 """
1346 """
1347 return ( magic.startswith(bare_text) and
1347 return ( magic.startswith(bare_text) and
1348 magic not in global_matches )
1348 magic not in global_matches )
1349 else:
1349 else:
1350 def matches(magic):
1350 def matches(magic):
1351 return magic.startswith(bare_text)
1351 return magic.startswith(bare_text)
1352
1352
1353 comp = [ pre2+m for m in cell_magics if matches(m)]
1353 comp = [ pre2+m for m in cell_magics if matches(m)]
1354 if not text.startswith(pre2):
1354 if not text.startswith(pre2):
1355 comp += [ pre+m for m in line_magics if matches(m)]
1355 comp += [ pre+m for m in line_magics if matches(m)]
1356
1356
1357 return comp
1357 return comp
1358
1358
1359 def magic_config_matches(self, text:str) -> List[str]:
1359 def magic_config_matches(self, text:str) -> List[str]:
1360 """ Match class names and attributes for %config magic """
1360 """ Match class names and attributes for %config magic """
1361 texts = text.strip().split()
1361 texts = text.strip().split()
1362
1362
1363 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1363 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1364 # get all configuration classes
1364 # get all configuration classes
1365 classes = sorted(set([ c for c in self.shell.configurables
1365 classes = sorted(set([ c for c in self.shell.configurables
1366 if c.__class__.class_traits(config=True)
1366 if c.__class__.class_traits(config=True)
1367 ]), key=lambda x: x.__class__.__name__)
1367 ]), key=lambda x: x.__class__.__name__)
1368 classnames = [ c.__class__.__name__ for c in classes ]
1368 classnames = [ c.__class__.__name__ for c in classes ]
1369
1369
1370 # return all classnames if config or %config is given
1370 # return all classnames if config or %config is given
1371 if len(texts) == 1:
1371 if len(texts) == 1:
1372 return classnames
1372 return classnames
1373
1373
1374 # match classname
1374 # match classname
1375 classname_texts = texts[1].split('.')
1375 classname_texts = texts[1].split('.')
1376 classname = classname_texts[0]
1376 classname = classname_texts[0]
1377 classname_matches = [ c for c in classnames
1377 classname_matches = [ c for c in classnames
1378 if c.startswith(classname) ]
1378 if c.startswith(classname) ]
1379
1379
1380 # return matched classes or the matched class with attributes
1380 # return matched classes or the matched class with attributes
1381 if texts[1].find('.') < 0:
1381 if texts[1].find('.') < 0:
1382 return classname_matches
1382 return classname_matches
1383 elif len(classname_matches) == 1 and \
1383 elif len(classname_matches) == 1 and \
1384 classname_matches[0] == classname:
1384 classname_matches[0] == classname:
1385 cls = classes[classnames.index(classname)].__class__
1385 cls = classes[classnames.index(classname)].__class__
1386 help = cls.class_get_help()
1386 help = cls.class_get_help()
1387 # strip leading '--' from cl-args:
1387 # strip leading '--' from cl-args:
1388 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1388 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1389 return [ attr.split('=')[0]
1389 return [ attr.split('=')[0]
1390 for attr in help.strip().splitlines()
1390 for attr in help.strip().splitlines()
1391 if attr.startswith(texts[1]) ]
1391 if attr.startswith(texts[1]) ]
1392 return []
1392 return []
1393
1393
1394 def magic_color_matches(self, text:str) -> List[str] :
1394 def magic_color_matches(self, text:str) -> List[str] :
1395 """ Match color schemes for %colors magic"""
1395 """ Match color schemes for %colors magic"""
1396 texts = text.split()
1396 texts = text.split()
1397 if text.endswith(' '):
1397 if text.endswith(' '):
1398 # .split() strips off the trailing whitespace. Add '' back
1398 # .split() strips off the trailing whitespace. Add '' back
1399 # so that: '%colors ' -> ['%colors', '']
1399 # so that: '%colors ' -> ['%colors', '']
1400 texts.append('')
1400 texts.append('')
1401
1401
1402 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1402 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1403 prefix = texts[1]
1403 prefix = texts[1]
1404 return [ color for color in InspectColors.keys()
1404 return [ color for color in InspectColors.keys()
1405 if color.startswith(prefix) ]
1405 if color.startswith(prefix) ]
1406 return []
1406 return []
1407
1407
1408 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str) -> Iterable[Any]:
1408 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str) -> Iterable[Any]:
1409 """
1409 """
1410 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1410 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1411 cursor position.
1411 cursor position.
1412
1412
1413 Parameters
1413 Parameters
1414 ----------
1414 ----------
1415 cursor_column : int
1415 cursor_column : int
1416 column position of the cursor in ``text``, 0-indexed.
1416 column position of the cursor in ``text``, 0-indexed.
1417 cursor_line : int
1417 cursor_line : int
1418 line position of the cursor in ``text``, 0-indexed
1418 line position of the cursor in ``text``, 0-indexed
1419 text : str
1419 text : str
1420 text to complete
1420 text to complete
1421
1421
1422 Notes
1422 Notes
1423 -----
1423 -----
1424 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1424 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1425 object containing a string with the Jedi debug information attached.
1425 object containing a string with the Jedi debug information attached.
1426 """
1426 """
1427 namespaces = [self.namespace]
1427 namespaces = [self.namespace]
1428 if self.global_namespace is not None:
1428 if self.global_namespace is not None:
1429 namespaces.append(self.global_namespace)
1429 namespaces.append(self.global_namespace)
1430
1430
1431 completion_filter = lambda x:x
1431 completion_filter = lambda x:x
1432 offset = cursor_to_position(text, cursor_line, cursor_column)
1432 offset = cursor_to_position(text, cursor_line, cursor_column)
1433 # filter output if we are completing for object members
1433 # filter output if we are completing for object members
1434 if offset:
1434 if offset:
1435 pre = text[offset-1]
1435 pre = text[offset-1]
1436 if pre == '.':
1436 if pre == '.':
1437 if self.omit__names == 2:
1437 if self.omit__names == 2:
1438 completion_filter = lambda c:not c.name.startswith('_')
1438 completion_filter = lambda c:not c.name.startswith('_')
1439 elif self.omit__names == 1:
1439 elif self.omit__names == 1:
1440 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1440 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1441 elif self.omit__names == 0:
1441 elif self.omit__names == 0:
1442 completion_filter = lambda x:x
1442 completion_filter = lambda x:x
1443 else:
1443 else:
1444 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1444 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1445
1445
1446 interpreter = jedi.Interpreter(text[:offset], namespaces)
1446 interpreter = jedi.Interpreter(text[:offset], namespaces)
1447 try_jedi = True
1447 try_jedi = True
1448
1448
1449 try:
1449 try:
1450 # find the first token in the current tree -- if it is a ' or " then we are in a string
1450 # find the first token in the current tree -- if it is a ' or " then we are in a string
1451 completing_string = False
1451 completing_string = False
1452 try:
1452 try:
1453 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1453 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1454 except StopIteration:
1454 except StopIteration:
1455 pass
1455 pass
1456 else:
1456 else:
1457 # note the value may be ', ", or it may also be ''' or """, or
1457 # note the value may be ', ", or it may also be ''' or """, or
1458 # in some cases, """what/you/typed..., but all of these are
1458 # in some cases, """what/you/typed..., but all of these are
1459 # strings.
1459 # strings.
1460 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1460 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1461
1461
1462 # if we are in a string jedi is likely not the right candidate for
1462 # if we are in a string jedi is likely not the right candidate for
1463 # now. Skip it.
1463 # now. Skip it.
1464 try_jedi = not completing_string
1464 try_jedi = not completing_string
1465 except Exception as e:
1465 except Exception as e:
1466 # many of things can go wrong, we are using private API just don't crash.
1466 # many of things can go wrong, we are using private API just don't crash.
1467 if self.debug:
1467 if self.debug:
1468 print("Error detecting if completing a non-finished string :", e, '|')
1468 print("Error detecting if completing a non-finished string :", e, '|')
1469
1469
1470 if not try_jedi:
1470 if not try_jedi:
1471 return []
1471 return []
1472 try:
1472 try:
1473 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1473 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1474 except Exception as e:
1474 except Exception as e:
1475 if self.debug:
1475 if self.debug:
1476 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1476 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1477 else:
1477 else:
1478 return []
1478 return []
1479
1479
1480 def python_matches(self, text:str)->List[str]:
1480 def python_matches(self, text:str)->List[str]:
1481 """Match attributes or global python names"""
1481 """Match attributes or global python names"""
1482 if "." in text:
1482 if "." in text:
1483 try:
1483 try:
1484 matches = self.attr_matches(text)
1484 matches = self.attr_matches(text)
1485 if text.endswith('.') and self.omit__names:
1485 if text.endswith('.') and self.omit__names:
1486 if self.omit__names == 1:
1486 if self.omit__names == 1:
1487 # true if txt is _not_ a __ name, false otherwise:
1487 # true if txt is _not_ a __ name, false otherwise:
1488 no__name = (lambda txt:
1488 no__name = (lambda txt:
1489 re.match(r'.*\.__.*?__',txt) is None)
1489 re.match(r'.*\.__.*?__',txt) is None)
1490 else:
1490 else:
1491 # true if txt is _not_ a _ name, false otherwise:
1491 # true if txt is _not_ a _ name, false otherwise:
1492 no__name = (lambda txt:
1492 no__name = (lambda txt:
1493 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1493 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1494 matches = filter(no__name, matches)
1494 matches = filter(no__name, matches)
1495 except NameError:
1495 except NameError:
1496 # catches <undefined attributes>.<tab>
1496 # catches <undefined attributes>.<tab>
1497 matches = []
1497 matches = []
1498 else:
1498 else:
1499 matches = self.global_matches(text)
1499 matches = self.global_matches(text)
1500 return matches
1500 return matches
1501
1501
1502 def _default_arguments_from_docstring(self, doc):
1502 def _default_arguments_from_docstring(self, doc):
1503 """Parse the first line of docstring for call signature.
1503 """Parse the first line of docstring for call signature.
1504
1504
1505 Docstring should be of the form 'min(iterable[, key=func])\n'.
1505 Docstring should be of the form 'min(iterable[, key=func])\n'.
1506 It can also parse cython docstring of the form
1506 It can also parse cython docstring of the form
1507 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1507 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1508 """
1508 """
1509 if doc is None:
1509 if doc is None:
1510 return []
1510 return []
1511
1511
1512 #care only the firstline
1512 #care only the firstline
1513 line = doc.lstrip().splitlines()[0]
1513 line = doc.lstrip().splitlines()[0]
1514
1514
1515 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1515 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1516 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1516 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1517 sig = self.docstring_sig_re.search(line)
1517 sig = self.docstring_sig_re.search(line)
1518 if sig is None:
1518 if sig is None:
1519 return []
1519 return []
1520 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1520 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1521 sig = sig.groups()[0].split(',')
1521 sig = sig.groups()[0].split(',')
1522 ret = []
1522 ret = []
1523 for s in sig:
1523 for s in sig:
1524 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1524 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1525 ret += self.docstring_kwd_re.findall(s)
1525 ret += self.docstring_kwd_re.findall(s)
1526 return ret
1526 return ret
1527
1527
1528 def _default_arguments(self, obj):
1528 def _default_arguments(self, obj):
1529 """Return the list of default arguments of obj if it is callable,
1529 """Return the list of default arguments of obj if it is callable,
1530 or empty list otherwise."""
1530 or empty list otherwise."""
1531 call_obj = obj
1531 call_obj = obj
1532 ret = []
1532 ret = []
1533 if inspect.isbuiltin(obj):
1533 if inspect.isbuiltin(obj):
1534 pass
1534 pass
1535 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1535 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1536 if inspect.isclass(obj):
1536 if inspect.isclass(obj):
1537 #for cython embedsignature=True the constructor docstring
1537 #for cython embedsignature=True the constructor docstring
1538 #belongs to the object itself not __init__
1538 #belongs to the object itself not __init__
1539 ret += self._default_arguments_from_docstring(
1539 ret += self._default_arguments_from_docstring(
1540 getattr(obj, '__doc__', ''))
1540 getattr(obj, '__doc__', ''))
1541 # for classes, check for __init__,__new__
1541 # for classes, check for __init__,__new__
1542 call_obj = (getattr(obj, '__init__', None) or
1542 call_obj = (getattr(obj, '__init__', None) or
1543 getattr(obj, '__new__', None))
1543 getattr(obj, '__new__', None))
1544 # for all others, check if they are __call__able
1544 # for all others, check if they are __call__able
1545 elif hasattr(obj, '__call__'):
1545 elif hasattr(obj, '__call__'):
1546 call_obj = obj.__call__
1546 call_obj = obj.__call__
1547 ret += self._default_arguments_from_docstring(
1547 ret += self._default_arguments_from_docstring(
1548 getattr(call_obj, '__doc__', ''))
1548 getattr(call_obj, '__doc__', ''))
1549
1549
1550 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1550 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1551 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1551 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1552
1552
1553 try:
1553 try:
1554 sig = inspect.signature(obj)
1554 sig = inspect.signature(obj)
1555 ret.extend(k for k, v in sig.parameters.items() if
1555 ret.extend(k for k, v in sig.parameters.items() if
1556 v.kind in _keeps)
1556 v.kind in _keeps)
1557 except ValueError:
1557 except ValueError:
1558 pass
1558 pass
1559
1559
1560 return list(set(ret))
1560 return list(set(ret))
1561
1561
1562 def python_func_kw_matches(self, text):
1562 def python_func_kw_matches(self, text):
1563 """Match named parameters (kwargs) of the last open function"""
1563 """Match named parameters (kwargs) of the last open function"""
1564
1564
1565 if "." in text: # a parameter cannot be dotted
1565 if "." in text: # a parameter cannot be dotted
1566 return []
1566 return []
1567 try: regexp = self.__funcParamsRegex
1567 try: regexp = self.__funcParamsRegex
1568 except AttributeError:
1568 except AttributeError:
1569 regexp = self.__funcParamsRegex = re.compile(r'''
1569 regexp = self.__funcParamsRegex = re.compile(r'''
1570 '.*?(?<!\\)' | # single quoted strings or
1570 '.*?(?<!\\)' | # single quoted strings or
1571 ".*?(?<!\\)" | # double quoted strings or
1571 ".*?(?<!\\)" | # double quoted strings or
1572 \w+ | # identifier
1572 \w+ | # identifier
1573 \S # other characters
1573 \S # other characters
1574 ''', re.VERBOSE | re.DOTALL)
1574 ''', re.VERBOSE | re.DOTALL)
1575 # 1. find the nearest identifier that comes before an unclosed
1575 # 1. find the nearest identifier that comes before an unclosed
1576 # parenthesis before the cursor
1576 # parenthesis before the cursor
1577 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1577 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1578 tokens = regexp.findall(self.text_until_cursor)
1578 tokens = regexp.findall(self.text_until_cursor)
1579 iterTokens = reversed(tokens); openPar = 0
1579 iterTokens = reversed(tokens); openPar = 0
1580
1580
1581 for token in iterTokens:
1581 for token in iterTokens:
1582 if token == ')':
1582 if token == ')':
1583 openPar -= 1
1583 openPar -= 1
1584 elif token == '(':
1584 elif token == '(':
1585 openPar += 1
1585 openPar += 1
1586 if openPar > 0:
1586 if openPar > 0:
1587 # found the last unclosed parenthesis
1587 # found the last unclosed parenthesis
1588 break
1588 break
1589 else:
1589 else:
1590 return []
1590 return []
1591 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1591 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1592 ids = []
1592 ids = []
1593 isId = re.compile(r'\w+$').match
1593 isId = re.compile(r'\w+$').match
1594
1594
1595 while True:
1595 while True:
1596 try:
1596 try:
1597 ids.append(next(iterTokens))
1597 ids.append(next(iterTokens))
1598 if not isId(ids[-1]):
1598 if not isId(ids[-1]):
1599 ids.pop(); break
1599 ids.pop(); break
1600 if not next(iterTokens) == '.':
1600 if not next(iterTokens) == '.':
1601 break
1601 break
1602 except StopIteration:
1602 except StopIteration:
1603 break
1603 break
1604
1604
1605 # Find all named arguments already assigned to, as to avoid suggesting
1605 # Find all named arguments already assigned to, as to avoid suggesting
1606 # them again
1606 # them again
1607 usedNamedArgs = set()
1607 usedNamedArgs = set()
1608 par_level = -1
1608 par_level = -1
1609 for token, next_token in zip(tokens, tokens[1:]):
1609 for token, next_token in zip(tokens, tokens[1:]):
1610 if token == '(':
1610 if token == '(':
1611 par_level += 1
1611 par_level += 1
1612 elif token == ')':
1612 elif token == ')':
1613 par_level -= 1
1613 par_level -= 1
1614
1614
1615 if par_level != 0:
1615 if par_level != 0:
1616 continue
1616 continue
1617
1617
1618 if next_token != '=':
1618 if next_token != '=':
1619 continue
1619 continue
1620
1620
1621 usedNamedArgs.add(token)
1621 usedNamedArgs.add(token)
1622
1622
1623 argMatches = []
1623 argMatches = []
1624 try:
1624 try:
1625 callableObj = '.'.join(ids[::-1])
1625 callableObj = '.'.join(ids[::-1])
1626 namedArgs = self._default_arguments(eval(callableObj,
1626 namedArgs = self._default_arguments(eval(callableObj,
1627 self.namespace))
1627 self.namespace))
1628
1628
1629 # Remove used named arguments from the list, no need to show twice
1629 # Remove used named arguments from the list, no need to show twice
1630 for namedArg in set(namedArgs) - usedNamedArgs:
1630 for namedArg in set(namedArgs) - usedNamedArgs:
1631 if namedArg.startswith(text):
1631 if namedArg.startswith(text):
1632 argMatches.append("%s=" %namedArg)
1632 argMatches.append("%s=" %namedArg)
1633 except:
1633 except:
1634 pass
1634 pass
1635
1635
1636 return argMatches
1636 return argMatches
1637
1637
1638 @staticmethod
1638 @staticmethod
1639 def _get_keys(obj: Any) -> List[Any]:
1639 def _get_keys(obj: Any) -> List[Any]:
1640 # Objects can define their own completions by defining an
1640 # Objects can define their own completions by defining an
1641 # _ipy_key_completions_() method.
1641 # _ipy_key_completions_() method.
1642 method = get_real_method(obj, '_ipython_key_completions_')
1642 method = get_real_method(obj, '_ipython_key_completions_')
1643 if method is not None:
1643 if method is not None:
1644 return method()
1644 return method()
1645
1645
1646 # Special case some common in-memory dict-like types
1646 # Special case some common in-memory dict-like types
1647 if isinstance(obj, dict) or\
1647 if isinstance(obj, dict) or\
1648 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1648 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1649 try:
1649 try:
1650 return list(obj.keys())
1650 return list(obj.keys())
1651 except Exception:
1651 except Exception:
1652 return []
1652 return []
1653 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1653 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1654 _safe_isinstance(obj, 'numpy', 'void'):
1654 _safe_isinstance(obj, 'numpy', 'void'):
1655 return obj.dtype.names or []
1655 return obj.dtype.names or []
1656 return []
1656 return []
1657
1657
1658 def dict_key_matches(self, text:str) -> List[str]:
1658 def dict_key_matches(self, text:str) -> List[str]:
1659 "Match string keys in a dictionary, after e.g. 'foo[' "
1659 "Match string keys in a dictionary, after e.g. 'foo[' "
1660
1660
1661
1661
1662 if self.__dict_key_regexps is not None:
1662 if self.__dict_key_regexps is not None:
1663 regexps = self.__dict_key_regexps
1663 regexps = self.__dict_key_regexps
1664 else:
1664 else:
1665 dict_key_re_fmt = r'''(?x)
1665 dict_key_re_fmt = r'''(?x)
1666 ( # match dict-referring expression wrt greedy setting
1666 ( # match dict-referring expression wrt greedy setting
1667 %s
1667 %s
1668 )
1668 )
1669 \[ # open bracket
1669 \[ # open bracket
1670 \s* # and optional whitespace
1670 \s* # and optional whitespace
1671 # Capture any number of str-like objects (e.g. "a", "b", 'c')
1671 # Capture any number of str-like objects (e.g. "a", "b", 'c')
1672 ((?:[uUbB]? # string prefix (r not handled)
1672 ((?:[uUbB]? # string prefix (r not handled)
1673 (?:
1673 (?:
1674 '(?:[^']|(?<!\\)\\')*'
1674 '(?:[^']|(?<!\\)\\')*'
1675 |
1675 |
1676 "(?:[^"]|(?<!\\)\\")*"
1676 "(?:[^"]|(?<!\\)\\")*"
1677 )
1677 )
1678 \s*,\s*
1678 \s*,\s*
1679 )*)
1679 )*)
1680 ([uUbB]? # string prefix (r not handled)
1680 ([uUbB]? # string prefix (r not handled)
1681 (?: # unclosed string
1681 (?: # unclosed string
1682 '(?:[^']|(?<!\\)\\')*
1682 '(?:[^']|(?<!\\)\\')*
1683 |
1683 |
1684 "(?:[^"]|(?<!\\)\\")*
1684 "(?:[^"]|(?<!\\)\\")*
1685 )
1685 )
1686 )?
1686 )?
1687 $
1687 $
1688 '''
1688 '''
1689 regexps = self.__dict_key_regexps = {
1689 regexps = self.__dict_key_regexps = {
1690 False: re.compile(dict_key_re_fmt % r'''
1690 False: re.compile(dict_key_re_fmt % r'''
1691 # identifiers separated by .
1691 # identifiers separated by .
1692 (?!\d)\w+
1692 (?!\d)\w+
1693 (?:\.(?!\d)\w+)*
1693 (?:\.(?!\d)\w+)*
1694 '''),
1694 '''),
1695 True: re.compile(dict_key_re_fmt % '''
1695 True: re.compile(dict_key_re_fmt % '''
1696 .+
1696 .+
1697 ''')
1697 ''')
1698 }
1698 }
1699
1699
1700 match = regexps[self.greedy].search(self.text_until_cursor)
1700 match = regexps[self.greedy].search(self.text_until_cursor)
1701
1701
1702 if match is None:
1702 if match is None:
1703 return []
1703 return []
1704
1704
1705 expr, prefix0, prefix = match.groups()
1705 expr, prefix0, prefix = match.groups()
1706 try:
1706 try:
1707 obj = eval(expr, self.namespace)
1707 obj = eval(expr, self.namespace)
1708 except Exception:
1708 except Exception:
1709 try:
1709 try:
1710 obj = eval(expr, self.global_namespace)
1710 obj = eval(expr, self.global_namespace)
1711 except Exception:
1711 except Exception:
1712 return []
1712 return []
1713
1713
1714 keys = self._get_keys(obj)
1714 keys = self._get_keys(obj)
1715 if not keys:
1715 if not keys:
1716 return keys
1716 return keys
1717
1717
1718 extra_prefix = eval(prefix0) if prefix0 != '' else None
1718 extra_prefix = eval(prefix0) if prefix0 != '' else None
1719
1719
1720 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
1720 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
1721 if not matches:
1721 if not matches:
1722 return matches
1722 return matches
1723
1723
1724 # get the cursor position of
1724 # get the cursor position of
1725 # - the text being completed
1725 # - the text being completed
1726 # - the start of the key text
1726 # - the start of the key text
1727 # - the start of the completion
1727 # - the start of the completion
1728 text_start = len(self.text_until_cursor) - len(text)
1728 text_start = len(self.text_until_cursor) - len(text)
1729 if prefix:
1729 if prefix:
1730 key_start = match.start(3)
1730 key_start = match.start(3)
1731 completion_start = key_start + token_offset
1731 completion_start = key_start + token_offset
1732 else:
1732 else:
1733 key_start = completion_start = match.end()
1733 key_start = completion_start = match.end()
1734
1734
1735 # grab the leading prefix, to make sure all completions start with `text`
1735 # grab the leading prefix, to make sure all completions start with `text`
1736 if text_start > key_start:
1736 if text_start > key_start:
1737 leading = ''
1737 leading = ''
1738 else:
1738 else:
1739 leading = text[text_start:completion_start]
1739 leading = text[text_start:completion_start]
1740
1740
1741 # the index of the `[` character
1741 # the index of the `[` character
1742 bracket_idx = match.end(1)
1742 bracket_idx = match.end(1)
1743
1743
1744 # append closing quote and bracket as appropriate
1744 # append closing quote and bracket as appropriate
1745 # this is *not* appropriate if the opening quote or bracket is outside
1745 # this is *not* appropriate if the opening quote or bracket is outside
1746 # the text given to this method
1746 # the text given to this method
1747 suf = ''
1747 suf = ''
1748 continuation = self.line_buffer[len(self.text_until_cursor):]
1748 continuation = self.line_buffer[len(self.text_until_cursor):]
1749 if key_start > text_start and closing_quote:
1749 if key_start > text_start and closing_quote:
1750 # quotes were opened inside text, maybe close them
1750 # quotes were opened inside text, maybe close them
1751 if continuation.startswith(closing_quote):
1751 if continuation.startswith(closing_quote):
1752 continuation = continuation[len(closing_quote):]
1752 continuation = continuation[len(closing_quote):]
1753 else:
1753 else:
1754 suf += closing_quote
1754 suf += closing_quote
1755 if bracket_idx > text_start:
1755 if bracket_idx > text_start:
1756 # brackets were opened inside text, maybe close them
1756 # brackets were opened inside text, maybe close them
1757 if not continuation.startswith(']'):
1757 if not continuation.startswith(']'):
1758 suf += ']'
1758 suf += ']'
1759
1759
1760 return [leading + k + suf for k in matches]
1760 return [leading + k + suf for k in matches]
1761
1761
1762 @staticmethod
1762 @staticmethod
1763 def unicode_name_matches(text:str) -> Tuple[str, List[str]] :
1763 def unicode_name_matches(text:str) -> Tuple[str, List[str]] :
1764 """Match Latex-like syntax for unicode characters base
1764 """Match Latex-like syntax for unicode characters base
1765 on the name of the character.
1765 on the name of the character.
1766
1766
1767 This does ``\\GREEK SMALL LETTER ETA`` -> ``η``
1767 This does ``\\GREEK SMALL LETTER ETA`` -> ``η``
1768
1768
1769 Works only on valid python 3 identifier, or on combining characters that
1769 Works only on valid python 3 identifier, or on combining characters that
1770 will combine to form a valid identifier.
1770 will combine to form a valid identifier.
1771 """
1771 """
1772 slashpos = text.rfind('\\')
1772 slashpos = text.rfind('\\')
1773 if slashpos > -1:
1773 if slashpos > -1:
1774 s = text[slashpos+1:]
1774 s = text[slashpos+1:]
1775 try :
1775 try :
1776 unic = unicodedata.lookup(s)
1776 unic = unicodedata.lookup(s)
1777 # allow combining chars
1777 # allow combining chars
1778 if ('a'+unic).isidentifier():
1778 if ('a'+unic).isidentifier():
1779 return '\\'+s,[unic]
1779 return '\\'+s,[unic]
1780 except KeyError:
1780 except KeyError:
1781 pass
1781 pass
1782 return '', []
1782 return '', []
1783
1783
1784
1784
1785 def latex_matches(self, text:str) -> Tuple[str, Sequence[str]]:
1785 def latex_matches(self, text:str) -> Tuple[str, Sequence[str]]:
1786 """Match Latex syntax for unicode characters.
1786 """Match Latex syntax for unicode characters.
1787
1787
1788 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``
1788 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``
1789 """
1789 """
1790 slashpos = text.rfind('\\')
1790 slashpos = text.rfind('\\')
1791 if slashpos > -1:
1791 if slashpos > -1:
1792 s = text[slashpos:]
1792 s = text[slashpos:]
1793 if s in latex_symbols:
1793 if s in latex_symbols:
1794 # Try to complete a full latex symbol to unicode
1794 # Try to complete a full latex symbol to unicode
1795 # \\alpha -> α
1795 # \\alpha -> α
1796 return s, [latex_symbols[s]]
1796 return s, [latex_symbols[s]]
1797 else:
1797 else:
1798 # If a user has partially typed a latex symbol, give them
1798 # If a user has partially typed a latex symbol, give them
1799 # a full list of options \al -> [\aleph, \alpha]
1799 # a full list of options \al -> [\aleph, \alpha]
1800 matches = [k for k in latex_symbols if k.startswith(s)]
1800 matches = [k for k in latex_symbols if k.startswith(s)]
1801 if matches:
1801 if matches:
1802 return s, matches
1802 return s, matches
1803 return '', ()
1803 return '', ()
1804
1804
1805 def dispatch_custom_completer(self, text):
1805 def dispatch_custom_completer(self, text):
1806 if not self.custom_completers:
1806 if not self.custom_completers:
1807 return
1807 return
1808
1808
1809 line = self.line_buffer
1809 line = self.line_buffer
1810 if not line.strip():
1810 if not line.strip():
1811 return None
1811 return None
1812
1812
1813 # Create a little structure to pass all the relevant information about
1813 # Create a little structure to pass all the relevant information about
1814 # the current completion to any custom completer.
1814 # the current completion to any custom completer.
1815 event = SimpleNamespace()
1815 event = SimpleNamespace()
1816 event.line = line
1816 event.line = line
1817 event.symbol = text
1817 event.symbol = text
1818 cmd = line.split(None,1)[0]
1818 cmd = line.split(None,1)[0]
1819 event.command = cmd
1819 event.command = cmd
1820 event.text_until_cursor = self.text_until_cursor
1820 event.text_until_cursor = self.text_until_cursor
1821
1821
1822 # for foo etc, try also to find completer for %foo
1822 # for foo etc, try also to find completer for %foo
1823 if not cmd.startswith(self.magic_escape):
1823 if not cmd.startswith(self.magic_escape):
1824 try_magic = self.custom_completers.s_matches(
1824 try_magic = self.custom_completers.s_matches(
1825 self.magic_escape + cmd)
1825 self.magic_escape + cmd)
1826 else:
1826 else:
1827 try_magic = []
1827 try_magic = []
1828
1828
1829 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1829 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1830 try_magic,
1830 try_magic,
1831 self.custom_completers.flat_matches(self.text_until_cursor)):
1831 self.custom_completers.flat_matches(self.text_until_cursor)):
1832 try:
1832 try:
1833 res = c(event)
1833 res = c(event)
1834 if res:
1834 if res:
1835 # first, try case sensitive match
1835 # first, try case sensitive match
1836 withcase = [r for r in res if r.startswith(text)]
1836 withcase = [r for r in res if r.startswith(text)]
1837 if withcase:
1837 if withcase:
1838 return withcase
1838 return withcase
1839 # if none, then case insensitive ones are ok too
1839 # if none, then case insensitive ones are ok too
1840 text_low = text.lower()
1840 text_low = text.lower()
1841 return [r for r in res if r.lower().startswith(text_low)]
1841 return [r for r in res if r.lower().startswith(text_low)]
1842 except TryNext:
1842 except TryNext:
1843 pass
1843 pass
1844 except KeyboardInterrupt:
1844 except KeyboardInterrupt:
1845 """
1845 """
1846 If custom completer take too long,
1846 If custom completer take too long,
1847 let keyboard interrupt abort and return nothing.
1847 let keyboard interrupt abort and return nothing.
1848 """
1848 """
1849 break
1849 break
1850
1850
1851 return None
1851 return None
1852
1852
1853 def completions(self, text: str, offset: int)->Iterator[Completion]:
1853 def completions(self, text: str, offset: int)->Iterator[Completion]:
1854 """
1854 """
1855 Returns an iterator over the possible completions
1855 Returns an iterator over the possible completions
1856
1856
1857 .. warning::
1857 .. warning::
1858
1858
1859 Unstable
1859 Unstable
1860
1860
1861 This function is unstable, API may change without warning.
1861 This function is unstable, API may change without warning.
1862 It will also raise unless use in proper context manager.
1862 It will also raise unless use in proper context manager.
1863
1863
1864 Parameters
1864 Parameters
1865 ----------
1865 ----------
1866 text : str
1866 text : str
1867 Full text of the current input, multi line string.
1867 Full text of the current input, multi line string.
1868 offset : int
1868 offset : int
1869 Integer representing the position of the cursor in ``text``. Offset
1869 Integer representing the position of the cursor in ``text``. Offset
1870 is 0-based indexed.
1870 is 0-based indexed.
1871
1871
1872 Yields
1872 Yields
1873 ------
1873 ------
1874 Completion
1874 Completion
1875
1875
1876 Notes
1876 Notes
1877 -----
1877 -----
1878 The cursor on a text can either be seen as being "in between"
1878 The cursor on a text can either be seen as being "in between"
1879 characters or "On" a character depending on the interface visible to
1879 characters or "On" a character depending on the interface visible to
1880 the user. For consistency the cursor being on "in between" characters X
1880 the user. For consistency the cursor being on "in between" characters X
1881 and Y is equivalent to the cursor being "on" character Y, that is to say
1881 and Y is equivalent to the cursor being "on" character Y, that is to say
1882 the character the cursor is on is considered as being after the cursor.
1882 the character the cursor is on is considered as being after the cursor.
1883
1883
1884 Combining characters may span more that one position in the
1884 Combining characters may span more that one position in the
1885 text.
1885 text.
1886
1886
1887 .. note::
1887 .. note::
1888
1888
1889 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1889 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1890 fake Completion token to distinguish completion returned by Jedi
1890 fake Completion token to distinguish completion returned by Jedi
1891 and usual IPython completion.
1891 and usual IPython completion.
1892
1892
1893 .. note::
1893 .. note::
1894
1894
1895 Completions are not completely deduplicated yet. If identical
1895 Completions are not completely deduplicated yet. If identical
1896 completions are coming from different sources this function does not
1896 completions are coming from different sources this function does not
1897 ensure that each completion object will only be present once.
1897 ensure that each completion object will only be present once.
1898 """
1898 """
1899 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1899 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1900 "It may change without warnings. "
1900 "It may change without warnings. "
1901 "Use in corresponding context manager.",
1901 "Use in corresponding context manager.",
1902 category=ProvisionalCompleterWarning, stacklevel=2)
1902 category=ProvisionalCompleterWarning, stacklevel=2)
1903
1903
1904 seen = set()
1904 seen = set()
1905 profiler:Optional[cProfile.Profile]
1905 profiler:Optional[cProfile.Profile]
1906 try:
1906 try:
1907 if self.profile_completions:
1907 if self.profile_completions:
1908 import cProfile
1908 import cProfile
1909 profiler = cProfile.Profile()
1909 profiler = cProfile.Profile()
1910 profiler.enable()
1910 profiler.enable()
1911 else:
1911 else:
1912 profiler = None
1912 profiler = None
1913
1913
1914 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1914 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1915 if c and (c in seen):
1915 if c and (c in seen):
1916 continue
1916 continue
1917 yield c
1917 yield c
1918 seen.add(c)
1918 seen.add(c)
1919 except KeyboardInterrupt:
1919 except KeyboardInterrupt:
1920 """if completions take too long and users send keyboard interrupt,
1920 """if completions take too long and users send keyboard interrupt,
1921 do not crash and return ASAP. """
1921 do not crash and return ASAP. """
1922 pass
1922 pass
1923 finally:
1923 finally:
1924 if profiler is not None:
1924 if profiler is not None:
1925 profiler.disable()
1925 profiler.disable()
1926 ensure_dir_exists(self.profiler_output_dir)
1926 ensure_dir_exists(self.profiler_output_dir)
1927 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
1927 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
1928 print("Writing profiler output to", output_path)
1928 print("Writing profiler output to", output_path)
1929 profiler.dump_stats(output_path)
1929 profiler.dump_stats(output_path)
1930
1930
1931 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
1931 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
1932 """
1932 """
1933 Core completion module.Same signature as :any:`completions`, with the
1933 Core completion module.Same signature as :any:`completions`, with the
1934 extra `timeout` parameter (in seconds).
1934 extra `timeout` parameter (in seconds).
1935
1935
1936 Computing jedi's completion ``.type`` can be quite expensive (it is a
1936 Computing jedi's completion ``.type`` can be quite expensive (it is a
1937 lazy property) and can require some warm-up, more warm up than just
1937 lazy property) and can require some warm-up, more warm up than just
1938 computing the ``name`` of a completion. The warm-up can be :
1938 computing the ``name`` of a completion. The warm-up can be :
1939
1939
1940 - Long warm-up the first time a module is encountered after
1940 - Long warm-up the first time a module is encountered after
1941 install/update: actually build parse/inference tree.
1941 install/update: actually build parse/inference tree.
1942
1942
1943 - first time the module is encountered in a session: load tree from
1943 - first time the module is encountered in a session: load tree from
1944 disk.
1944 disk.
1945
1945
1946 We don't want to block completions for tens of seconds so we give the
1946 We don't want to block completions for tens of seconds so we give the
1947 completer a "budget" of ``_timeout`` seconds per invocation to compute
1947 completer a "budget" of ``_timeout`` seconds per invocation to compute
1948 completions types, the completions that have not yet been computed will
1948 completions types, the completions that have not yet been computed will
1949 be marked as "unknown" an will have a chance to be computed next round
1949 be marked as "unknown" an will have a chance to be computed next round
1950 are things get cached.
1950 are things get cached.
1951
1951
1952 Keep in mind that Jedi is not the only thing treating the completion so
1952 Keep in mind that Jedi is not the only thing treating the completion so
1953 keep the timeout short-ish as if we take more than 0.3 second we still
1953 keep the timeout short-ish as if we take more than 0.3 second we still
1954 have lots of processing to do.
1954 have lots of processing to do.
1955
1955
1956 """
1956 """
1957 deadline = time.monotonic() + _timeout
1957 deadline = time.monotonic() + _timeout
1958
1958
1959
1959
1960 before = full_text[:offset]
1960 before = full_text[:offset]
1961 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1961 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1962
1962
1963 matched_text, matches, matches_origin, jedi_matches = self._complete(
1963 matched_text, matches, matches_origin, jedi_matches = self._complete(
1964 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1964 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1965
1965
1966 iter_jm = iter(jedi_matches)
1966 iter_jm = iter(jedi_matches)
1967 if _timeout:
1967 if _timeout:
1968 for jm in iter_jm:
1968 for jm in iter_jm:
1969 try:
1969 try:
1970 type_ = jm.type
1970 type_ = jm.type
1971 except Exception:
1971 except Exception:
1972 if self.debug:
1972 if self.debug:
1973 print("Error in Jedi getting type of ", jm)
1973 print("Error in Jedi getting type of ", jm)
1974 type_ = None
1974 type_ = None
1975 delta = len(jm.name_with_symbols) - len(jm.complete)
1975 delta = len(jm.name_with_symbols) - len(jm.complete)
1976 if type_ == 'function':
1976 if type_ == 'function':
1977 signature = _make_signature(jm)
1977 signature = _make_signature(jm)
1978 else:
1978 else:
1979 signature = ''
1979 signature = ''
1980 yield Completion(start=offset - delta,
1980 yield Completion(start=offset - delta,
1981 end=offset,
1981 end=offset,
1982 text=jm.name_with_symbols,
1982 text=jm.name_with_symbols,
1983 type=type_,
1983 type=type_,
1984 signature=signature,
1984 signature=signature,
1985 _origin='jedi')
1985 _origin='jedi')
1986
1986
1987 if time.monotonic() > deadline:
1987 if time.monotonic() > deadline:
1988 break
1988 break
1989
1989
1990 for jm in iter_jm:
1990 for jm in iter_jm:
1991 delta = len(jm.name_with_symbols) - len(jm.complete)
1991 delta = len(jm.name_with_symbols) - len(jm.complete)
1992 yield Completion(start=offset - delta,
1992 yield Completion(start=offset - delta,
1993 end=offset,
1993 end=offset,
1994 text=jm.name_with_symbols,
1994 text=jm.name_with_symbols,
1995 type='<unknown>', # don't compute type for speed
1995 type='<unknown>', # don't compute type for speed
1996 _origin='jedi',
1996 _origin='jedi',
1997 signature='')
1997 signature='')
1998
1998
1999
1999
2000 start_offset = before.rfind(matched_text)
2000 start_offset = before.rfind(matched_text)
2001
2001
2002 # TODO:
2002 # TODO:
2003 # Suppress this, right now just for debug.
2003 # Suppress this, right now just for debug.
2004 if jedi_matches and matches and self.debug:
2004 if jedi_matches and matches and self.debug:
2005 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
2005 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
2006 _origin='debug', type='none', signature='')
2006 _origin='debug', type='none', signature='')
2007
2007
2008 # I'm unsure if this is always true, so let's assert and see if it
2008 # I'm unsure if this is always true, so let's assert and see if it
2009 # crash
2009 # crash
2010 assert before.endswith(matched_text)
2010 assert before.endswith(matched_text)
2011 for m, t in zip(matches, matches_origin):
2011 for m, t in zip(matches, matches_origin):
2012 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
2012 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
2013
2013
2014
2014
2015 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2015 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2016 """Find completions for the given text and line context.
2016 """Find completions for the given text and line context.
2017
2017
2018 Note that both the text and the line_buffer are optional, but at least
2018 Note that both the text and the line_buffer are optional, but at least
2019 one of them must be given.
2019 one of them must be given.
2020
2020
2021 Parameters
2021 Parameters
2022 ----------
2022 ----------
2023 text : string, optional
2023 text : string, optional
2024 Text to perform the completion on. If not given, the line buffer
2024 Text to perform the completion on. If not given, the line buffer
2025 is split using the instance's CompletionSplitter object.
2025 is split using the instance's CompletionSplitter object.
2026 line_buffer : string, optional
2026 line_buffer : string, optional
2027 If not given, the completer attempts to obtain the current line
2027 If not given, the completer attempts to obtain the current line
2028 buffer via readline. This keyword allows clients which are
2028 buffer via readline. This keyword allows clients which are
2029 requesting for text completions in non-readline contexts to inform
2029 requesting for text completions in non-readline contexts to inform
2030 the completer of the entire text.
2030 the completer of the entire text.
2031 cursor_pos : int, optional
2031 cursor_pos : int, optional
2032 Index of the cursor in the full line buffer. Should be provided by
2032 Index of the cursor in the full line buffer. Should be provided by
2033 remote frontends where kernel has no access to frontend state.
2033 remote frontends where kernel has no access to frontend state.
2034
2034
2035 Returns
2035 Returns
2036 -------
2036 -------
2037 Tuple of two items:
2037 Tuple of two items:
2038 text : str
2038 text : str
2039 Text that was actually used in the completion.
2039 Text that was actually used in the completion.
2040 matches : list
2040 matches : list
2041 A list of completion matches.
2041 A list of completion matches.
2042
2042
2043 Notes
2043 Notes
2044 -----
2044 -----
2045 This API is likely to be deprecated and replaced by
2045 This API is likely to be deprecated and replaced by
2046 :any:`IPCompleter.completions` in the future.
2046 :any:`IPCompleter.completions` in the future.
2047
2047
2048 """
2048 """
2049 warnings.warn('`Completer.complete` is pending deprecation since '
2049 warnings.warn('`Completer.complete` is pending deprecation since '
2050 'IPython 6.0 and will be replaced by `Completer.completions`.',
2050 'IPython 6.0 and will be replaced by `Completer.completions`.',
2051 PendingDeprecationWarning)
2051 PendingDeprecationWarning)
2052 # potential todo, FOLD the 3rd throw away argument of _complete
2052 # potential todo, FOLD the 3rd throw away argument of _complete
2053 # into the first 2 one.
2053 # into the first 2 one.
2054 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
2054 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
2055
2055
2056 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2056 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2057 full_text=None) -> _CompleteResult:
2057 full_text=None) -> _CompleteResult:
2058 """
2058 """
2059 Like complete but can also returns raw jedi completions as well as the
2059 Like complete but can also returns raw jedi completions as well as the
2060 origin of the completion text. This could (and should) be made much
2060 origin of the completion text. This could (and should) be made much
2061 cleaner but that will be simpler once we drop the old (and stateful)
2061 cleaner but that will be simpler once we drop the old (and stateful)
2062 :any:`complete` API.
2062 :any:`complete` API.
2063
2063
2064 With current provisional API, cursor_pos act both (depending on the
2064 With current provisional API, cursor_pos act both (depending on the
2065 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2065 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2066 ``column`` when passing multiline strings this could/should be renamed
2066 ``column`` when passing multiline strings this could/should be renamed
2067 but would add extra noise.
2067 but would add extra noise.
2068
2068
2069 Parameters
2069 Parameters
2070 ----------
2070 ----------
2071 cursor_line :
2071 cursor_line :
2072 Index of the line the cursor is on. 0 indexed.
2072 Index of the line the cursor is on. 0 indexed.
2073 cursor_pos :
2073 cursor_pos :
2074 Position of the cursor in the current line/line_buffer/text. 0
2074 Position of the cursor in the current line/line_buffer/text. 0
2075 indexed.
2075 indexed.
2076 line_buffer : optional, str
2076 line_buffer : optional, str
2077 The current line the cursor is in, this is mostly due to legacy
2077 The current line the cursor is in, this is mostly due to legacy
2078 reason that readline coudl only give a us the single current line.
2078 reason that readline coudl only give a us the single current line.
2079 Prefer `full_text`.
2079 Prefer `full_text`.
2080 text : str
2080 text : str
2081 The current "token" the cursor is in, mostly also for historical
2081 The current "token" the cursor is in, mostly also for historical
2082 reasons. as the completer would trigger only after the current line
2082 reasons. as the completer would trigger only after the current line
2083 was parsed.
2083 was parsed.
2084 full_text : str
2084 full_text : str
2085 Full text of the current cell.
2085 Full text of the current cell.
2086
2086
2087 Returns
2087 Returns
2088 -------
2088 -------
2089 A tuple of N elements which are (likely):
2089 A tuple of N elements which are (likely):
2090 matched_text: ? the text that the complete matched
2090 matched_text: ? the text that the complete matched
2091 matches: list of completions ?
2091 matches: list of completions ?
2092 matches_origin: ? list same length as matches, and where each completion came from
2092 matches_origin: ? list same length as matches, and where each completion came from
2093 jedi_matches: list of Jedi matches, have it's own structure.
2093 jedi_matches: list of Jedi matches, have it's own structure.
2094 """
2094 """
2095
2095
2096
2096
2097 # if the cursor position isn't given, the only sane assumption we can
2097 # if the cursor position isn't given, the only sane assumption we can
2098 # make is that it's at the end of the line (the common case)
2098 # make is that it's at the end of the line (the common case)
2099 if cursor_pos is None:
2099 if cursor_pos is None:
2100 cursor_pos = len(line_buffer) if text is None else len(text)
2100 cursor_pos = len(line_buffer) if text is None else len(text)
2101
2101
2102 if self.use_main_ns:
2102 if self.use_main_ns:
2103 self.namespace = __main__.__dict__
2103 self.namespace = __main__.__dict__
2104
2104
2105 # if text is either None or an empty string, rely on the line buffer
2105 # if text is either None or an empty string, rely on the line buffer
2106 if (not line_buffer) and full_text:
2106 if (not line_buffer) and full_text:
2107 line_buffer = full_text.split('\n')[cursor_line]
2107 line_buffer = full_text.split('\n')[cursor_line]
2108 if not text: # issue #11508: check line_buffer before calling split_line
2108 if not text: # issue #11508: check line_buffer before calling split_line
2109 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2109 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2110
2110
2111 if self.backslash_combining_completions:
2111 if self.backslash_combining_completions:
2112 # allow deactivation of these on windows.
2112 # allow deactivation of these on windows.
2113 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2113 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2114
2114
2115 for meth in (self.latex_matches,
2115 for meth in (self.latex_matches,
2116 self.unicode_name_matches,
2116 self.unicode_name_matches,
2117 back_latex_name_matches,
2117 back_latex_name_matches,
2118 back_unicode_name_matches,
2118 back_unicode_name_matches,
2119 self.fwd_unicode_match):
2119 self.fwd_unicode_match):
2120 name_text, name_matches = meth(base_text)
2120 name_text, name_matches = meth(base_text)
2121 if name_text:
2121 if name_text:
2122 return _CompleteResult(name_text, name_matches[:MATCHES_LIMIT], \
2122 return _CompleteResult(name_text, name_matches[:MATCHES_LIMIT], \
2123 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ())
2123 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ())
2124
2124
2125
2125
2126 # If no line buffer is given, assume the input text is all there was
2126 # If no line buffer is given, assume the input text is all there was
2127 if line_buffer is None:
2127 if line_buffer is None:
2128 line_buffer = text
2128 line_buffer = text
2129
2129
2130 self.line_buffer = line_buffer
2130 self.line_buffer = line_buffer
2131 self.text_until_cursor = self.line_buffer[:cursor_pos]
2131 self.text_until_cursor = self.line_buffer[:cursor_pos]
2132
2132
2133 # Do magic arg matches
2133 # Do magic arg matches
2134 for matcher in self.magic_arg_matchers:
2134 for matcher in self.magic_arg_matchers:
2135 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2135 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2136 if matches:
2136 if matches:
2137 origins = [matcher.__qualname__] * len(matches)
2137 origins = [matcher.__qualname__] * len(matches)
2138 return _CompleteResult(text, matches, origins, ())
2138 return _CompleteResult(text, matches, origins, ())
2139
2139
2140 # Start with a clean slate of completions
2140 # Start with a clean slate of completions
2141 matches = []
2141 matches = []
2142
2142
2143 # FIXME: we should extend our api to return a dict with completions for
2143 # FIXME: we should extend our api to return a dict with completions for
2144 # different types of objects. The rlcomplete() method could then
2144 # different types of objects. The rlcomplete() method could then
2145 # simply collapse the dict into a list for readline, but we'd have
2145 # simply collapse the dict into a list for readline, but we'd have
2146 # richer completion semantics in other environments.
2146 # richer completion semantics in other environments.
2147 completions:Iterable[Any] = []
2147 completions:Iterable[Any] = []
2148 if self.use_jedi:
2148 if self.use_jedi:
2149 if not full_text:
2149 if not full_text:
2150 full_text = line_buffer
2150 full_text = line_buffer
2151 completions = self._jedi_matches(
2151 completions = self._jedi_matches(
2152 cursor_pos, cursor_line, full_text)
2152 cursor_pos, cursor_line, full_text)
2153
2153
2154 if self.merge_completions:
2154 if self.merge_completions:
2155 matches = []
2155 matches = []
2156 for matcher in self.matchers:
2156 for matcher in self.matchers:
2157 try:
2157 try:
2158 matches.extend([(m, matcher.__qualname__)
2158 matches.extend([(m, matcher.__qualname__)
2159 for m in matcher(text)])
2159 for m in matcher(text)])
2160 except:
2160 except:
2161 # Show the ugly traceback if the matcher causes an
2161 # Show the ugly traceback if the matcher causes an
2162 # exception, but do NOT crash the kernel!
2162 # exception, but do NOT crash the kernel!
2163 sys.excepthook(*sys.exc_info())
2163 sys.excepthook(*sys.exc_info())
2164 else:
2164 else:
2165 for matcher in self.matchers:
2165 for matcher in self.matchers:
2166 matches = [(m, matcher.__qualname__)
2166 matches = [(m, matcher.__qualname__)
2167 for m in matcher(text)]
2167 for m in matcher(text)]
2168 if matches:
2168 if matches:
2169 break
2169 break
2170
2170
2171 seen = set()
2171 seen = set()
2172 filtered_matches = set()
2172 filtered_matches = set()
2173 for m in matches:
2173 for m in matches:
2174 t, c = m
2174 t, c = m
2175 if t not in seen:
2175 if t not in seen:
2176 filtered_matches.add(m)
2176 filtered_matches.add(m)
2177 seen.add(t)
2177 seen.add(t)
2178
2178
2179 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2179 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2180
2180
2181 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2181 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2182
2182
2183 _filtered_matches = custom_res or _filtered_matches
2183 _filtered_matches = custom_res or _filtered_matches
2184
2184
2185 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2185 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2186 _matches = [m[0] for m in _filtered_matches]
2186 _matches = [m[0] for m in _filtered_matches]
2187 origins = [m[1] for m in _filtered_matches]
2187 origins = [m[1] for m in _filtered_matches]
2188
2188
2189 self.matches = _matches
2189 self.matches = _matches
2190
2190
2191 return _CompleteResult(text, _matches, origins, completions)
2191 return _CompleteResult(text, _matches, origins, completions)
2192
2192
2193 def fwd_unicode_match(self, text:str) -> Tuple[str, Sequence[str]]:
2193 def fwd_unicode_match(self, text:str) -> Tuple[str, Sequence[str]]:
2194 """
2194 """
2195 Forward match a string starting with a backslash with a list of
2195 Forward match a string starting with a backslash with a list of
2196 potential Unicode completions.
2196 potential Unicode completions.
2197
2197
2198 Will compute list list of Unicode character names on first call and cache it.
2198 Will compute list list of Unicode character names on first call and cache it.
2199
2199
2200 Returns
2200 Returns
2201 -------
2201 -------
2202 At tuple with:
2202 At tuple with:
2203 - matched text (empty if no matches)
2203 - matched text (empty if no matches)
2204 - list of potential completions, empty tuple otherwise)
2204 - list of potential completions, empty tuple otherwise)
2205 """
2205 """
2206 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2206 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2207 # We could do a faster match using a Trie.
2207 # We could do a faster match using a Trie.
2208
2208
2209 # Using pygtrie the following seem to work:
2209 # Using pygtrie the following seem to work:
2210
2210
2211 # s = PrefixSet()
2211 # s = PrefixSet()
2212
2212
2213 # for c in range(0,0x10FFFF + 1):
2213 # for c in range(0,0x10FFFF + 1):
2214 # try:
2214 # try:
2215 # s.add(unicodedata.name(chr(c)))
2215 # s.add(unicodedata.name(chr(c)))
2216 # except ValueError:
2216 # except ValueError:
2217 # pass
2217 # pass
2218 # [''.join(k) for k in s.iter(prefix)]
2218 # [''.join(k) for k in s.iter(prefix)]
2219
2219
2220 # But need to be timed and adds an extra dependency.
2220 # But need to be timed and adds an extra dependency.
2221
2221
2222 slashpos = text.rfind('\\')
2222 slashpos = text.rfind('\\')
2223 # if text starts with slash
2223 # if text starts with slash
2224 if slashpos > -1:
2224 if slashpos > -1:
2225 # PERF: It's important that we don't access self._unicode_names
2225 # PERF: It's important that we don't access self._unicode_names
2226 # until we're inside this if-block. _unicode_names is lazily
2226 # until we're inside this if-block. _unicode_names is lazily
2227 # initialized, and it takes a user-noticeable amount of time to
2227 # initialized, and it takes a user-noticeable amount of time to
2228 # initialize it, so we don't want to initialize it unless we're
2228 # initialize it, so we don't want to initialize it unless we're
2229 # actually going to use it.
2229 # actually going to use it.
2230 s = text[slashpos+1:]
2230 s = text[slashpos+1:]
2231 candidates = [x for x in self.unicode_names if x.startswith(s)]
2231 candidates = [x for x in self.unicode_names if x.startswith(s)]
2232 if candidates:
2232 if candidates:
2233 return s, candidates
2233 return s, candidates
2234 else:
2234 else:
2235 return '', ()
2235 return '', ()
2236
2236
2237 # if text does not start with slash
2237 # if text does not start with slash
2238 else:
2238 else:
2239 return '', ()
2239 return '', ()
2240
2240
2241 @property
2241 @property
2242 def unicode_names(self) -> List[str]:
2242 def unicode_names(self) -> List[str]:
2243 """List of names of unicode code points that can be completed.
2243 """List of names of unicode code points that can be completed.
2244
2244
2245 The list is lazily initialized on first access.
2245 The list is lazily initialized on first access.
2246 """
2246 """
2247 if self._unicode_names is None:
2247 if self._unicode_names is None:
2248 names = []
2248 names = []
2249 for c in range(0,0x10FFFF + 1):
2249 for c in range(0,0x10FFFF + 1):
2250 try:
2250 try:
2251 names.append(unicodedata.name(chr(c)))
2251 names.append(unicodedata.name(chr(c)))
2252 except ValueError:
2252 except ValueError:
2253 pass
2253 pass
2254 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2254 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2255
2255
2256 return self._unicode_names
2256 return self._unicode_names
2257
2257
2258 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2258 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2259 names = []
2259 names = []
2260 for start,stop in ranges:
2260 for start,stop in ranges:
2261 for c in range(start, stop) :
2261 for c in range(start, stop) :
2262 try:
2262 try:
2263 names.append(unicodedata.name(chr(c)))
2263 names.append(unicodedata.name(chr(c)))
2264 except ValueError:
2264 except ValueError:
2265 pass
2265 pass
2266 return names
2266 return names
@@ -1,187 +1,187 b''
1 """Implementation of configuration-related magic functions.
1 """Implementation of configuration-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import re
16 import re
17
17
18 # Our own packages
18 # Our own packages
19 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
20 from IPython.core.magic import Magics, magics_class, line_magic
20 from IPython.core.magic import Magics, magics_class, line_magic
21 from logging import error
21 from logging import error
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Magic implementation classes
24 # Magic implementation classes
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 reg = re.compile(r'^\w+\.\w+$')
27 reg = re.compile(r'^\w+\.\w+$')
28 @magics_class
28 @magics_class
29 class ConfigMagics(Magics):
29 class ConfigMagics(Magics):
30
30
31 def __init__(self, shell):
31 def __init__(self, shell):
32 super(ConfigMagics, self).__init__(shell)
32 super(ConfigMagics, self).__init__(shell)
33 self.configurables = []
33 self.configurables = []
34
34
35 @line_magic
35 @line_magic
36 def config(self, s):
36 def config(self, s):
37 """configure IPython
37 """configure IPython
38
38
39 %config Class[.trait=value]
39 %config Class[.trait=value]
40
40
41 This magic exposes most of the IPython config system. Any
41 This magic exposes most of the IPython config system. Any
42 Configurable class should be able to be configured with the simple
42 Configurable class should be able to be configured with the simple
43 line::
43 line::
44
44
45 %config Class.trait=value
45 %config Class.trait=value
46
46
47 Where `value` will be resolved in the user's namespace, if it is an
47 Where `value` will be resolved in the user's namespace, if it is an
48 expression or variable name.
48 expression or variable name.
49
49
50 Examples
50 Examples
51 --------
51 --------
52
52
53 To see what classes are available for config, pass no arguments::
53 To see what classes are available for config, pass no arguments::
54
54
55 In [1]: %config
55 In [1]: %config
56 Available objects for config:
56 Available objects for config:
57 AliasManager
57 AliasManager
58 DisplayFormatter
58 DisplayFormatter
59 HistoryManager
59 HistoryManager
60 IPCompleter
60 IPCompleter
61 LoggingMagics
61 LoggingMagics
62 MagicsManager
62 MagicsManager
63 OSMagics
63 OSMagics
64 PrefilterManager
64 PrefilterManager
65 ScriptMagics
65 ScriptMagics
66 TerminalInteractiveShell
66 TerminalInteractiveShell
67
67
68 To view what is configurable on a given class, just pass the class
68 To view what is configurable on a given class, just pass the class
69 name::
69 name::
70
70
71 In [2]: %config IPCompleter
71 In [2]: %config IPCompleter
72 IPCompleter(Completer) options
72 IPCompleter(Completer) options
73 ----------------------------
73 ----------------------------
74 IPCompleter.backslash_combining_completions=<Bool>
74 IPCompleter.backslash_combining_completions=<Bool>
75 Enable unicode completions, e.g. \\alpha<tab> . Includes completion of latex
75 Enable unicode completions, e.g. \\alpha<tab> . Includes completion of latex
76 commands, unicode names, and expanding unicode characters back to latex
76 commands, unicode names, and expanding unicode characters back to latex
77 commands.
77 commands.
78 Current: True
78 Current: True
79 IPCompleter.debug=<Bool>
79 IPCompleter.debug=<Bool>
80 Enable debug for the Completer. Mostly print extra information for
80 Enable debug for the Completer. Mostly print extra information for
81 experimental jedi integration.
81 experimental jedi integration.
82 Current: False
82 Current: False
83 IPCompleter.greedy=<Bool>
83 IPCompleter.greedy=<Bool>
84 Activate greedy completion
84 Activate greedy completion
85 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
85 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
86 This will enable completion on elements of lists, results of function calls, etc.,
86 This will enable completion on elements of lists, results of function calls, etc.,
87 but can be unsafe because the code is actually evaluated on TAB.
87 but can be unsafe because the code is actually evaluated on TAB.
88 Current: False
88 Current: False
89 IPCompleter.jedi_compute_type_timeout=<Int>
89 IPCompleter.jedi_compute_type_timeout=<Int>
90 Experimental: restrict time (in milliseconds) during which Jedi can compute types.
90 Experimental: restrict time (in milliseconds) during which Jedi can compute types.
91 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
91 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
92 performance by preventing jedi to build its cache.
92 performance by preventing jedi to build its cache.
93 Current: 400
93 Current: 400
94 IPCompleter.limit_to__all__=<Bool>
94 IPCompleter.limit_to__all__=<Bool>
95 DEPRECATED as of version 5.0.
95 DEPRECATED as of version 5.0.
96 Instruct the completer to use __all__ for the completion
96 Instruct the completer to use __all__ for the completion
97 Specifically, when completing on ``object.<tab>``.
97 Specifically, when completing on ``object.<tab>``.
98 When True: only those names in obj.__all__ will be included.
98 When True: only those names in obj.__all__ will be included.
99 When False [default]: the __all__ attribute is ignored
99 When False [default]: the __all__ attribute is ignored
100 Current: False
100 Current: False
101 IPCompleter.merge_completions=<Bool>
101 IPCompleter.merge_completions=<Bool>
102 Whether to merge completion results into a single list
102 Whether to merge completion results into a single list
103 If False, only the completion results from the first non-empty
103 If False, only the completion results from the first non-empty
104 completer will be returned.
104 completer will be returned.
105 Current: True
105 Current: True
106 IPCompleter.omit__names=<Enum>
106 IPCompleter.omit__names=<Enum>
107 Instruct the completer to omit private method names
107 Instruct the completer to omit private method names
108 Specifically, when completing on ``object.<tab>``.
108 Specifically, when completing on ``object.<tab>``.
109 When 2 [default]: all names that start with '_' will be excluded.
109 When 2 [default]: all names that start with '_' will be excluded.
110 When 1: all 'magic' names (``__foo__``) will be excluded.
110 When 1: all 'magic' names (``__foo__``) will be excluded.
111 When 0: nothing will be excluded.
111 When 0: nothing will be excluded.
112 Choices: any of [0, 1, 2]
112 Choices: any of [0, 1, 2]
113 Current: 2
113 Current: 2
114 IPCompleter.profile_completions=<Bool>
114 IPCompleter.profile_completions=<Bool>
115 If True, emit profiling data for completion subsystem using cProfile.
115 If True, emit profiling data for completion subsystem using cProfile.
116 Current: False
116 Current: False
117 IPCompleter.profiler_output_dir=<Unicode>
117 IPCompleter.profiler_output_dir=<Unicode>
118 Template for path at which to output profile data for completions.
118 Template for path at which to output profile data for completions.
119 Current: '.completion_profiles'
119 Current: '.completion_profiles'
120 IPCompleter.use_jedi=<Bool>
120 IPCompleter.use_jedi=<Bool>
121 Experimental: Use Jedi to generate autocompletions. Default to True if jedi
121 Experimental: Use Jedi to generate autocompletions. Default to True if jedi
122 is installed.
122 is installed.
123 Current: True
123 Current: True
124
124
125 but the real use is in setting values::
125 but the real use is in setting values::
126
126
127 In [3]: %config IPCompleter.greedy = True
127 In [3]: %config IPCompleter.greedy = True
128
128
129 and these values are read from the user_ns if they are variables::
129 and these values are read from the user_ns if they are variables::
130
130
131 In [4]: feeling_greedy=False
131 In [4]: feeling_greedy=False
132
132
133 In [5]: %config IPCompleter.greedy = feeling_greedy
133 In [5]: %config IPCompleter.greedy = feeling_greedy
134
134
135 """
135 """
136 from traitlets.config.loader import Config
136 from traitlets.config.loader import Config
137 # some IPython objects are Configurable, but do not yet have
137 # some IPython objects are Configurable, but do not yet have
138 # any configurable traits. Exclude them from the effects of
138 # any configurable traits. Exclude them from the effects of
139 # this magic, as their presence is just noise:
139 # this magic, as their presence is just noise:
140 configurables = sorted(set([ c for c in self.shell.configurables
140 configurables = sorted(set([ c for c in self.shell.configurables
141 if c.__class__.class_traits(config=True)
141 if c.__class__.class_traits(config=True)
142 ]), key=lambda x: x.__class__.__name__)
142 ]), key=lambda x: x.__class__.__name__)
143 classnames = [ c.__class__.__name__ for c in configurables ]
143 classnames = [ c.__class__.__name__ for c in configurables ]
144
144
145 line = s.strip()
145 line = s.strip()
146 if not line:
146 if not line:
147 # print available configurable names
147 # print available configurable names
148 print("Available objects for config:")
148 print("Available objects for config:")
149 for name in classnames:
149 for name in classnames:
150 print(" ", name)
150 print(" ", name)
151 return
151 return
152 elif line in classnames:
152 elif line in classnames:
153 # `%config TerminalInteractiveShell` will print trait info for
153 # `%config TerminalInteractiveShell` will print trait info for
154 # TerminalInteractiveShell
154 # TerminalInteractiveShell
155 c = configurables[classnames.index(line)]
155 c = configurables[classnames.index(line)]
156 cls = c.__class__
156 cls = c.__class__
157 help = cls.class_get_help(c)
157 help = cls.class_get_help(c)
158 # strip leading '--' from cl-args:
158 # strip leading '--' from cl-args:
159 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
159 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
160 print(help)
160 print(help)
161 return
161 return
162 elif reg.match(line):
162 elif reg.match(line):
163 cls, attr = line.split('.')
163 cls, attr = line.split('.')
164 return getattr(configurables[classnames.index(cls)],attr)
164 return getattr(configurables[classnames.index(cls)],attr)
165 elif '=' not in line:
165 elif '=' not in line:
166 msg = "Invalid config statement: %r, "\
166 msg = "Invalid config statement: %r, "\
167 "should be `Class.trait = value`."
167 "should be `Class.trait = value`."
168
168
169 ll = line.lower()
169 ll = line.lower()
170 for classname in classnames:
170 for classname in classnames:
171 if ll == classname.lower():
171 if ll == classname.lower():
172 msg = msg + '\nDid you mean %s (note the case)?' % classname
172 msg = msg + '\nDid you mean %s (note the case)?' % classname
173 break
173 break
174
174
175 raise UsageError( msg % line)
175 raise UsageError( msg % line)
176
176
177 # otherwise, assume we are setting configurables.
177 # otherwise, assume we are setting configurables.
178 # leave quotes on args when splitting, because we want
178 # leave quotes on args when splitting, because we want
179 # unquoted args to eval in user_ns
179 # unquoted args to eval in user_ns
180 cfg = Config()
180 cfg = Config()
181 exec("cfg."+line, self.shell.user_ns, locals())
181 exec("cfg."+line, self.shell.user_ns, locals())
182
182
183 for configurable in configurables:
183 for configurable in configurables:
184 try:
184 try:
185 configurable.update_config(cfg)
185 configurable.update_config(cfg)
186 except Exception as e:
186 except Exception as e:
187 error(e)
187 error(e)
@@ -1,698 +1,691 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2
2
3 import asyncio
3 import asyncio
4 import os
4 import os
5 import sys
5 import sys
6 import warnings
6 import warnings
7 from warnings import warn
7 from warnings import warn
8
8
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
10 from IPython.utils import io
10 from IPython.utils import io
11 from IPython.utils.py3compat import input
11 from IPython.utils.py3compat import input
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title, restore_term_title
13 from IPython.utils.process import abbrev_cwd
13 from IPython.utils.process import abbrev_cwd
14 from traitlets import (
14 from traitlets import (
15 Bool,
15 Bool,
16 Unicode,
16 Unicode,
17 Dict,
17 Dict,
18 Integer,
18 Integer,
19 observe,
19 observe,
20 Instance,
20 Instance,
21 Type,
21 Type,
22 default,
22 default,
23 Enum,
23 Enum,
24 Union,
24 Union,
25 Any,
25 Any,
26 validate,
26 validate,
27 Float,
27 Float,
28 )
28 )
29
29
30 from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
30 from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
31 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
31 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
32 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
32 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
33 from prompt_toolkit.formatted_text import PygmentsTokens
33 from prompt_toolkit.formatted_text import PygmentsTokens
34 from prompt_toolkit.history import InMemoryHistory
34 from prompt_toolkit.history import InMemoryHistory
35 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
35 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
36 from prompt_toolkit.output import ColorDepth
36 from prompt_toolkit.output import ColorDepth
37 from prompt_toolkit.patch_stdout import patch_stdout
37 from prompt_toolkit.patch_stdout import patch_stdout
38 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
38 from prompt_toolkit.shortcuts import PromptSession, CompleteStyle, print_formatted_text
39 from prompt_toolkit.styles import DynamicStyle, merge_styles
39 from prompt_toolkit.styles import DynamicStyle, merge_styles
40 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
40 from prompt_toolkit.styles.pygments import style_from_pygments_cls, style_from_pygments_dict
41 from prompt_toolkit import __version__ as ptk_version
41 from prompt_toolkit import __version__ as ptk_version
42
42
43 from pygments.styles import get_style_by_name
43 from pygments.styles import get_style_by_name
44 from pygments.style import Style
44 from pygments.style import Style
45 from pygments.token import Token
45 from pygments.token import Token
46
46
47 from .debugger import TerminalPdb, Pdb
47 from .debugger import TerminalPdb, Pdb
48 from .magics import TerminalMagics
48 from .magics import TerminalMagics
49 from .pt_inputhooks import get_inputhook_name_and_func
49 from .pt_inputhooks import get_inputhook_name_and_func
50 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
50 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
51 from .ptutils import IPythonPTCompleter, IPythonPTLexer
51 from .ptutils import IPythonPTCompleter, IPythonPTLexer
52 from .shortcuts import create_ipython_shortcuts
52 from .shortcuts import create_ipython_shortcuts
53
53
54 DISPLAY_BANNER_DEPRECATED = object()
55 PTK3 = ptk_version.startswith('3.')
54 PTK3 = ptk_version.startswith('3.')
56
55
57
56
58 class _NoStyle(Style): pass
57 class _NoStyle(Style): pass
59
58
60
59
61
60
62 _style_overrides_light_bg = {
61 _style_overrides_light_bg = {
63 Token.Prompt: '#ansibrightblue',
62 Token.Prompt: '#ansibrightblue',
64 Token.PromptNum: '#ansiblue bold',
63 Token.PromptNum: '#ansiblue bold',
65 Token.OutPrompt: '#ansibrightred',
64 Token.OutPrompt: '#ansibrightred',
66 Token.OutPromptNum: '#ansired bold',
65 Token.OutPromptNum: '#ansired bold',
67 }
66 }
68
67
69 _style_overrides_linux = {
68 _style_overrides_linux = {
70 Token.Prompt: '#ansibrightgreen',
69 Token.Prompt: '#ansibrightgreen',
71 Token.PromptNum: '#ansigreen bold',
70 Token.PromptNum: '#ansigreen bold',
72 Token.OutPrompt: '#ansibrightred',
71 Token.OutPrompt: '#ansibrightred',
73 Token.OutPromptNum: '#ansired bold',
72 Token.OutPromptNum: '#ansired bold',
74 }
73 }
75
74
76 def get_default_editor():
75 def get_default_editor():
77 try:
76 try:
78 return os.environ['EDITOR']
77 return os.environ['EDITOR']
79 except KeyError:
78 except KeyError:
80 pass
79 pass
81 except UnicodeError:
80 except UnicodeError:
82 warn("$EDITOR environment variable is not pure ASCII. Using platform "
81 warn("$EDITOR environment variable is not pure ASCII. Using platform "
83 "default editor.")
82 "default editor.")
84
83
85 if os.name == 'posix':
84 if os.name == 'posix':
86 return 'vi' # the only one guaranteed to be there!
85 return 'vi' # the only one guaranteed to be there!
87 else:
86 else:
88 return 'notepad' # same in Windows!
87 return 'notepad' # same in Windows!
89
88
90 # conservatively check for tty
89 # conservatively check for tty
91 # overridden streams can result in things like:
90 # overridden streams can result in things like:
92 # - sys.stdin = None
91 # - sys.stdin = None
93 # - no isatty method
92 # - no isatty method
94 for _name in ('stdin', 'stdout', 'stderr'):
93 for _name in ('stdin', 'stdout', 'stderr'):
95 _stream = getattr(sys, _name)
94 _stream = getattr(sys, _name)
96 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
95 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
97 _is_tty = False
96 _is_tty = False
98 break
97 break
99 else:
98 else:
100 _is_tty = True
99 _is_tty = True
101
100
102
101
103 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
102 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
104
103
105 def black_reformat_handler(text_before_cursor):
104 def black_reformat_handler(text_before_cursor):
106 import black
105 import black
107 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
106 formatted_text = black.format_str(text_before_cursor, mode=black.FileMode())
108 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
107 if not text_before_cursor.endswith('\n') and formatted_text.endswith('\n'):
109 formatted_text = formatted_text[:-1]
108 formatted_text = formatted_text[:-1]
110 return formatted_text
109 return formatted_text
111
110
112
111
113 class TerminalInteractiveShell(InteractiveShell):
112 class TerminalInteractiveShell(InteractiveShell):
114 mime_renderers = Dict().tag(config=True)
113 mime_renderers = Dict().tag(config=True)
115
114
116 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
115 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
117 'to reserve for the tab completion menu, '
116 'to reserve for the tab completion menu, '
118 'search history, ...etc, the height of '
117 'search history, ...etc, the height of '
119 'these menus will at most this value. '
118 'these menus will at most this value. '
120 'Increase it is you prefer long and skinny '
119 'Increase it is you prefer long and skinny '
121 'menus, decrease for short and wide.'
120 'menus, decrease for short and wide.'
122 ).tag(config=True)
121 ).tag(config=True)
123
122
124 pt_app = None
123 pt_app = None
125 debugger_history = None
124 debugger_history = None
126
125
127 debugger_history_file = Unicode(
126 debugger_history_file = Unicode(
128 "~/.pdbhistory", help="File in which to store and read history"
127 "~/.pdbhistory", help="File in which to store and read history"
129 ).tag(config=True)
128 ).tag(config=True)
130
129
131 simple_prompt = Bool(_use_simple_prompt,
130 simple_prompt = Bool(_use_simple_prompt,
132 help="""Use `raw_input` for the REPL, without completion and prompt colors.
131 help="""Use `raw_input` for the REPL, without completion and prompt colors.
133
132
134 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
133 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
135 IPython own testing machinery, and emacs inferior-shell integration through elpy.
134 IPython own testing machinery, and emacs inferior-shell integration through elpy.
136
135
137 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
136 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
138 environment variable is set, or the current terminal is not a tty."""
137 environment variable is set, or the current terminal is not a tty."""
139 ).tag(config=True)
138 ).tag(config=True)
140
139
141 @property
140 @property
142 def debugger_cls(self):
141 def debugger_cls(self):
143 return Pdb if self.simple_prompt else TerminalPdb
142 return Pdb if self.simple_prompt else TerminalPdb
144
143
145 confirm_exit = Bool(True,
144 confirm_exit = Bool(True,
146 help="""
145 help="""
147 Set to confirm when you try to exit IPython with an EOF (Control-D
146 Set to confirm when you try to exit IPython with an EOF (Control-D
148 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
147 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
149 you can force a direct exit without any confirmation.""",
148 you can force a direct exit without any confirmation.""",
150 ).tag(config=True)
149 ).tag(config=True)
151
150
152 editing_mode = Unicode('emacs',
151 editing_mode = Unicode('emacs',
153 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
152 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
154 ).tag(config=True)
153 ).tag(config=True)
155
154
156 emacs_bindings_in_vi_insert_mode = Bool(
155 emacs_bindings_in_vi_insert_mode = Bool(
157 True,
156 True,
158 help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.",
157 help="Add shortcuts from 'emacs' insert mode to 'vi' insert mode.",
159 ).tag(config=True)
158 ).tag(config=True)
160
159
161 modal_cursor = Bool(
160 modal_cursor = Bool(
162 True,
161 True,
163 help="""
162 help="""
164 Cursor shape changes depending on vi mode: beam in vi insert mode,
163 Cursor shape changes depending on vi mode: beam in vi insert mode,
165 block in nav mode, underscore in replace mode.""",
164 block in nav mode, underscore in replace mode.""",
166 ).tag(config=True)
165 ).tag(config=True)
167
166
168 ttimeoutlen = Float(
167 ttimeoutlen = Float(
169 0.01,
168 0.01,
170 help="""The time in milliseconds that is waited for a key code
169 help="""The time in milliseconds that is waited for a key code
171 to complete.""",
170 to complete.""",
172 ).tag(config=True)
171 ).tag(config=True)
173
172
174 timeoutlen = Float(
173 timeoutlen = Float(
175 0.5,
174 0.5,
176 help="""The time in milliseconds that is waited for a mapped key
175 help="""The time in milliseconds that is waited for a mapped key
177 sequence to complete.""",
176 sequence to complete.""",
178 ).tag(config=True)
177 ).tag(config=True)
179
178
180 autoformatter = Unicode(None,
179 autoformatter = Unicode(None,
181 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
180 help="Autoformatter to reformat Terminal code. Can be `'black'` or `None`",
182 allow_none=True
181 allow_none=True
183 ).tag(config=True)
182 ).tag(config=True)
184
183
185 mouse_support = Bool(False,
184 mouse_support = Bool(False,
186 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
185 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
187 ).tag(config=True)
186 ).tag(config=True)
188
187
189 # We don't load the list of styles for the help string, because loading
188 # We don't load the list of styles for the help string, because loading
190 # Pygments plugins takes time and can cause unexpected errors.
189 # Pygments plugins takes time and can cause unexpected errors.
191 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
190 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
192 help="""The name or class of a Pygments style to use for syntax
191 help="""The name or class of a Pygments style to use for syntax
193 highlighting. To see available styles, run `pygmentize -L styles`."""
192 highlighting. To see available styles, run `pygmentize -L styles`."""
194 ).tag(config=True)
193 ).tag(config=True)
195
194
196 @validate('editing_mode')
195 @validate('editing_mode')
197 def _validate_editing_mode(self, proposal):
196 def _validate_editing_mode(self, proposal):
198 if proposal['value'].lower() == 'vim':
197 if proposal['value'].lower() == 'vim':
199 proposal['value']= 'vi'
198 proposal['value']= 'vi'
200 elif proposal['value'].lower() == 'default':
199 elif proposal['value'].lower() == 'default':
201 proposal['value']= 'emacs'
200 proposal['value']= 'emacs'
202
201
203 if hasattr(EditingMode, proposal['value'].upper()):
202 if hasattr(EditingMode, proposal['value'].upper()):
204 return proposal['value'].lower()
203 return proposal['value'].lower()
205
204
206 return self.editing_mode
205 return self.editing_mode
207
206
208
207
209 @observe('editing_mode')
208 @observe('editing_mode')
210 def _editing_mode(self, change):
209 def _editing_mode(self, change):
211 if self.pt_app:
210 if self.pt_app:
212 self.pt_app.editing_mode = getattr(EditingMode, change.new.upper())
211 self.pt_app.editing_mode = getattr(EditingMode, change.new.upper())
213
212
214 @observe('autoformatter')
213 @observe('autoformatter')
215 def _autoformatter_changed(self, change):
214 def _autoformatter_changed(self, change):
216 formatter = change.new
215 formatter = change.new
217 if formatter is None:
216 if formatter is None:
218 self.reformat_handler = lambda x:x
217 self.reformat_handler = lambda x:x
219 elif formatter == 'black':
218 elif formatter == 'black':
220 self.reformat_handler = black_reformat_handler
219 self.reformat_handler = black_reformat_handler
221 else:
220 else:
222 raise ValueError
221 raise ValueError
223
222
224 @observe('highlighting_style')
223 @observe('highlighting_style')
225 @observe('colors')
224 @observe('colors')
226 def _highlighting_style_changed(self, change):
225 def _highlighting_style_changed(self, change):
227 self.refresh_style()
226 self.refresh_style()
228
227
229 def refresh_style(self):
228 def refresh_style(self):
230 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
229 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
231
230
232
231
233 highlighting_style_overrides = Dict(
232 highlighting_style_overrides = Dict(
234 help="Override highlighting format for specific tokens"
233 help="Override highlighting format for specific tokens"
235 ).tag(config=True)
234 ).tag(config=True)
236
235
237 true_color = Bool(False,
236 true_color = Bool(False,
238 help="""Use 24bit colors instead of 256 colors in prompt highlighting.
237 help="""Use 24bit colors instead of 256 colors in prompt highlighting.
239 If your terminal supports true color, the following command should
238 If your terminal supports true color, the following command should
240 print ``TRUECOLOR`` in orange::
239 print ``TRUECOLOR`` in orange::
241
240
242 printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"
241 printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"
243 """,
242 """,
244 ).tag(config=True)
243 ).tag(config=True)
245
244
246 editor = Unicode(get_default_editor(),
245 editor = Unicode(get_default_editor(),
247 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
246 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
248 ).tag(config=True)
247 ).tag(config=True)
249
248
250 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
249 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
251
250
252 prompts = Instance(Prompts)
251 prompts = Instance(Prompts)
253
252
254 @default('prompts')
253 @default('prompts')
255 def _prompts_default(self):
254 def _prompts_default(self):
256 return self.prompts_class(self)
255 return self.prompts_class(self)
257
256
258 # @observe('prompts')
257 # @observe('prompts')
259 # def _(self, change):
258 # def _(self, change):
260 # self._update_layout()
259 # self._update_layout()
261
260
262 @default('displayhook_class')
261 @default('displayhook_class')
263 def _displayhook_class_default(self):
262 def _displayhook_class_default(self):
264 return RichPromptDisplayHook
263 return RichPromptDisplayHook
265
264
266 term_title = Bool(True,
265 term_title = Bool(True,
267 help="Automatically set the terminal title"
266 help="Automatically set the terminal title"
268 ).tag(config=True)
267 ).tag(config=True)
269
268
270 term_title_format = Unicode("IPython: {cwd}",
269 term_title_format = Unicode("IPython: {cwd}",
271 help="Customize the terminal title format. This is a python format string. " +
270 help="Customize the terminal title format. This is a python format string. " +
272 "Available substitutions are: {cwd}."
271 "Available substitutions are: {cwd}."
273 ).tag(config=True)
272 ).tag(config=True)
274
273
275 display_completions = Enum(('column', 'multicolumn','readlinelike'),
274 display_completions = Enum(('column', 'multicolumn','readlinelike'),
276 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
275 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
277 "'readlinelike'. These options are for `prompt_toolkit`, see "
276 "'readlinelike'. These options are for `prompt_toolkit`, see "
278 "`prompt_toolkit` documentation for more information."
277 "`prompt_toolkit` documentation for more information."
279 ),
278 ),
280 default_value='multicolumn').tag(config=True)
279 default_value='multicolumn').tag(config=True)
281
280
282 highlight_matching_brackets = Bool(True,
281 highlight_matching_brackets = Bool(True,
283 help="Highlight matching brackets.",
282 help="Highlight matching brackets.",
284 ).tag(config=True)
283 ).tag(config=True)
285
284
286 extra_open_editor_shortcuts = Bool(False,
285 extra_open_editor_shortcuts = Bool(False,
287 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
286 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
288 "This is in addition to the F2 binding, which is always enabled."
287 "This is in addition to the F2 binding, which is always enabled."
289 ).tag(config=True)
288 ).tag(config=True)
290
289
291 handle_return = Any(None,
290 handle_return = Any(None,
292 help="Provide an alternative handler to be called when the user presses "
291 help="Provide an alternative handler to be called when the user presses "
293 "Return. This is an advanced option intended for debugging, which "
292 "Return. This is an advanced option intended for debugging, which "
294 "may be changed or removed in later releases."
293 "may be changed or removed in later releases."
295 ).tag(config=True)
294 ).tag(config=True)
296
295
297 enable_history_search = Bool(True,
296 enable_history_search = Bool(True,
298 help="Allows to enable/disable the prompt toolkit history search"
297 help="Allows to enable/disable the prompt toolkit history search"
299 ).tag(config=True)
298 ).tag(config=True)
300
299
301 prompt_includes_vi_mode = Bool(True,
300 prompt_includes_vi_mode = Bool(True,
302 help="Display the current vi mode (when using vi editing mode)."
301 help="Display the current vi mode (when using vi editing mode)."
303 ).tag(config=True)
302 ).tag(config=True)
304
303
305 @observe('term_title')
304 @observe('term_title')
306 def init_term_title(self, change=None):
305 def init_term_title(self, change=None):
307 # Enable or disable the terminal title.
306 # Enable or disable the terminal title.
308 if self.term_title:
307 if self.term_title:
309 toggle_set_term_title(True)
308 toggle_set_term_title(True)
310 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
309 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
311 else:
310 else:
312 toggle_set_term_title(False)
311 toggle_set_term_title(False)
313
312
314 def restore_term_title(self):
313 def restore_term_title(self):
315 if self.term_title:
314 if self.term_title:
316 restore_term_title()
315 restore_term_title()
317
316
318 def init_display_formatter(self):
317 def init_display_formatter(self):
319 super(TerminalInteractiveShell, self).init_display_formatter()
318 super(TerminalInteractiveShell, self).init_display_formatter()
320 # terminal only supports plain text
319 # terminal only supports plain text
321 self.display_formatter.active_types = ['text/plain']
320 self.display_formatter.active_types = ['text/plain']
322 # disable `_ipython_display_`
321 # disable `_ipython_display_`
323 self.display_formatter.ipython_display_formatter.enabled = False
322 self.display_formatter.ipython_display_formatter.enabled = False
324
323
325 def init_prompt_toolkit_cli(self):
324 def init_prompt_toolkit_cli(self):
326 if self.simple_prompt:
325 if self.simple_prompt:
327 # Fall back to plain non-interactive output for tests.
326 # Fall back to plain non-interactive output for tests.
328 # This is very limited.
327 # This is very limited.
329 def prompt():
328 def prompt():
330 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
329 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
331 lines = [input(prompt_text)]
330 lines = [input(prompt_text)]
332 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
331 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
333 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
332 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
334 lines.append( input(prompt_continuation) )
333 lines.append( input(prompt_continuation) )
335 return '\n'.join(lines)
334 return '\n'.join(lines)
336 self.prompt_for_code = prompt
335 self.prompt_for_code = prompt
337 return
336 return
338
337
339 # Set up keyboard shortcuts
338 # Set up keyboard shortcuts
340 key_bindings = create_ipython_shortcuts(self)
339 key_bindings = create_ipython_shortcuts(self)
341
340
342 # Pre-populate history from IPython's history database
341 # Pre-populate history from IPython's history database
343 history = InMemoryHistory()
342 history = InMemoryHistory()
344 last_cell = u""
343 last_cell = u""
345 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
344 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
346 include_latest=True):
345 include_latest=True):
347 # Ignore blank lines and consecutive duplicates
346 # Ignore blank lines and consecutive duplicates
348 cell = cell.rstrip()
347 cell = cell.rstrip()
349 if cell and (cell != last_cell):
348 if cell and (cell != last_cell):
350 history.append_string(cell)
349 history.append_string(cell)
351 last_cell = cell
350 last_cell = cell
352
351
353 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
352 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
354 self.style = DynamicStyle(lambda: self._style)
353 self.style = DynamicStyle(lambda: self._style)
355
354
356 editing_mode = getattr(EditingMode, self.editing_mode.upper())
355 editing_mode = getattr(EditingMode, self.editing_mode.upper())
357
356
358 self.pt_loop = asyncio.new_event_loop()
357 self.pt_loop = asyncio.new_event_loop()
359 self.pt_app = PromptSession(
358 self.pt_app = PromptSession(
360 auto_suggest=AutoSuggestFromHistory(),
359 auto_suggest=AutoSuggestFromHistory(),
361 editing_mode=editing_mode,
360 editing_mode=editing_mode,
362 key_bindings=key_bindings,
361 key_bindings=key_bindings,
363 history=history,
362 history=history,
364 completer=IPythonPTCompleter(shell=self),
363 completer=IPythonPTCompleter(shell=self),
365 enable_history_search=self.enable_history_search,
364 enable_history_search=self.enable_history_search,
366 style=self.style,
365 style=self.style,
367 include_default_pygments_style=False,
366 include_default_pygments_style=False,
368 mouse_support=self.mouse_support,
367 mouse_support=self.mouse_support,
369 enable_open_in_editor=self.extra_open_editor_shortcuts,
368 enable_open_in_editor=self.extra_open_editor_shortcuts,
370 color_depth=self.color_depth,
369 color_depth=self.color_depth,
371 tempfile_suffix=".py",
370 tempfile_suffix=".py",
372 **self._extra_prompt_options()
371 **self._extra_prompt_options()
373 )
372 )
374
373
375 def _make_style_from_name_or_cls(self, name_or_cls):
374 def _make_style_from_name_or_cls(self, name_or_cls):
376 """
375 """
377 Small wrapper that make an IPython compatible style from a style name
376 Small wrapper that make an IPython compatible style from a style name
378
377
379 We need that to add style for prompt ... etc.
378 We need that to add style for prompt ... etc.
380 """
379 """
381 style_overrides = {}
380 style_overrides = {}
382 if name_or_cls == 'legacy':
381 if name_or_cls == 'legacy':
383 legacy = self.colors.lower()
382 legacy = self.colors.lower()
384 if legacy == 'linux':
383 if legacy == 'linux':
385 style_cls = get_style_by_name('monokai')
384 style_cls = get_style_by_name('monokai')
386 style_overrides = _style_overrides_linux
385 style_overrides = _style_overrides_linux
387 elif legacy == 'lightbg':
386 elif legacy == 'lightbg':
388 style_overrides = _style_overrides_light_bg
387 style_overrides = _style_overrides_light_bg
389 style_cls = get_style_by_name('pastie')
388 style_cls = get_style_by_name('pastie')
390 elif legacy == 'neutral':
389 elif legacy == 'neutral':
391 # The default theme needs to be visible on both a dark background
390 # The default theme needs to be visible on both a dark background
392 # and a light background, because we can't tell what the terminal
391 # and a light background, because we can't tell what the terminal
393 # looks like. These tweaks to the default theme help with that.
392 # looks like. These tweaks to the default theme help with that.
394 style_cls = get_style_by_name('default')
393 style_cls = get_style_by_name('default')
395 style_overrides.update({
394 style_overrides.update({
396 Token.Number: '#ansigreen',
395 Token.Number: '#ansigreen',
397 Token.Operator: 'noinherit',
396 Token.Operator: 'noinherit',
398 Token.String: '#ansiyellow',
397 Token.String: '#ansiyellow',
399 Token.Name.Function: '#ansiblue',
398 Token.Name.Function: '#ansiblue',
400 Token.Name.Class: 'bold #ansiblue',
399 Token.Name.Class: 'bold #ansiblue',
401 Token.Name.Namespace: 'bold #ansiblue',
400 Token.Name.Namespace: 'bold #ansiblue',
402 Token.Name.Variable.Magic: '#ansiblue',
401 Token.Name.Variable.Magic: '#ansiblue',
403 Token.Prompt: '#ansigreen',
402 Token.Prompt: '#ansigreen',
404 Token.PromptNum: '#ansibrightgreen bold',
403 Token.PromptNum: '#ansibrightgreen bold',
405 Token.OutPrompt: '#ansired',
404 Token.OutPrompt: '#ansired',
406 Token.OutPromptNum: '#ansibrightred bold',
405 Token.OutPromptNum: '#ansibrightred bold',
407 })
406 })
408
407
409 # Hack: Due to limited color support on the Windows console
408 # Hack: Due to limited color support on the Windows console
410 # the prompt colors will be wrong without this
409 # the prompt colors will be wrong without this
411 if os.name == 'nt':
410 if os.name == 'nt':
412 style_overrides.update({
411 style_overrides.update({
413 Token.Prompt: '#ansidarkgreen',
412 Token.Prompt: '#ansidarkgreen',
414 Token.PromptNum: '#ansigreen bold',
413 Token.PromptNum: '#ansigreen bold',
415 Token.OutPrompt: '#ansidarkred',
414 Token.OutPrompt: '#ansidarkred',
416 Token.OutPromptNum: '#ansired bold',
415 Token.OutPromptNum: '#ansired bold',
417 })
416 })
418 elif legacy =='nocolor':
417 elif legacy =='nocolor':
419 style_cls=_NoStyle
418 style_cls=_NoStyle
420 style_overrides = {}
419 style_overrides = {}
421 else :
420 else :
422 raise ValueError('Got unknown colors: ', legacy)
421 raise ValueError('Got unknown colors: ', legacy)
423 else :
422 else :
424 if isinstance(name_or_cls, str):
423 if isinstance(name_or_cls, str):
425 style_cls = get_style_by_name(name_or_cls)
424 style_cls = get_style_by_name(name_or_cls)
426 else:
425 else:
427 style_cls = name_or_cls
426 style_cls = name_or_cls
428 style_overrides = {
427 style_overrides = {
429 Token.Prompt: '#ansigreen',
428 Token.Prompt: '#ansigreen',
430 Token.PromptNum: '#ansibrightgreen bold',
429 Token.PromptNum: '#ansibrightgreen bold',
431 Token.OutPrompt: '#ansired',
430 Token.OutPrompt: '#ansired',
432 Token.OutPromptNum: '#ansibrightred bold',
431 Token.OutPromptNum: '#ansibrightred bold',
433 }
432 }
434 style_overrides.update(self.highlighting_style_overrides)
433 style_overrides.update(self.highlighting_style_overrides)
435 style = merge_styles([
434 style = merge_styles([
436 style_from_pygments_cls(style_cls),
435 style_from_pygments_cls(style_cls),
437 style_from_pygments_dict(style_overrides),
436 style_from_pygments_dict(style_overrides),
438 ])
437 ])
439
438
440 return style
439 return style
441
440
442 @property
441 @property
443 def pt_complete_style(self):
442 def pt_complete_style(self):
444 return {
443 return {
445 'multicolumn': CompleteStyle.MULTI_COLUMN,
444 'multicolumn': CompleteStyle.MULTI_COLUMN,
446 'column': CompleteStyle.COLUMN,
445 'column': CompleteStyle.COLUMN,
447 'readlinelike': CompleteStyle.READLINE_LIKE,
446 'readlinelike': CompleteStyle.READLINE_LIKE,
448 }[self.display_completions]
447 }[self.display_completions]
449
448
450 @property
449 @property
451 def color_depth(self):
450 def color_depth(self):
452 return (ColorDepth.TRUE_COLOR if self.true_color else None)
451 return (ColorDepth.TRUE_COLOR if self.true_color else None)
453
452
454 def _extra_prompt_options(self):
453 def _extra_prompt_options(self):
455 """
454 """
456 Return the current layout option for the current Terminal InteractiveShell
455 Return the current layout option for the current Terminal InteractiveShell
457 """
456 """
458 def get_message():
457 def get_message():
459 return PygmentsTokens(self.prompts.in_prompt_tokens())
458 return PygmentsTokens(self.prompts.in_prompt_tokens())
460
459
461 if self.editing_mode == 'emacs':
460 if self.editing_mode == 'emacs':
462 # with emacs mode the prompt is (usually) static, so we call only
461 # with emacs mode the prompt is (usually) static, so we call only
463 # the function once. With VI mode it can toggle between [ins] and
462 # the function once. With VI mode it can toggle between [ins] and
464 # [nor] so we can't precompute.
463 # [nor] so we can't precompute.
465 # here I'm going to favor the default keybinding which almost
464 # here I'm going to favor the default keybinding which almost
466 # everybody uses to decrease CPU usage.
465 # everybody uses to decrease CPU usage.
467 # if we have issues with users with custom Prompts we can see how to
466 # if we have issues with users with custom Prompts we can see how to
468 # work around this.
467 # work around this.
469 get_message = get_message()
468 get_message = get_message()
470
469
471 options = {
470 options = {
472 'complete_in_thread': False,
471 'complete_in_thread': False,
473 'lexer':IPythonPTLexer(),
472 'lexer':IPythonPTLexer(),
474 'reserve_space_for_menu':self.space_for_menu,
473 'reserve_space_for_menu':self.space_for_menu,
475 'message': get_message,
474 'message': get_message,
476 'prompt_continuation': (
475 'prompt_continuation': (
477 lambda width, lineno, is_soft_wrap:
476 lambda width, lineno, is_soft_wrap:
478 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
477 PygmentsTokens(self.prompts.continuation_prompt_tokens(width))),
479 'multiline': True,
478 'multiline': True,
480 'complete_style': self.pt_complete_style,
479 'complete_style': self.pt_complete_style,
481
480
482 # Highlight matching brackets, but only when this setting is
481 # Highlight matching brackets, but only when this setting is
483 # enabled, and only when the DEFAULT_BUFFER has the focus.
482 # enabled, and only when the DEFAULT_BUFFER has the focus.
484 'input_processors': [ConditionalProcessor(
483 'input_processors': [ConditionalProcessor(
485 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
484 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
486 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
485 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
487 Condition(lambda: self.highlight_matching_brackets))],
486 Condition(lambda: self.highlight_matching_brackets))],
488 }
487 }
489 if not PTK3:
488 if not PTK3:
490 options['inputhook'] = self.inputhook
489 options['inputhook'] = self.inputhook
491
490
492 return options
491 return options
493
492
494 def prompt_for_code(self):
493 def prompt_for_code(self):
495 if self.rl_next_input:
494 if self.rl_next_input:
496 default = self.rl_next_input
495 default = self.rl_next_input
497 self.rl_next_input = None
496 self.rl_next_input = None
498 else:
497 else:
499 default = ''
498 default = ''
500
499
501 # In order to make sure that asyncio code written in the
500 # In order to make sure that asyncio code written in the
502 # interactive shell doesn't interfere with the prompt, we run the
501 # interactive shell doesn't interfere with the prompt, we run the
503 # prompt in a different event loop.
502 # prompt in a different event loop.
504 # If we don't do this, people could spawn coroutine with a
503 # If we don't do this, people could spawn coroutine with a
505 # while/true inside which will freeze the prompt.
504 # while/true inside which will freeze the prompt.
506
505
507 policy = asyncio.get_event_loop_policy()
506 policy = asyncio.get_event_loop_policy()
508 try:
507 try:
509 old_loop = policy.get_event_loop()
508 old_loop = policy.get_event_loop()
510 except RuntimeError:
509 except RuntimeError:
511 # This happens when the the event loop is closed,
510 # This happens when the the event loop is closed,
512 # e.g. by calling `asyncio.run()`.
511 # e.g. by calling `asyncio.run()`.
513 old_loop = None
512 old_loop = None
514
513
515 policy.set_event_loop(self.pt_loop)
514 policy.set_event_loop(self.pt_loop)
516 try:
515 try:
517 with patch_stdout(raw=True):
516 with patch_stdout(raw=True):
518 text = self.pt_app.prompt(
517 text = self.pt_app.prompt(
519 default=default,
518 default=default,
520 **self._extra_prompt_options())
519 **self._extra_prompt_options())
521 finally:
520 finally:
522 # Restore the original event loop.
521 # Restore the original event loop.
523 if old_loop is not None:
522 if old_loop is not None:
524 policy.set_event_loop(old_loop)
523 policy.set_event_loop(old_loop)
525
524
526 return text
525 return text
527
526
528 def enable_win_unicode_console(self):
527 def enable_win_unicode_console(self):
529 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
528 # Since IPython 7.10 doesn't support python < 3.6 and PEP 528, Python uses the unicode APIs for the Windows
530 # console by default, so WUC shouldn't be needed.
529 # console by default, so WUC shouldn't be needed.
531 from warnings import warn
530 from warnings import warn
532 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
531 warn("`enable_win_unicode_console` is deprecated since IPython 7.10, does not do anything and will be removed in the future",
533 DeprecationWarning,
532 DeprecationWarning,
534 stacklevel=2)
533 stacklevel=2)
535
534
536 def init_io(self):
535 def init_io(self):
537 if sys.platform not in {'win32', 'cli'}:
536 if sys.platform not in {'win32', 'cli'}:
538 return
537 return
539
538
540 import colorama
539 import colorama
541 colorama.init()
540 colorama.init()
542
541
543 # For some reason we make these wrappers around stdout/stderr.
542 # For some reason we make these wrappers around stdout/stderr.
544 # For now, we need to reset them so all output gets coloured.
543 # For now, we need to reset them so all output gets coloured.
545 # https://github.com/ipython/ipython/issues/8669
544 # https://github.com/ipython/ipython/issues/8669
546 # io.std* are deprecated, but don't show our own deprecation warnings
545 # io.std* are deprecated, but don't show our own deprecation warnings
547 # during initialization of the deprecated API.
546 # during initialization of the deprecated API.
548 with warnings.catch_warnings():
547 with warnings.catch_warnings():
549 warnings.simplefilter('ignore', DeprecationWarning)
548 warnings.simplefilter('ignore', DeprecationWarning)
550 io.stdout = io.IOStream(sys.stdout)
549 io.stdout = io.IOStream(sys.stdout)
551 io.stderr = io.IOStream(sys.stderr)
550 io.stderr = io.IOStream(sys.stderr)
552
551
553 def init_magics(self):
552 def init_magics(self):
554 super(TerminalInteractiveShell, self).init_magics()
553 super(TerminalInteractiveShell, self).init_magics()
555 self.register_magics(TerminalMagics)
554 self.register_magics(TerminalMagics)
556
555
557 def init_alias(self):
556 def init_alias(self):
558 # The parent class defines aliases that can be safely used with any
557 # The parent class defines aliases that can be safely used with any
559 # frontend.
558 # frontend.
560 super(TerminalInteractiveShell, self).init_alias()
559 super(TerminalInteractiveShell, self).init_alias()
561
560
562 # Now define aliases that only make sense on the terminal, because they
561 # Now define aliases that only make sense on the terminal, because they
563 # need direct access to the console in a way that we can't emulate in
562 # need direct access to the console in a way that we can't emulate in
564 # GUI or web frontend
563 # GUI or web frontend
565 if os.name == 'posix':
564 if os.name == 'posix':
566 for cmd in ('clear', 'more', 'less', 'man'):
565 for cmd in ('clear', 'more', 'less', 'man'):
567 self.alias_manager.soft_define_alias(cmd, cmd)
566 self.alias_manager.soft_define_alias(cmd, cmd)
568
567
569
568
570 def __init__(self, *args, **kwargs):
569 def __init__(self, *args, **kwargs):
571 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
570 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
572 self.init_prompt_toolkit_cli()
571 self.init_prompt_toolkit_cli()
573 self.init_term_title()
572 self.init_term_title()
574 self.keep_running = True
573 self.keep_running = True
575
574
576
575
577 def ask_exit(self):
576 def ask_exit(self):
578 self.keep_running = False
577 self.keep_running = False
579
578
580 rl_next_input = None
579 rl_next_input = None
581
580
582 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
581 def interact(self):
583
584 if display_banner is not DISPLAY_BANNER_DEPRECATED:
585 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
586
587 self.keep_running = True
582 self.keep_running = True
588 while self.keep_running:
583 while self.keep_running:
589 print(self.separate_in, end='')
584 print(self.separate_in, end='')
590
585
591 try:
586 try:
592 code = self.prompt_for_code()
587 code = self.prompt_for_code()
593 except EOFError:
588 except EOFError:
594 if (not self.confirm_exit) \
589 if (not self.confirm_exit) \
595 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
590 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
596 self.ask_exit()
591 self.ask_exit()
597
592
598 else:
593 else:
599 if code:
594 if code:
600 self.run_cell(code, store_history=True)
595 self.run_cell(code, store_history=True)
601
596
602 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
597 def mainloop(self):
603 # An extra layer of protection in case someone mashing Ctrl-C breaks
598 # An extra layer of protection in case someone mashing Ctrl-C breaks
604 # out of our internal code.
599 # out of our internal code.
605 if display_banner is not DISPLAY_BANNER_DEPRECATED:
606 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
607 while True:
600 while True:
608 try:
601 try:
609 self.interact()
602 self.interact()
610 break
603 break
611 except KeyboardInterrupt as e:
604 except KeyboardInterrupt as e:
612 print("\n%s escaped interact()\n" % type(e).__name__)
605 print("\n%s escaped interact()\n" % type(e).__name__)
613 finally:
606 finally:
614 # An interrupt during the eventloop will mess up the
607 # An interrupt during the eventloop will mess up the
615 # internal state of the prompt_toolkit library.
608 # internal state of the prompt_toolkit library.
616 # Stopping the eventloop fixes this, see
609 # Stopping the eventloop fixes this, see
617 # https://github.com/ipython/ipython/pull/9867
610 # https://github.com/ipython/ipython/pull/9867
618 if hasattr(self, '_eventloop'):
611 if hasattr(self, '_eventloop'):
619 self._eventloop.stop()
612 self._eventloop.stop()
620
613
621 self.restore_term_title()
614 self.restore_term_title()
622
615
623 # try to call some at-exit operation optimistically as some things can't
616 # try to call some at-exit operation optimistically as some things can't
624 # be done during interpreter shutdown. this is technically inaccurate as
617 # be done during interpreter shutdown. this is technically inaccurate as
625 # this make mainlool not re-callable, but that should be a rare if not
618 # this make mainlool not re-callable, but that should be a rare if not
626 # in existent use case.
619 # in existent use case.
627
620
628 self._atexit_once()
621 self._atexit_once()
629
622
630
623
631 _inputhook = None
624 _inputhook = None
632 def inputhook(self, context):
625 def inputhook(self, context):
633 if self._inputhook is not None:
626 if self._inputhook is not None:
634 self._inputhook(context)
627 self._inputhook(context)
635
628
636 active_eventloop = None
629 active_eventloop = None
637 def enable_gui(self, gui=None):
630 def enable_gui(self, gui=None):
638 if gui and (gui != 'inline') :
631 if gui and (gui != 'inline') :
639 self.active_eventloop, self._inputhook =\
632 self.active_eventloop, self._inputhook =\
640 get_inputhook_name_and_func(gui)
633 get_inputhook_name_and_func(gui)
641 else:
634 else:
642 self.active_eventloop = self._inputhook = None
635 self.active_eventloop = self._inputhook = None
643
636
644 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
637 # For prompt_toolkit 3.0. We have to create an asyncio event loop with
645 # this inputhook.
638 # this inputhook.
646 if PTK3:
639 if PTK3:
647 import asyncio
640 import asyncio
648 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
641 from prompt_toolkit.eventloop import new_eventloop_with_inputhook
649
642
650 if gui == 'asyncio':
643 if gui == 'asyncio':
651 # When we integrate the asyncio event loop, run the UI in the
644 # When we integrate the asyncio event loop, run the UI in the
652 # same event loop as the rest of the code. don't use an actual
645 # same event loop as the rest of the code. don't use an actual
653 # input hook. (Asyncio is not made for nesting event loops.)
646 # input hook. (Asyncio is not made for nesting event loops.)
654 self.pt_loop = asyncio.get_event_loop_policy().get_event_loop()
647 self.pt_loop = asyncio.get_event_loop_policy().get_event_loop()
655
648
656 elif self._inputhook:
649 elif self._inputhook:
657 # If an inputhook was set, create a new asyncio event loop with
650 # If an inputhook was set, create a new asyncio event loop with
658 # this inputhook for the prompt.
651 # this inputhook for the prompt.
659 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
652 self.pt_loop = new_eventloop_with_inputhook(self._inputhook)
660 else:
653 else:
661 # When there's no inputhook, run the prompt in a separate
654 # When there's no inputhook, run the prompt in a separate
662 # asyncio event loop.
655 # asyncio event loop.
663 self.pt_loop = asyncio.new_event_loop()
656 self.pt_loop = asyncio.new_event_loop()
664
657
665 # Run !system commands directly, not through pipes, so terminal programs
658 # Run !system commands directly, not through pipes, so terminal programs
666 # work correctly.
659 # work correctly.
667 system = InteractiveShell.system_raw
660 system = InteractiveShell.system_raw
668
661
669 def auto_rewrite_input(self, cmd):
662 def auto_rewrite_input(self, cmd):
670 """Overridden from the parent class to use fancy rewriting prompt"""
663 """Overridden from the parent class to use fancy rewriting prompt"""
671 if not self.show_rewritten_input:
664 if not self.show_rewritten_input:
672 return
665 return
673
666
674 tokens = self.prompts.rewrite_prompt_tokens()
667 tokens = self.prompts.rewrite_prompt_tokens()
675 if self.pt_app:
668 if self.pt_app:
676 print_formatted_text(PygmentsTokens(tokens), end='',
669 print_formatted_text(PygmentsTokens(tokens), end='',
677 style=self.pt_app.app.style)
670 style=self.pt_app.app.style)
678 print(cmd)
671 print(cmd)
679 else:
672 else:
680 prompt = ''.join(s for t, s in tokens)
673 prompt = ''.join(s for t, s in tokens)
681 print(prompt, cmd, sep='')
674 print(prompt, cmd, sep='')
682
675
683 _prompts_before = None
676 _prompts_before = None
684 def switch_doctest_mode(self, mode):
677 def switch_doctest_mode(self, mode):
685 """Switch prompts to classic for %doctest_mode"""
678 """Switch prompts to classic for %doctest_mode"""
686 if mode:
679 if mode:
687 self._prompts_before = self.prompts
680 self._prompts_before = self.prompts
688 self.prompts = ClassicPrompts(self)
681 self.prompts = ClassicPrompts(self)
689 elif self._prompts_before:
682 elif self._prompts_before:
690 self.prompts = self._prompts_before
683 self.prompts = self._prompts_before
691 self._prompts_before = None
684 self._prompts_before = None
692 # self._update_layout()
685 # self._update_layout()
693
686
694
687
695 InteractiveShellABC.register(TerminalInteractiveShell)
688 InteractiveShellABC.register(TerminalInteractiveShell)
696
689
697 if __name__ == '__main__':
690 if __name__ == '__main__':
698 TerminalInteractiveShell.instance().interact()
691 TerminalInteractiveShell.instance().interact()
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now