##// END OF EJS Templates
Merge pull request #13600 from Carreau/cell-id-II...
Matthias Bussonnier -
r27618:4d73f5c6 merge
parent child Browse files
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,2272 +1,2272 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 ProvisionalCompleterWarning(FutureWarning):
181 class ProvisionalCompleterWarning(FutureWarning):
182 """
182 """
183 Exception raise by an experimental feature in this module.
183 Exception raise by an experimental feature in this module.
184
184
185 Wrap code in :any:`provisionalcompleter` context manager if you
185 Wrap code in :any:`provisionalcompleter` context manager if you
186 are certain you want to use an unstable feature.
186 are certain you want to use an unstable feature.
187 """
187 """
188 pass
188 pass
189
189
190 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
190 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
191
191
192
192
193 @skip_doctest
193 @skip_doctest
194 @contextmanager
194 @contextmanager
195 def provisionalcompleter(action='ignore'):
195 def provisionalcompleter(action='ignore'):
196 """
196 """
197 This context manager has to be used in any place where unstable completer
197 This context manager has to be used in any place where unstable completer
198 behavior and API may be called.
198 behavior and API may be called.
199
199
200 >>> with provisionalcompleter():
200 >>> with provisionalcompleter():
201 ... completer.do_experimental_things() # works
201 ... completer.do_experimental_things() # works
202
202
203 >>> completer.do_experimental_things() # raises.
203 >>> completer.do_experimental_things() # raises.
204
204
205 .. note::
205 .. note::
206
206
207 Unstable
207 Unstable
208
208
209 By using this context manager you agree that the API in use may change
209 By using this context manager you agree that the API in use may change
210 without warning, and that you won't complain if they do so.
210 without warning, and that you won't complain if they do so.
211
211
212 You also understand that, if the API is not to your liking, you should report
212 You also understand that, if the API is not to your liking, you should report
213 a bug to explain your use case upstream.
213 a bug to explain your use case upstream.
214
214
215 We'll be happy to get your feedback, feature requests, and improvements on
215 We'll be happy to get your feedback, feature requests, and improvements on
216 any of the unstable APIs!
216 any of the unstable APIs!
217 """
217 """
218 with warnings.catch_warnings():
218 with warnings.catch_warnings():
219 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
219 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
220 yield
220 yield
221
221
222
222
223 def has_open_quotes(s):
223 def has_open_quotes(s):
224 """Return whether a string has open quotes.
224 """Return whether a string has open quotes.
225
225
226 This simply counts whether the number of quote characters of either type in
226 This simply counts whether the number of quote characters of either type in
227 the string is odd.
227 the string is odd.
228
228
229 Returns
229 Returns
230 -------
230 -------
231 If there is an open quote, the quote character is returned. Else, return
231 If there is an open quote, the quote character is returned. Else, return
232 False.
232 False.
233 """
233 """
234 # We check " first, then ', so complex cases with nested quotes will get
234 # We check " first, then ', so complex cases with nested quotes will get
235 # the " to take precedence.
235 # the " to take precedence.
236 if s.count('"') % 2:
236 if s.count('"') % 2:
237 return '"'
237 return '"'
238 elif s.count("'") % 2:
238 elif s.count("'") % 2:
239 return "'"
239 return "'"
240 else:
240 else:
241 return False
241 return False
242
242
243
243
244 def protect_filename(s, protectables=PROTECTABLES):
244 def protect_filename(s, protectables=PROTECTABLES):
245 """Escape a string to protect certain characters."""
245 """Escape a string to protect certain characters."""
246 if set(s) & set(protectables):
246 if set(s) & set(protectables):
247 if sys.platform == "win32":
247 if sys.platform == "win32":
248 return '"' + s + '"'
248 return '"' + s + '"'
249 else:
249 else:
250 return "".join(("\\" + c if c in protectables else c) for c in s)
250 return "".join(("\\" + c if c in protectables else c) for c in s)
251 else:
251 else:
252 return s
252 return s
253
253
254
254
255 def expand_user(path:str) -> Tuple[str, bool, str]:
255 def expand_user(path:str) -> Tuple[str, bool, str]:
256 """Expand ``~``-style usernames in strings.
256 """Expand ``~``-style usernames in strings.
257
257
258 This is similar to :func:`os.path.expanduser`, but it computes and returns
258 This is similar to :func:`os.path.expanduser`, but it computes and returns
259 extra information that will be useful if the input was being used in
259 extra information that will be useful if the input was being used in
260 computing completions, and you wish to return the completions with the
260 computing completions, and you wish to return the completions with the
261 original '~' instead of its expanded value.
261 original '~' instead of its expanded value.
262
262
263 Parameters
263 Parameters
264 ----------
264 ----------
265 path : str
265 path : str
266 String to be expanded. If no ~ is present, the output is the same as the
266 String to be expanded. If no ~ is present, the output is the same as the
267 input.
267 input.
268
268
269 Returns
269 Returns
270 -------
270 -------
271 newpath : str
271 newpath : str
272 Result of ~ expansion in the input path.
272 Result of ~ expansion in the input path.
273 tilde_expand : bool
273 tilde_expand : bool
274 Whether any expansion was performed or not.
274 Whether any expansion was performed or not.
275 tilde_val : str
275 tilde_val : str
276 The value that ~ was replaced with.
276 The value that ~ was replaced with.
277 """
277 """
278 # Default values
278 # Default values
279 tilde_expand = False
279 tilde_expand = False
280 tilde_val = ''
280 tilde_val = ''
281 newpath = path
281 newpath = path
282
282
283 if path.startswith('~'):
283 if path.startswith('~'):
284 tilde_expand = True
284 tilde_expand = True
285 rest = len(path)-1
285 rest = len(path)-1
286 newpath = os.path.expanduser(path)
286 newpath = os.path.expanduser(path)
287 if rest:
287 if rest:
288 tilde_val = newpath[:-rest]
288 tilde_val = newpath[:-rest]
289 else:
289 else:
290 tilde_val = newpath
290 tilde_val = newpath
291
291
292 return newpath, tilde_expand, tilde_val
292 return newpath, tilde_expand, tilde_val
293
293
294
294
295 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
295 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
296 """Does the opposite of expand_user, with its outputs.
296 """Does the opposite of expand_user, with its outputs.
297 """
297 """
298 if tilde_expand:
298 if tilde_expand:
299 return path.replace(tilde_val, '~')
299 return path.replace(tilde_val, '~')
300 else:
300 else:
301 return path
301 return path
302
302
303
303
304 def completions_sorting_key(word):
304 def completions_sorting_key(word):
305 """key for sorting completions
305 """key for sorting completions
306
306
307 This does several things:
307 This does several things:
308
308
309 - Demote any completions starting with underscores to the end
309 - Demote any completions starting with underscores to the end
310 - Insert any %magic and %%cellmagic completions in the alphabetical order
310 - Insert any %magic and %%cellmagic completions in the alphabetical order
311 by their name
311 by their name
312 """
312 """
313 prio1, prio2 = 0, 0
313 prio1, prio2 = 0, 0
314
314
315 if word.startswith('__'):
315 if word.startswith('__'):
316 prio1 = 2
316 prio1 = 2
317 elif word.startswith('_'):
317 elif word.startswith('_'):
318 prio1 = 1
318 prio1 = 1
319
319
320 if word.endswith('='):
320 if word.endswith('='):
321 prio1 = -1
321 prio1 = -1
322
322
323 if word.startswith('%%'):
323 if word.startswith('%%'):
324 # If there's another % in there, this is something else, so leave it alone
324 # If there's another % in there, this is something else, so leave it alone
325 if not "%" in word[2:]:
325 if not "%" in word[2:]:
326 word = word[2:]
326 word = word[2:]
327 prio2 = 2
327 prio2 = 2
328 elif word.startswith('%'):
328 elif word.startswith('%'):
329 if not "%" in word[1:]:
329 if not "%" in word[1:]:
330 word = word[1:]
330 word = word[1:]
331 prio2 = 1
331 prio2 = 1
332
332
333 return prio1, word, prio2
333 return prio1, word, prio2
334
334
335
335
336 class _FakeJediCompletion:
336 class _FakeJediCompletion:
337 """
337 """
338 This is a workaround to communicate to the UI that Jedi has crashed and to
338 This is a workaround to communicate to the UI that Jedi has crashed and to
339 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
339 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
340
340
341 Added in IPython 6.0 so should likely be removed for 7.0
341 Added in IPython 6.0 so should likely be removed for 7.0
342
342
343 """
343 """
344
344
345 def __init__(self, name):
345 def __init__(self, name):
346
346
347 self.name = name
347 self.name = name
348 self.complete = name
348 self.complete = name
349 self.type = 'crashed'
349 self.type = 'crashed'
350 self.name_with_symbols = name
350 self.name_with_symbols = name
351 self.signature = ''
351 self.signature = ''
352 self._origin = 'fake'
352 self._origin = 'fake'
353
353
354 def __repr__(self):
354 def __repr__(self):
355 return '<Fake completion object jedi has crashed>'
355 return '<Fake completion object jedi has crashed>'
356
356
357
357
358 class Completion:
358 class Completion:
359 """
359 """
360 Completion object used and return by IPython completers.
360 Completion object used and return by IPython completers.
361
361
362 .. warning::
362 .. warning::
363
363
364 Unstable
364 Unstable
365
365
366 This function is unstable, API may change without warning.
366 This function is unstable, API may change without warning.
367 It will also raise unless use in proper context manager.
367 It will also raise unless use in proper context manager.
368
368
369 This act as a middle ground :any:`Completion` object between the
369 This act as a middle ground :any:`Completion` object between the
370 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
370 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
371 object. While Jedi need a lot of information about evaluator and how the
371 object. While Jedi need a lot of information about evaluator and how the
372 code should be ran/inspected, PromptToolkit (and other frontend) mostly
372 code should be ran/inspected, PromptToolkit (and other frontend) mostly
373 need user facing information.
373 need user facing information.
374
374
375 - Which range should be replaced replaced by what.
375 - Which range should be replaced replaced by what.
376 - Some metadata (like completion type), or meta information to displayed to
376 - Some metadata (like completion type), or meta information to displayed to
377 the use user.
377 the use user.
378
378
379 For debugging purpose we can also store the origin of the completion (``jedi``,
379 For debugging purpose we can also store the origin of the completion (``jedi``,
380 ``IPython.python_matches``, ``IPython.magics_matches``...).
380 ``IPython.python_matches``, ``IPython.magics_matches``...).
381 """
381 """
382
382
383 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
383 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
384
384
385 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
385 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
386 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
386 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
387 "It may change without warnings. "
387 "It may change without warnings. "
388 "Use in corresponding context manager.",
388 "Use in corresponding context manager.",
389 category=ProvisionalCompleterWarning, stacklevel=2)
389 category=ProvisionalCompleterWarning, stacklevel=2)
390
390
391 self.start = start
391 self.start = start
392 self.end = end
392 self.end = end
393 self.text = text
393 self.text = text
394 self.type = type
394 self.type = type
395 self.signature = signature
395 self.signature = signature
396 self._origin = _origin
396 self._origin = _origin
397
397
398 def __repr__(self):
398 def __repr__(self):
399 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
399 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
400 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
400 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
401
401
402 def __eq__(self, other)->Bool:
402 def __eq__(self, other)->Bool:
403 """
403 """
404 Equality and hash do not hash the type (as some completer may not be
404 Equality and hash do not hash the type (as some completer may not be
405 able to infer the type), but are use to (partially) de-duplicate
405 able to infer the type), but are use to (partially) de-duplicate
406 completion.
406 completion.
407
407
408 Completely de-duplicating completion is a bit tricker that just
408 Completely de-duplicating completion is a bit tricker that just
409 comparing as it depends on surrounding text, which Completions are not
409 comparing as it depends on surrounding text, which Completions are not
410 aware of.
410 aware of.
411 """
411 """
412 return self.start == other.start and \
412 return self.start == other.start and \
413 self.end == other.end and \
413 self.end == other.end and \
414 self.text == other.text
414 self.text == other.text
415
415
416 def __hash__(self):
416 def __hash__(self):
417 return hash((self.start, self.end, self.text))
417 return hash((self.start, self.end, self.text))
418
418
419
419
420 _IC = Iterable[Completion]
420 _IC = Iterable[Completion]
421
421
422
422
423 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
423 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
424 """
424 """
425 Deduplicate a set of completions.
425 Deduplicate a set of completions.
426
426
427 .. warning::
427 .. warning::
428
428
429 Unstable
429 Unstable
430
430
431 This function is unstable, API may change without warning.
431 This function is unstable, API may change without warning.
432
432
433 Parameters
433 Parameters
434 ----------
434 ----------
435 text : str
435 text : str
436 text that should be completed.
436 text that should be completed.
437 completions : Iterator[Completion]
437 completions : Iterator[Completion]
438 iterator over the completions to deduplicate
438 iterator over the completions to deduplicate
439
439
440 Yields
440 Yields
441 ------
441 ------
442 `Completions` objects
442 `Completions` objects
443 Completions coming from multiple sources, may be different but end up having
443 Completions coming from multiple sources, may be different but end up having
444 the same effect when applied to ``text``. If this is the case, this will
444 the same effect when applied to ``text``. If this is the case, this will
445 consider completions as equal and only emit the first encountered.
445 consider completions as equal and only emit the first encountered.
446 Not folded in `completions()` yet for debugging purpose, and to detect when
446 Not folded in `completions()` yet for debugging purpose, and to detect when
447 the IPython completer does return things that Jedi does not, but should be
447 the IPython completer does return things that Jedi does not, but should be
448 at some point.
448 at some point.
449 """
449 """
450 completions = list(completions)
450 completions = list(completions)
451 if not completions:
451 if not completions:
452 return
452 return
453
453
454 new_start = min(c.start for c in completions)
454 new_start = min(c.start for c in completions)
455 new_end = max(c.end for c in completions)
455 new_end = max(c.end for c in completions)
456
456
457 seen = set()
457 seen = set()
458 for c in completions:
458 for c in completions:
459 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
459 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
460 if new_text not in seen:
460 if new_text not in seen:
461 yield c
461 yield c
462 seen.add(new_text)
462 seen.add(new_text)
463
463
464
464
465 def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
465 def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
466 """
466 """
467 Rectify a set of completions to all have the same ``start`` and ``end``
467 Rectify a set of completions to all have the same ``start`` and ``end``
468
468
469 .. warning::
469 .. warning::
470
470
471 Unstable
471 Unstable
472
472
473 This function is unstable, API may change without warning.
473 This function is unstable, API may change without warning.
474 It will also raise unless use in proper context manager.
474 It will also raise unless use in proper context manager.
475
475
476 Parameters
476 Parameters
477 ----------
477 ----------
478 text : str
478 text : str
479 text that should be completed.
479 text that should be completed.
480 completions : Iterator[Completion]
480 completions : Iterator[Completion]
481 iterator over the completions to rectify
481 iterator over the completions to rectify
482 _debug : bool
482 _debug : bool
483 Log failed completion
483 Log failed completion
484
484
485 Notes
485 Notes
486 -----
486 -----
487 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
487 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
488 the Jupyter Protocol requires them to behave like so. This will readjust
488 the Jupyter Protocol requires them to behave like so. This will readjust
489 the completion to have the same ``start`` and ``end`` by padding both
489 the completion to have the same ``start`` and ``end`` by padding both
490 extremities with surrounding text.
490 extremities with surrounding text.
491
491
492 During stabilisation should support a ``_debug`` option to log which
492 During stabilisation should support a ``_debug`` option to log which
493 completion are return by the IPython completer and not found in Jedi in
493 completion are return by the IPython completer and not found in Jedi in
494 order to make upstream bug report.
494 order to make upstream bug report.
495 """
495 """
496 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
496 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
497 "It may change without warnings. "
497 "It may change without warnings. "
498 "Use in corresponding context manager.",
498 "Use in corresponding context manager.",
499 category=ProvisionalCompleterWarning, stacklevel=2)
499 category=ProvisionalCompleterWarning, stacklevel=2)
500
500
501 completions = list(completions)
501 completions = list(completions)
502 if not completions:
502 if not completions:
503 return
503 return
504 starts = (c.start for c in completions)
504 starts = (c.start for c in completions)
505 ends = (c.end for c in completions)
505 ends = (c.end for c in completions)
506
506
507 new_start = min(starts)
507 new_start = min(starts)
508 new_end = max(ends)
508 new_end = max(ends)
509
509
510 seen_jedi = set()
510 seen_jedi = set()
511 seen_python_matches = set()
511 seen_python_matches = set()
512 for c in completions:
512 for c in completions:
513 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
513 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
514 if c._origin == 'jedi':
514 if c._origin == 'jedi':
515 seen_jedi.add(new_text)
515 seen_jedi.add(new_text)
516 elif c._origin == 'IPCompleter.python_matches':
516 elif c._origin == 'IPCompleter.python_matches':
517 seen_python_matches.add(new_text)
517 seen_python_matches.add(new_text)
518 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
518 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
519 diff = seen_python_matches.difference(seen_jedi)
519 diff = seen_python_matches.difference(seen_jedi)
520 if diff and _debug:
520 if diff and _debug:
521 print('IPython.python matches have extras:', diff)
521 print('IPython.python matches have extras:', diff)
522
522
523
523
524 if sys.platform == 'win32':
524 if sys.platform == 'win32':
525 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
525 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
526 else:
526 else:
527 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
527 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
528
528
529 GREEDY_DELIMS = ' =\r\n'
529 GREEDY_DELIMS = ' =\r\n'
530
530
531
531
532 class CompletionSplitter(object):
532 class CompletionSplitter(object):
533 """An object to split an input line in a manner similar to readline.
533 """An object to split an input line in a manner similar to readline.
534
534
535 By having our own implementation, we can expose readline-like completion in
535 By having our own implementation, we can expose readline-like completion in
536 a uniform manner to all frontends. This object only needs to be given the
536 a uniform manner to all frontends. This object only needs to be given the
537 line of text to be split and the cursor position on said line, and it
537 line of text to be split and the cursor position on said line, and it
538 returns the 'word' to be completed on at the cursor after splitting the
538 returns the 'word' to be completed on at the cursor after splitting the
539 entire line.
539 entire line.
540
540
541 What characters are used as splitting delimiters can be controlled by
541 What characters are used as splitting delimiters can be controlled by
542 setting the ``delims`` attribute (this is a property that internally
542 setting the ``delims`` attribute (this is a property that internally
543 automatically builds the necessary regular expression)"""
543 automatically builds the necessary regular expression)"""
544
544
545 # Private interface
545 # Private interface
546
546
547 # A string of delimiter characters. The default value makes sense for
547 # A string of delimiter characters. The default value makes sense for
548 # IPython's most typical usage patterns.
548 # IPython's most typical usage patterns.
549 _delims = DELIMS
549 _delims = DELIMS
550
550
551 # The expression (a normal string) to be compiled into a regular expression
551 # The expression (a normal string) to be compiled into a regular expression
552 # for actual splitting. We store it as an attribute mostly for ease of
552 # for actual splitting. We store it as an attribute mostly for ease of
553 # debugging, since this type of code can be so tricky to debug.
553 # debugging, since this type of code can be so tricky to debug.
554 _delim_expr = None
554 _delim_expr = None
555
555
556 # The regular expression that does the actual splitting
556 # The regular expression that does the actual splitting
557 _delim_re = None
557 _delim_re = None
558
558
559 def __init__(self, delims=None):
559 def __init__(self, delims=None):
560 delims = CompletionSplitter._delims if delims is None else delims
560 delims = CompletionSplitter._delims if delims is None else delims
561 self.delims = delims
561 self.delims = delims
562
562
563 @property
563 @property
564 def delims(self):
564 def delims(self):
565 """Return the string of delimiter characters."""
565 """Return the string of delimiter characters."""
566 return self._delims
566 return self._delims
567
567
568 @delims.setter
568 @delims.setter
569 def delims(self, delims):
569 def delims(self, delims):
570 """Set the delimiters for line splitting."""
570 """Set the delimiters for line splitting."""
571 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
571 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
572 self._delim_re = re.compile(expr)
572 self._delim_re = re.compile(expr)
573 self._delims = delims
573 self._delims = delims
574 self._delim_expr = expr
574 self._delim_expr = expr
575
575
576 def split_line(self, line, cursor_pos=None):
576 def split_line(self, line, cursor_pos=None):
577 """Split a line of text with a cursor at the given position.
577 """Split a line of text with a cursor at the given position.
578 """
578 """
579 l = line if cursor_pos is None else line[:cursor_pos]
579 l = line if cursor_pos is None else line[:cursor_pos]
580 return self._delim_re.split(l)[-1]
580 return self._delim_re.split(l)[-1]
581
581
582
582
583
583
584 class Completer(Configurable):
584 class Completer(Configurable):
585
585
586 greedy = Bool(False,
586 greedy = Bool(False,
587 help="""Activate greedy completion
587 help="""Activate greedy completion
588 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
588 PENDING DEPRECATION. this is now mostly taken care of with Jedi.
589
589
590 This will enable completion on elements of lists, results of function calls, etc.,
590 This will enable completion on elements of lists, results of function calls, etc.,
591 but can be unsafe because the code is actually evaluated on TAB.
591 but can be unsafe because the code is actually evaluated on TAB.
592 """
592 """
593 ).tag(config=True)
593 ).tag(config=True)
594
594
595 use_jedi = Bool(default_value=JEDI_INSTALLED,
595 use_jedi = Bool(default_value=JEDI_INSTALLED,
596 help="Experimental: Use Jedi to generate autocompletions. "
596 help="Experimental: Use Jedi to generate autocompletions. "
597 "Default to True if jedi is installed.").tag(config=True)
597 "Default to True if jedi is installed.").tag(config=True)
598
598
599 jedi_compute_type_timeout = Int(default_value=400,
599 jedi_compute_type_timeout = Int(default_value=400,
600 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
600 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
601 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
601 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
602 performance by preventing jedi to build its cache.
602 performance by preventing jedi to build its cache.
603 """).tag(config=True)
603 """).tag(config=True)
604
604
605 debug = Bool(default_value=False,
605 debug = Bool(default_value=False,
606 help='Enable debug for the Completer. Mostly print extra '
606 help='Enable debug for the Completer. Mostly print extra '
607 'information for experimental jedi integration.')\
607 'information for experimental jedi integration.')\
608 .tag(config=True)
608 .tag(config=True)
609
609
610 backslash_combining_completions = Bool(True,
610 backslash_combining_completions = Bool(True,
611 help="Enable unicode completions, e.g. \\alpha<tab> . "
611 help="Enable unicode completions, e.g. \\alpha<tab> . "
612 "Includes completion of latex commands, unicode names, and expanding "
612 "Includes completion of latex commands, unicode names, and expanding "
613 "unicode characters back to latex commands.").tag(config=True)
613 "unicode characters back to latex commands.").tag(config=True)
614
614
615 def __init__(self, namespace=None, global_namespace=None, **kwargs):
615 def __init__(self, namespace=None, global_namespace=None, **kwargs):
616 """Create a new completer for the command line.
616 """Create a new completer for the command line.
617
617
618 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
618 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
619
619
620 If unspecified, the default namespace where completions are performed
620 If unspecified, the default namespace where completions are performed
621 is __main__ (technically, __main__.__dict__). Namespaces should be
621 is __main__ (technically, __main__.__dict__). Namespaces should be
622 given as dictionaries.
622 given as dictionaries.
623
623
624 An optional second namespace can be given. This allows the completer
624 An optional second namespace can be given. This allows the completer
625 to handle cases where both the local and global scopes need to be
625 to handle cases where both the local and global scopes need to be
626 distinguished.
626 distinguished.
627 """
627 """
628
628
629 # Don't bind to namespace quite yet, but flag whether the user wants a
629 # Don't bind to namespace quite yet, but flag whether the user wants a
630 # specific namespace or to use __main__.__dict__. This will allow us
630 # specific namespace or to use __main__.__dict__. This will allow us
631 # to bind to __main__.__dict__ at completion time, not now.
631 # to bind to __main__.__dict__ at completion time, not now.
632 if namespace is None:
632 if namespace is None:
633 self.use_main_ns = True
633 self.use_main_ns = True
634 else:
634 else:
635 self.use_main_ns = False
635 self.use_main_ns = False
636 self.namespace = namespace
636 self.namespace = namespace
637
637
638 # The global namespace, if given, can be bound directly
638 # The global namespace, if given, can be bound directly
639 if global_namespace is None:
639 if global_namespace is None:
640 self.global_namespace = {}
640 self.global_namespace = {}
641 else:
641 else:
642 self.global_namespace = global_namespace
642 self.global_namespace = global_namespace
643
643
644 self.custom_matchers = []
644 self.custom_matchers = []
645
645
646 super(Completer, self).__init__(**kwargs)
646 super(Completer, self).__init__(**kwargs)
647
647
648 def complete(self, text, state):
648 def complete(self, text, state):
649 """Return the next possible completion for 'text'.
649 """Return the next possible completion for 'text'.
650
650
651 This is called successively with state == 0, 1, 2, ... until it
651 This is called successively with state == 0, 1, 2, ... until it
652 returns None. The completion should begin with 'text'.
652 returns None. The completion should begin with 'text'.
653
653
654 """
654 """
655 if self.use_main_ns:
655 if self.use_main_ns:
656 self.namespace = __main__.__dict__
656 self.namespace = __main__.__dict__
657
657
658 if state == 0:
658 if state == 0:
659 if "." in text:
659 if "." in text:
660 self.matches = self.attr_matches(text)
660 self.matches = self.attr_matches(text)
661 else:
661 else:
662 self.matches = self.global_matches(text)
662 self.matches = self.global_matches(text)
663 try:
663 try:
664 return self.matches[state]
664 return self.matches[state]
665 except IndexError:
665 except IndexError:
666 return None
666 return None
667
667
668 def global_matches(self, text):
668 def global_matches(self, text):
669 """Compute matches when text is a simple name.
669 """Compute matches when text is a simple name.
670
670
671 Return a list of all keywords, built-in functions and names currently
671 Return a list of all keywords, built-in functions and names currently
672 defined in self.namespace or self.global_namespace that match.
672 defined in self.namespace or self.global_namespace that match.
673
673
674 """
674 """
675 matches = []
675 matches = []
676 match_append = matches.append
676 match_append = matches.append
677 n = len(text)
677 n = len(text)
678 for lst in [keyword.kwlist,
678 for lst in [keyword.kwlist,
679 builtin_mod.__dict__.keys(),
679 builtin_mod.__dict__.keys(),
680 self.namespace.keys(),
680 self.namespace.keys(),
681 self.global_namespace.keys()]:
681 self.global_namespace.keys()]:
682 for word in lst:
682 for word in lst:
683 if word[:n] == text and word != "__builtins__":
683 if word[:n] == text and word != "__builtins__":
684 match_append(word)
684 match_append(word)
685
685
686 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
686 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
687 for lst in [self.namespace.keys(),
687 for lst in [self.namespace.keys(),
688 self.global_namespace.keys()]:
688 self.global_namespace.keys()]:
689 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
689 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
690 for word in lst if snake_case_re.match(word)}
690 for word in lst if snake_case_re.match(word)}
691 for word in shortened.keys():
691 for word in shortened.keys():
692 if word[:n] == text and word != "__builtins__":
692 if word[:n] == text and word != "__builtins__":
693 match_append(shortened[word])
693 match_append(shortened[word])
694 return matches
694 return matches
695
695
696 def attr_matches(self, text):
696 def attr_matches(self, text):
697 """Compute matches when text contains a dot.
697 """Compute matches when text contains a dot.
698
698
699 Assuming the text is of the form NAME.NAME....[NAME], and is
699 Assuming the text is of the form NAME.NAME....[NAME], and is
700 evaluatable in self.namespace or self.global_namespace, it will be
700 evaluatable in self.namespace or self.global_namespace, it will be
701 evaluated and its attributes (as revealed by dir()) are used as
701 evaluated and its attributes (as revealed by dir()) are used as
702 possible completions. (For class instances, class members are
702 possible completions. (For class instances, class members are
703 also considered.)
703 also considered.)
704
704
705 WARNING: this can still invoke arbitrary C code, if an object
705 WARNING: this can still invoke arbitrary C code, if an object
706 with a __getattr__ hook is evaluated.
706 with a __getattr__ hook is evaluated.
707
707
708 """
708 """
709
709
710 # Another option, seems to work great. Catches things like ''.<tab>
710 # Another option, seems to work great. Catches things like ''.<tab>
711 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
711 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
712
712
713 if m:
713 if m:
714 expr, attr = m.group(1, 3)
714 expr, attr = m.group(1, 3)
715 elif self.greedy:
715 elif self.greedy:
716 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
716 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
717 if not m2:
717 if not m2:
718 return []
718 return []
719 expr, attr = m2.group(1,2)
719 expr, attr = m2.group(1,2)
720 else:
720 else:
721 return []
721 return []
722
722
723 try:
723 try:
724 obj = eval(expr, self.namespace)
724 obj = eval(expr, self.namespace)
725 except:
725 except:
726 try:
726 try:
727 obj = eval(expr, self.global_namespace)
727 obj = eval(expr, self.global_namespace)
728 except:
728 except:
729 return []
729 return []
730
730
731 if self.limit_to__all__ and hasattr(obj, '__all__'):
731 if self.limit_to__all__ and hasattr(obj, '__all__'):
732 words = get__all__entries(obj)
732 words = get__all__entries(obj)
733 else:
733 else:
734 words = dir2(obj)
734 words = dir2(obj)
735
735
736 try:
736 try:
737 words = generics.complete_object(obj, words)
737 words = generics.complete_object(obj, words)
738 except TryNext:
738 except TryNext:
739 pass
739 pass
740 except AssertionError:
740 except AssertionError:
741 raise
741 raise
742 except Exception:
742 except Exception:
743 # Silence errors from completion function
743 # Silence errors from completion function
744 #raise # dbg
744 #raise # dbg
745 pass
745 pass
746 # Build match list to return
746 # Build match list to return
747 n = len(attr)
747 n = len(attr)
748 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
748 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
749
749
750
750
751 def get__all__entries(obj):
751 def get__all__entries(obj):
752 """returns the strings in the __all__ attribute"""
752 """returns the strings in the __all__ attribute"""
753 try:
753 try:
754 words = getattr(obj, '__all__')
754 words = getattr(obj, '__all__')
755 except:
755 except:
756 return []
756 return []
757
757
758 return [w for w in words if isinstance(w, str)]
758 return [w for w in words if isinstance(w, str)]
759
759
760
760
761 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
761 def match_dict_keys(keys: List[Union[str, bytes, Tuple[Union[str, bytes]]]], prefix: str, delims: str,
762 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
762 extra_prefix: Optional[Tuple[str, bytes]]=None) -> Tuple[str, int, List[str]]:
763 """Used by dict_key_matches, matching the prefix to a list of keys
763 """Used by dict_key_matches, matching the prefix to a list of keys
764
764
765 Parameters
765 Parameters
766 ----------
766 ----------
767 keys
767 keys
768 list of keys in dictionary currently being completed.
768 list of keys in dictionary currently being completed.
769 prefix
769 prefix
770 Part of the text already typed by the user. E.g. `mydict[b'fo`
770 Part of the text already typed by the user. E.g. `mydict[b'fo`
771 delims
771 delims
772 String of delimiters to consider when finding the current key.
772 String of delimiters to consider when finding the current key.
773 extra_prefix : optional
773 extra_prefix : optional
774 Part of the text already typed in multi-key index cases. E.g. for
774 Part of the text already typed in multi-key index cases. E.g. for
775 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
775 `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
776
776
777 Returns
777 Returns
778 -------
778 -------
779 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
779 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
780 ``quote`` being the quote that need to be used to close current string.
780 ``quote`` being the quote that need to be used to close current string.
781 ``token_start`` the position where the replacement should start occurring,
781 ``token_start`` the position where the replacement should start occurring,
782 ``matches`` a list of replacement/completion
782 ``matches`` a list of replacement/completion
783
783
784 """
784 """
785 prefix_tuple = extra_prefix if extra_prefix else ()
785 prefix_tuple = extra_prefix if extra_prefix else ()
786 Nprefix = len(prefix_tuple)
786 Nprefix = len(prefix_tuple)
787 def filter_prefix_tuple(key):
787 def filter_prefix_tuple(key):
788 # Reject too short keys
788 # Reject too short keys
789 if len(key) <= Nprefix:
789 if len(key) <= Nprefix:
790 return False
790 return False
791 # Reject keys with non str/bytes in it
791 # Reject keys with non str/bytes in it
792 for k in key:
792 for k in key:
793 if not isinstance(k, (str, bytes)):
793 if not isinstance(k, (str, bytes)):
794 return False
794 return False
795 # Reject keys that do not match the prefix
795 # Reject keys that do not match the prefix
796 for k, pt in zip(key, prefix_tuple):
796 for k, pt in zip(key, prefix_tuple):
797 if k != pt:
797 if k != pt:
798 return False
798 return False
799 # All checks passed!
799 # All checks passed!
800 return True
800 return True
801
801
802 filtered_keys:List[Union[str,bytes]] = []
802 filtered_keys:List[Union[str,bytes]] = []
803 def _add_to_filtered_keys(key):
803 def _add_to_filtered_keys(key):
804 if isinstance(key, (str, bytes)):
804 if isinstance(key, (str, bytes)):
805 filtered_keys.append(key)
805 filtered_keys.append(key)
806
806
807 for k in keys:
807 for k in keys:
808 if isinstance(k, tuple):
808 if isinstance(k, tuple):
809 if filter_prefix_tuple(k):
809 if filter_prefix_tuple(k):
810 _add_to_filtered_keys(k[Nprefix])
810 _add_to_filtered_keys(k[Nprefix])
811 else:
811 else:
812 _add_to_filtered_keys(k)
812 _add_to_filtered_keys(k)
813
813
814 if not prefix:
814 if not prefix:
815 return '', 0, [repr(k) for k in filtered_keys]
815 return '', 0, [repr(k) for k in filtered_keys]
816 quote_match = re.search('["\']', prefix)
816 quote_match = re.search('["\']', prefix)
817 assert quote_match is not None # silence mypy
817 assert quote_match is not None # silence mypy
818 quote = quote_match.group()
818 quote = quote_match.group()
819 try:
819 try:
820 prefix_str = eval(prefix + quote, {})
820 prefix_str = eval(prefix + quote, {})
821 except Exception:
821 except Exception:
822 return '', 0, []
822 return '', 0, []
823
823
824 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
824 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
825 token_match = re.search(pattern, prefix, re.UNICODE)
825 token_match = re.search(pattern, prefix, re.UNICODE)
826 assert token_match is not None # silence mypy
826 assert token_match is not None # silence mypy
827 token_start = token_match.start()
827 token_start = token_match.start()
828 token_prefix = token_match.group()
828 token_prefix = token_match.group()
829
829
830 matched:List[str] = []
830 matched:List[str] = []
831 for key in filtered_keys:
831 for key in filtered_keys:
832 try:
832 try:
833 if not key.startswith(prefix_str):
833 if not key.startswith(prefix_str):
834 continue
834 continue
835 except (AttributeError, TypeError, UnicodeError):
835 except (AttributeError, TypeError, UnicodeError):
836 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
836 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
837 continue
837 continue
838
838
839 # reformat remainder of key to begin with prefix
839 # reformat remainder of key to begin with prefix
840 rem = key[len(prefix_str):]
840 rem = key[len(prefix_str):]
841 # force repr wrapped in '
841 # force repr wrapped in '
842 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
842 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
843 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
843 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
844 if quote == '"':
844 if quote == '"':
845 # The entered prefix is quoted with ",
845 # The entered prefix is quoted with ",
846 # but the match is quoted with '.
846 # but the match is quoted with '.
847 # A contained " hence needs escaping for comparison:
847 # A contained " hence needs escaping for comparison:
848 rem_repr = rem_repr.replace('"', '\\"')
848 rem_repr = rem_repr.replace('"', '\\"')
849
849
850 # then reinsert prefix from start of token
850 # then reinsert prefix from start of token
851 matched.append('%s%s' % (token_prefix, rem_repr))
851 matched.append('%s%s' % (token_prefix, rem_repr))
852 return quote, token_start, matched
852 return quote, token_start, matched
853
853
854
854
855 def cursor_to_position(text:str, line:int, column:int)->int:
855 def cursor_to_position(text:str, line:int, column:int)->int:
856 """
856 """
857 Convert the (line,column) position of the cursor in text to an offset in a
857 Convert the (line,column) position of the cursor in text to an offset in a
858 string.
858 string.
859
859
860 Parameters
860 Parameters
861 ----------
861 ----------
862 text : str
862 text : str
863 The text in which to calculate the cursor offset
863 The text in which to calculate the cursor offset
864 line : int
864 line : int
865 Line of the cursor; 0-indexed
865 Line of the cursor; 0-indexed
866 column : int
866 column : int
867 Column of the cursor 0-indexed
867 Column of the cursor 0-indexed
868
868
869 Returns
869 Returns
870 -------
870 -------
871 Position of the cursor in ``text``, 0-indexed.
871 Position of the cursor in ``text``, 0-indexed.
872
872
873 See Also
873 See Also
874 --------
874 --------
875 position_to_cursor : reciprocal of this function
875 position_to_cursor : reciprocal of this function
876
876
877 """
877 """
878 lines = text.split('\n')
878 lines = text.split('\n')
879 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
879 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
880
880
881 return sum(len(l) + 1 for l in lines[:line]) + column
881 return sum(len(l) + 1 for l in lines[:line]) + column
882
882
883 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
883 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
884 """
884 """
885 Convert the position of the cursor in text (0 indexed) to a line
885 Convert the position of the cursor in text (0 indexed) to a line
886 number(0-indexed) and a column number (0-indexed) pair
886 number(0-indexed) and a column number (0-indexed) pair
887
887
888 Position should be a valid position in ``text``.
888 Position should be a valid position in ``text``.
889
889
890 Parameters
890 Parameters
891 ----------
891 ----------
892 text : str
892 text : str
893 The text in which to calculate the cursor offset
893 The text in which to calculate the cursor offset
894 offset : int
894 offset : int
895 Position of the cursor in ``text``, 0-indexed.
895 Position of the cursor in ``text``, 0-indexed.
896
896
897 Returns
897 Returns
898 -------
898 -------
899 (line, column) : (int, int)
899 (line, column) : (int, int)
900 Line of the cursor; 0-indexed, column of the cursor 0-indexed
900 Line of the cursor; 0-indexed, column of the cursor 0-indexed
901
901
902 See Also
902 See Also
903 --------
903 --------
904 cursor_to_position : reciprocal of this function
904 cursor_to_position : reciprocal of this function
905
905
906 """
906 """
907
907
908 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
908 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
909
909
910 before = text[:offset]
910 before = text[:offset]
911 blines = before.split('\n') # ! splitnes trim trailing \n
911 blines = before.split('\n') # ! splitnes trim trailing \n
912 line = before.count('\n')
912 line = before.count('\n')
913 col = len(blines[-1])
913 col = len(blines[-1])
914 return line, col
914 return line, col
915
915
916
916
917 def _safe_isinstance(obj, module, class_name):
917 def _safe_isinstance(obj, module, class_name):
918 """Checks if obj is an instance of module.class_name if loaded
918 """Checks if obj is an instance of module.class_name if loaded
919 """
919 """
920 return (module in sys.modules and
920 return (module in sys.modules and
921 isinstance(obj, getattr(import_module(module), class_name)))
921 isinstance(obj, getattr(import_module(module), class_name)))
922
922
923 def back_unicode_name_matches(text:str) -> Tuple[str, Sequence[str]]:
923 def back_unicode_name_matches(text:str) -> Tuple[str, Sequence[str]]:
924 """Match Unicode characters back to Unicode name
924 """Match Unicode characters back to Unicode name
925
925
926 This does ``β˜ƒ`` -> ``\\snowman``
926 This does ``β˜ƒ`` -> ``\\snowman``
927
927
928 Note that snowman is not a valid python3 combining character but will be expanded.
928 Note that snowman is not a valid python3 combining character but will be expanded.
929 Though it will not recombine back to the snowman character by the completion machinery.
929 Though it will not recombine back to the snowman character by the completion machinery.
930
930
931 This will not either back-complete standard sequences like \\n, \\b ...
931 This will not either back-complete standard sequences like \\n, \\b ...
932
932
933 Returns
933 Returns
934 =======
934 =======
935
935
936 Return a tuple with two elements:
936 Return a tuple with two elements:
937
937
938 - The Unicode character that was matched (preceded with a backslash), or
938 - The Unicode character that was matched (preceded with a backslash), or
939 empty string,
939 empty string,
940 - a sequence (of 1), name for the match Unicode character, preceded by
940 - a sequence (of 1), name for the match Unicode character, preceded by
941 backslash, or empty if no match.
941 backslash, or empty if no match.
942
942
943 """
943 """
944 if len(text)<2:
944 if len(text)<2:
945 return '', ()
945 return '', ()
946 maybe_slash = text[-2]
946 maybe_slash = text[-2]
947 if maybe_slash != '\\':
947 if maybe_slash != '\\':
948 return '', ()
948 return '', ()
949
949
950 char = text[-1]
950 char = text[-1]
951 # no expand on quote for completion in strings.
951 # no expand on quote for completion in strings.
952 # nor backcomplete standard ascii keys
952 # nor backcomplete standard ascii keys
953 if char in string.ascii_letters or char in ('"',"'"):
953 if char in string.ascii_letters or char in ('"',"'"):
954 return '', ()
954 return '', ()
955 try :
955 try :
956 unic = unicodedata.name(char)
956 unic = unicodedata.name(char)
957 return '\\'+char,('\\'+unic,)
957 return '\\'+char,('\\'+unic,)
958 except KeyError:
958 except KeyError:
959 pass
959 pass
960 return '', ()
960 return '', ()
961
961
962 def back_latex_name_matches(text:str) -> Tuple[str, Sequence[str]] :
962 def back_latex_name_matches(text:str) -> Tuple[str, Sequence[str]] :
963 """Match latex characters back to unicode name
963 """Match latex characters back to unicode name
964
964
965 This does ``\\β„΅`` -> ``\\aleph``
965 This does ``\\β„΅`` -> ``\\aleph``
966
966
967 """
967 """
968 if len(text)<2:
968 if len(text)<2:
969 return '', ()
969 return '', ()
970 maybe_slash = text[-2]
970 maybe_slash = text[-2]
971 if maybe_slash != '\\':
971 if maybe_slash != '\\':
972 return '', ()
972 return '', ()
973
973
974
974
975 char = text[-1]
975 char = text[-1]
976 # no expand on quote for completion in strings.
976 # no expand on quote for completion in strings.
977 # nor backcomplete standard ascii keys
977 # nor backcomplete standard ascii keys
978 if char in string.ascii_letters or char in ('"',"'"):
978 if char in string.ascii_letters or char in ('"',"'"):
979 return '', ()
979 return '', ()
980 try :
980 try :
981 latex = reverse_latex_symbol[char]
981 latex = reverse_latex_symbol[char]
982 # '\\' replace the \ as well
982 # '\\' replace the \ as well
983 return '\\'+char,[latex]
983 return '\\'+char,[latex]
984 except KeyError:
984 except KeyError:
985 pass
985 pass
986 return '', ()
986 return '', ()
987
987
988
988
989 def _formatparamchildren(parameter) -> str:
989 def _formatparamchildren(parameter) -> str:
990 """
990 """
991 Get parameter name and value from Jedi Private API
991 Get parameter name and value from Jedi Private API
992
992
993 Jedi does not expose a simple way to get `param=value` from its API.
993 Jedi does not expose a simple way to get `param=value` from its API.
994
994
995 Parameters
995 Parameters
996 ----------
996 ----------
997 parameter
997 parameter
998 Jedi's function `Param`
998 Jedi's function `Param`
999
999
1000 Returns
1000 Returns
1001 -------
1001 -------
1002 A string like 'a', 'b=1', '*args', '**kwargs'
1002 A string like 'a', 'b=1', '*args', '**kwargs'
1003
1003
1004 """
1004 """
1005 description = parameter.description
1005 description = parameter.description
1006 if not description.startswith('param '):
1006 if not description.startswith('param '):
1007 raise ValueError('Jedi function parameter description have change format.'
1007 raise ValueError('Jedi function parameter description have change format.'
1008 'Expected "param ...", found %r".' % description)
1008 'Expected "param ...", found %r".' % description)
1009 return description[6:]
1009 return description[6:]
1010
1010
1011 def _make_signature(completion)-> str:
1011 def _make_signature(completion)-> str:
1012 """
1012 """
1013 Make the signature from a jedi completion
1013 Make the signature from a jedi completion
1014
1014
1015 Parameters
1015 Parameters
1016 ----------
1016 ----------
1017 completion : jedi.Completion
1017 completion : jedi.Completion
1018 object does not complete a function type
1018 object does not complete a function type
1019
1019
1020 Returns
1020 Returns
1021 -------
1021 -------
1022 a string consisting of the function signature, with the parenthesis but
1022 a string consisting of the function signature, with the parenthesis but
1023 without the function name. example:
1023 without the function name. example:
1024 `(a, *args, b=1, **kwargs)`
1024 `(a, *args, b=1, **kwargs)`
1025
1025
1026 """
1026 """
1027
1027
1028 # it looks like this might work on jedi 0.17
1028 # it looks like this might work on jedi 0.17
1029 if hasattr(completion, 'get_signatures'):
1029 if hasattr(completion, 'get_signatures'):
1030 signatures = completion.get_signatures()
1030 signatures = completion.get_signatures()
1031 if not signatures:
1031 if not signatures:
1032 return '(?)'
1032 return '(?)'
1033
1033
1034 c0 = completion.get_signatures()[0]
1034 c0 = completion.get_signatures()[0]
1035 return '('+c0.to_string().split('(', maxsplit=1)[1]
1035 return '('+c0.to_string().split('(', maxsplit=1)[1]
1036
1036
1037 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1037 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1038 for p in signature.defined_names()) if f])
1038 for p in signature.defined_names()) if f])
1039
1039
1040
1040
1041 class _CompleteResult(NamedTuple):
1041 class _CompleteResult(NamedTuple):
1042 matched_text : str
1042 matched_text : str
1043 matches: Sequence[str]
1043 matches: Sequence[str]
1044 matches_origin: Sequence[str]
1044 matches_origin: Sequence[str]
1045 jedi_matches: Any
1045 jedi_matches: Any
1046
1046
1047
1047
1048 class IPCompleter(Completer):
1048 class IPCompleter(Completer):
1049 """Extension of the completer class with IPython-specific features"""
1049 """Extension of the completer class with IPython-specific features"""
1050
1050
1051 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1051 __dict_key_regexps: Optional[Dict[bool,Pattern]] = None
1052
1052
1053 @observe('greedy')
1053 @observe('greedy')
1054 def _greedy_changed(self, change):
1054 def _greedy_changed(self, change):
1055 """update the splitter and readline delims when greedy is changed"""
1055 """update the splitter and readline delims when greedy is changed"""
1056 if change['new']:
1056 if change['new']:
1057 self.splitter.delims = GREEDY_DELIMS
1057 self.splitter.delims = GREEDY_DELIMS
1058 else:
1058 else:
1059 self.splitter.delims = DELIMS
1059 self.splitter.delims = DELIMS
1060
1060
1061 dict_keys_only = Bool(False,
1061 dict_keys_only = Bool(False,
1062 help="""Whether to show dict key matches only""")
1062 help="""Whether to show dict key matches only""")
1063
1063
1064 merge_completions = Bool(True,
1064 merge_completions = Bool(True,
1065 help="""Whether to merge completion results into a single list
1065 help="""Whether to merge completion results into a single list
1066
1066
1067 If False, only the completion results from the first non-empty
1067 If False, only the completion results from the first non-empty
1068 completer will be returned.
1068 completer will be returned.
1069 """
1069 """
1070 ).tag(config=True)
1070 ).tag(config=True)
1071 omit__names = Enum((0,1,2), default_value=2,
1071 omit__names = Enum((0,1,2), default_value=2,
1072 help="""Instruct the completer to omit private method names
1072 help="""Instruct the completer to omit private method names
1073
1073
1074 Specifically, when completing on ``object.<tab>``.
1074 Specifically, when completing on ``object.<tab>``.
1075
1075
1076 When 2 [default]: all names that start with '_' will be excluded.
1076 When 2 [default]: all names that start with '_' will be excluded.
1077
1077
1078 When 1: all 'magic' names (``__foo__``) will be excluded.
1078 When 1: all 'magic' names (``__foo__``) will be excluded.
1079
1079
1080 When 0: nothing will be excluded.
1080 When 0: nothing will be excluded.
1081 """
1081 """
1082 ).tag(config=True)
1082 ).tag(config=True)
1083 limit_to__all__ = Bool(False,
1083 limit_to__all__ = Bool(False,
1084 help="""
1084 help="""
1085 DEPRECATED as of version 5.0.
1085 DEPRECATED as of version 5.0.
1086
1086
1087 Instruct the completer to use __all__ for the completion
1087 Instruct the completer to use __all__ for the completion
1088
1088
1089 Specifically, when completing on ``object.<tab>``.
1089 Specifically, when completing on ``object.<tab>``.
1090
1090
1091 When True: only those names in obj.__all__ will be included.
1091 When True: only those names in obj.__all__ will be included.
1092
1092
1093 When False [default]: the __all__ attribute is ignored
1093 When False [default]: the __all__ attribute is ignored
1094 """,
1094 """,
1095 ).tag(config=True)
1095 ).tag(config=True)
1096
1096
1097 profile_completions = Bool(
1097 profile_completions = Bool(
1098 default_value=False,
1098 default_value=False,
1099 help="If True, emit profiling data for completion subsystem using cProfile."
1099 help="If True, emit profiling data for completion subsystem using cProfile."
1100 ).tag(config=True)
1100 ).tag(config=True)
1101
1101
1102 profiler_output_dir = Unicode(
1102 profiler_output_dir = Unicode(
1103 default_value=".completion_profiles",
1103 default_value=".completion_profiles",
1104 help="Template for path at which to output profile data for completions."
1104 help="Template for path at which to output profile data for completions."
1105 ).tag(config=True)
1105 ).tag(config=True)
1106
1106
1107 @observe('limit_to__all__')
1107 @observe('limit_to__all__')
1108 def _limit_to_all_changed(self, change):
1108 def _limit_to_all_changed(self, change):
1109 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1109 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1110 'value has been deprecated since IPython 5.0, will be made to have '
1110 'value has been deprecated since IPython 5.0, will be made to have '
1111 'no effects and then removed in future version of IPython.',
1111 'no effects and then removed in future version of IPython.',
1112 UserWarning)
1112 UserWarning)
1113
1113
1114 def __init__(
1114 def __init__(
1115 self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
1115 self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
1116 ):
1116 ):
1117 """IPCompleter() -> completer
1117 """IPCompleter() -> completer
1118
1118
1119 Return a completer object.
1119 Return a completer object.
1120
1120
1121 Parameters
1121 Parameters
1122 ----------
1122 ----------
1123 shell
1123 shell
1124 a pointer to the ipython shell itself. This is needed
1124 a pointer to the ipython shell itself. This is needed
1125 because this completer knows about magic functions, and those can
1125 because this completer knows about magic functions, and those can
1126 only be accessed via the ipython instance.
1126 only be accessed via the ipython instance.
1127 namespace : dict, optional
1127 namespace : dict, optional
1128 an optional dict where completions are performed.
1128 an optional dict where completions are performed.
1129 global_namespace : dict, optional
1129 global_namespace : dict, optional
1130 secondary optional dict for completions, to
1130 secondary optional dict for completions, to
1131 handle cases (such as IPython embedded inside functions) where
1131 handle cases (such as IPython embedded inside functions) where
1132 both Python scopes are visible.
1132 both Python scopes are visible.
1133 config : Config
1133 config : Config
1134 traitlet's config object
1134 traitlet's config object
1135 **kwargs
1135 **kwargs
1136 passed to super class unmodified.
1136 passed to super class unmodified.
1137 """
1137 """
1138
1138
1139 self.magic_escape = ESC_MAGIC
1139 self.magic_escape = ESC_MAGIC
1140 self.splitter = CompletionSplitter()
1140 self.splitter = CompletionSplitter()
1141
1141
1142 # _greedy_changed() depends on splitter and readline being defined:
1142 # _greedy_changed() depends on splitter and readline being defined:
1143 super().__init__(
1143 super().__init__(
1144 namespace=namespace,
1144 namespace=namespace,
1145 global_namespace=global_namespace,
1145 global_namespace=global_namespace,
1146 config=config,
1146 config=config,
1147 **kwargs
1147 **kwargs
1148 )
1148 )
1149
1149
1150 # List where completion matches will be stored
1150 # List where completion matches will be stored
1151 self.matches = []
1151 self.matches = []
1152 self.shell = shell
1152 self.shell = shell
1153 # Regexp to split filenames with spaces in them
1153 # Regexp to split filenames with spaces in them
1154 self.space_name_re = re.compile(r'([^\\] )')
1154 self.space_name_re = re.compile(r'([^\\] )')
1155 # Hold a local ref. to glob.glob for speed
1155 # Hold a local ref. to glob.glob for speed
1156 self.glob = glob.glob
1156 self.glob = glob.glob
1157
1157
1158 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1158 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1159 # buffers, to avoid completion problems.
1159 # buffers, to avoid completion problems.
1160 term = os.environ.get('TERM','xterm')
1160 term = os.environ.get('TERM','xterm')
1161 self.dumb_terminal = term in ['dumb','emacs']
1161 self.dumb_terminal = term in ['dumb','emacs']
1162
1162
1163 # Special handling of backslashes needed in win32 platforms
1163 # Special handling of backslashes needed in win32 platforms
1164 if sys.platform == "win32":
1164 if sys.platform == "win32":
1165 self.clean_glob = self._clean_glob_win32
1165 self.clean_glob = self._clean_glob_win32
1166 else:
1166 else:
1167 self.clean_glob = self._clean_glob
1167 self.clean_glob = self._clean_glob
1168
1168
1169 #regexp to parse docstring for function signature
1169 #regexp to parse docstring for function signature
1170 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1170 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1171 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1171 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1172 #use this if positional argument name is also needed
1172 #use this if positional argument name is also needed
1173 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1173 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1174
1174
1175 self.magic_arg_matchers = [
1175 self.magic_arg_matchers = [
1176 self.magic_config_matches,
1176 self.magic_config_matches,
1177 self.magic_color_matches,
1177 self.magic_color_matches,
1178 ]
1178 ]
1179
1179
1180 # This is set externally by InteractiveShell
1180 # This is set externally by InteractiveShell
1181 self.custom_completers = None
1181 self.custom_completers = None
1182
1182
1183 # This is a list of names of unicode characters that can be completed
1183 # This is a list of names of unicode characters that can be completed
1184 # into their corresponding unicode value. The list is large, so we
1184 # into their corresponding unicode value. The list is large, so we
1185 # lazily initialize it on first use. Consuming code should access this
1185 # lazily initialize it on first use. Consuming code should access this
1186 # attribute through the `@unicode_names` property.
1186 # attribute through the `@unicode_names` property.
1187 self._unicode_names = None
1187 self._unicode_names = None
1188
1188
1189 @property
1189 @property
1190 def matchers(self) -> List[Any]:
1190 def matchers(self) -> List[Any]:
1191 """All active matcher routines for completion"""
1191 """All active matcher routines for completion"""
1192 if self.dict_keys_only:
1192 if self.dict_keys_only:
1193 return [self.dict_key_matches]
1193 return [self.dict_key_matches]
1194
1194
1195 if self.use_jedi:
1195 if self.use_jedi:
1196 return [
1196 return [
1197 *self.custom_matchers,
1197 *self.custom_matchers,
1198 self.dict_key_matches,
1198 self.dict_key_matches,
1199 self.file_matches,
1199 self.file_matches,
1200 self.magic_matches,
1200 self.magic_matches,
1201 ]
1201 ]
1202 else:
1202 else:
1203 return [
1203 return [
1204 *self.custom_matchers,
1204 *self.custom_matchers,
1205 self.dict_key_matches,
1205 self.dict_key_matches,
1206 self.python_matches,
1206 self.python_matches,
1207 self.file_matches,
1207 self.file_matches,
1208 self.magic_matches,
1208 self.magic_matches,
1209 self.python_func_kw_matches,
1209 self.python_func_kw_matches,
1210 ]
1210 ]
1211
1211
1212 def all_completions(self, text:str) -> List[str]:
1212 def all_completions(self, text:str) -> List[str]:
1213 """
1213 """
1214 Wrapper around the completion methods for the benefit of emacs.
1214 Wrapper around the completion methods for the benefit of emacs.
1215 """
1215 """
1216 prefix = text.rpartition('.')[0]
1216 prefix = text.rpartition('.')[0]
1217 with provisionalcompleter():
1217 with provisionalcompleter():
1218 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1218 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1219 for c in self.completions(text, len(text))]
1219 for c in self.completions(text, len(text))]
1220
1220
1221 return self.complete(text)[1]
1221 return self.complete(text)[1]
1222
1222
1223 def _clean_glob(self, text:str):
1223 def _clean_glob(self, text:str):
1224 return self.glob("%s*" % text)
1224 return self.glob("%s*" % text)
1225
1225
1226 def _clean_glob_win32(self, text:str):
1226 def _clean_glob_win32(self, text:str):
1227 return [f.replace("\\","/")
1227 return [f.replace("\\","/")
1228 for f in self.glob("%s*" % text)]
1228 for f in self.glob("%s*" % text)]
1229
1229
1230 def file_matches(self, text:str)->List[str]:
1230 def file_matches(self, text:str)->List[str]:
1231 """Match filenames, expanding ~USER type strings.
1231 """Match filenames, expanding ~USER type strings.
1232
1232
1233 Most of the seemingly convoluted logic in this completer is an
1233 Most of the seemingly convoluted logic in this completer is an
1234 attempt to handle filenames with spaces in them. And yet it's not
1234 attempt to handle filenames with spaces in them. And yet it's not
1235 quite perfect, because Python's readline doesn't expose all of the
1235 quite perfect, because Python's readline doesn't expose all of the
1236 GNU readline details needed for this to be done correctly.
1236 GNU readline details needed for this to be done correctly.
1237
1237
1238 For a filename with a space in it, the printed completions will be
1238 For a filename with a space in it, the printed completions will be
1239 only the parts after what's already been typed (instead of the
1239 only the parts after what's already been typed (instead of the
1240 full completions, as is normally done). I don't think with the
1240 full completions, as is normally done). I don't think with the
1241 current (as of Python 2.3) Python readline it's possible to do
1241 current (as of Python 2.3) Python readline it's possible to do
1242 better."""
1242 better."""
1243
1243
1244 # chars that require escaping with backslash - i.e. chars
1244 # chars that require escaping with backslash - i.e. chars
1245 # that readline treats incorrectly as delimiters, but we
1245 # that readline treats incorrectly as delimiters, but we
1246 # don't want to treat as delimiters in filename matching
1246 # don't want to treat as delimiters in filename matching
1247 # when escaped with backslash
1247 # when escaped with backslash
1248 if text.startswith('!'):
1248 if text.startswith('!'):
1249 text = text[1:]
1249 text = text[1:]
1250 text_prefix = u'!'
1250 text_prefix = u'!'
1251 else:
1251 else:
1252 text_prefix = u''
1252 text_prefix = u''
1253
1253
1254 text_until_cursor = self.text_until_cursor
1254 text_until_cursor = self.text_until_cursor
1255 # track strings with open quotes
1255 # track strings with open quotes
1256 open_quotes = has_open_quotes(text_until_cursor)
1256 open_quotes = has_open_quotes(text_until_cursor)
1257
1257
1258 if '(' in text_until_cursor or '[' in text_until_cursor:
1258 if '(' in text_until_cursor or '[' in text_until_cursor:
1259 lsplit = text
1259 lsplit = text
1260 else:
1260 else:
1261 try:
1261 try:
1262 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1262 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1263 lsplit = arg_split(text_until_cursor)[-1]
1263 lsplit = arg_split(text_until_cursor)[-1]
1264 except ValueError:
1264 except ValueError:
1265 # typically an unmatched ", or backslash without escaped char.
1265 # typically an unmatched ", or backslash without escaped char.
1266 if open_quotes:
1266 if open_quotes:
1267 lsplit = text_until_cursor.split(open_quotes)[-1]
1267 lsplit = text_until_cursor.split(open_quotes)[-1]
1268 else:
1268 else:
1269 return []
1269 return []
1270 except IndexError:
1270 except IndexError:
1271 # tab pressed on empty line
1271 # tab pressed on empty line
1272 lsplit = ""
1272 lsplit = ""
1273
1273
1274 if not open_quotes and lsplit != protect_filename(lsplit):
1274 if not open_quotes and lsplit != protect_filename(lsplit):
1275 # if protectables are found, do matching on the whole escaped name
1275 # if protectables are found, do matching on the whole escaped name
1276 has_protectables = True
1276 has_protectables = True
1277 text0,text = text,lsplit
1277 text0,text = text,lsplit
1278 else:
1278 else:
1279 has_protectables = False
1279 has_protectables = False
1280 text = os.path.expanduser(text)
1280 text = os.path.expanduser(text)
1281
1281
1282 if text == "":
1282 if text == "":
1283 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1283 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1284
1284
1285 # Compute the matches from the filesystem
1285 # Compute the matches from the filesystem
1286 if sys.platform == 'win32':
1286 if sys.platform == 'win32':
1287 m0 = self.clean_glob(text)
1287 m0 = self.clean_glob(text)
1288 else:
1288 else:
1289 m0 = self.clean_glob(text.replace('\\', ''))
1289 m0 = self.clean_glob(text.replace('\\', ''))
1290
1290
1291 if has_protectables:
1291 if has_protectables:
1292 # If we had protectables, we need to revert our changes to the
1292 # If we had protectables, we need to revert our changes to the
1293 # beginning of filename so that we don't double-write the part
1293 # beginning of filename so that we don't double-write the part
1294 # of the filename we have so far
1294 # of the filename we have so far
1295 len_lsplit = len(lsplit)
1295 len_lsplit = len(lsplit)
1296 matches = [text_prefix + text0 +
1296 matches = [text_prefix + text0 +
1297 protect_filename(f[len_lsplit:]) for f in m0]
1297 protect_filename(f[len_lsplit:]) for f in m0]
1298 else:
1298 else:
1299 if open_quotes:
1299 if open_quotes:
1300 # if we have a string with an open quote, we don't need to
1300 # if we have a string with an open quote, we don't need to
1301 # protect the names beyond the quote (and we _shouldn't_, as
1301 # protect the names beyond the quote (and we _shouldn't_, as
1302 # it would cause bugs when the filesystem call is made).
1302 # it would cause bugs when the filesystem call is made).
1303 matches = m0 if sys.platform == "win32" else\
1303 matches = m0 if sys.platform == "win32" else\
1304 [protect_filename(f, open_quotes) for f in m0]
1304 [protect_filename(f, open_quotes) for f in m0]
1305 else:
1305 else:
1306 matches = [text_prefix +
1306 matches = [text_prefix +
1307 protect_filename(f) for f in m0]
1307 protect_filename(f) for f in m0]
1308
1308
1309 # Mark directories in input list by appending '/' to their names.
1309 # Mark directories in input list by appending '/' to their names.
1310 return [x+'/' if os.path.isdir(x) else x for x in matches]
1310 return [x+'/' if os.path.isdir(x) else x for x in matches]
1311
1311
1312 def magic_matches(self, text:str):
1312 def magic_matches(self, text:str):
1313 """Match magics"""
1313 """Match magics"""
1314 # Get all shell magics now rather than statically, so magics loaded at
1314 # Get all shell magics now rather than statically, so magics loaded at
1315 # runtime show up too.
1315 # runtime show up too.
1316 lsm = self.shell.magics_manager.lsmagic()
1316 lsm = self.shell.magics_manager.lsmagic()
1317 line_magics = lsm['line']
1317 line_magics = lsm['line']
1318 cell_magics = lsm['cell']
1318 cell_magics = lsm['cell']
1319 pre = self.magic_escape
1319 pre = self.magic_escape
1320 pre2 = pre+pre
1320 pre2 = pre+pre
1321
1321
1322 explicit_magic = text.startswith(pre)
1322 explicit_magic = text.startswith(pre)
1323
1323
1324 # Completion logic:
1324 # Completion logic:
1325 # - user gives %%: only do cell magics
1325 # - user gives %%: only do cell magics
1326 # - user gives %: do both line and cell magics
1326 # - user gives %: do both line and cell magics
1327 # - no prefix: do both
1327 # - no prefix: do both
1328 # In other words, line magics are skipped if the user gives %% explicitly
1328 # In other words, line magics are skipped if the user gives %% explicitly
1329 #
1329 #
1330 # We also exclude magics that match any currently visible names:
1330 # We also exclude magics that match any currently visible names:
1331 # https://github.com/ipython/ipython/issues/4877, unless the user has
1331 # https://github.com/ipython/ipython/issues/4877, unless the user has
1332 # typed a %:
1332 # typed a %:
1333 # https://github.com/ipython/ipython/issues/10754
1333 # https://github.com/ipython/ipython/issues/10754
1334 bare_text = text.lstrip(pre)
1334 bare_text = text.lstrip(pre)
1335 global_matches = self.global_matches(bare_text)
1335 global_matches = self.global_matches(bare_text)
1336 if not explicit_magic:
1336 if not explicit_magic:
1337 def matches(magic):
1337 def matches(magic):
1338 """
1338 """
1339 Filter magics, in particular remove magics that match
1339 Filter magics, in particular remove magics that match
1340 a name present in global namespace.
1340 a name present in global namespace.
1341 """
1341 """
1342 return ( magic.startswith(bare_text) and
1342 return ( magic.startswith(bare_text) and
1343 magic not in global_matches )
1343 magic not in global_matches )
1344 else:
1344 else:
1345 def matches(magic):
1345 def matches(magic):
1346 return magic.startswith(bare_text)
1346 return magic.startswith(bare_text)
1347
1347
1348 comp = [ pre2+m for m in cell_magics if matches(m)]
1348 comp = [ pre2+m for m in cell_magics if matches(m)]
1349 if not text.startswith(pre2):
1349 if not text.startswith(pre2):
1350 comp += [ pre+m for m in line_magics if matches(m)]
1350 comp += [ pre+m for m in line_magics if matches(m)]
1351
1351
1352 return comp
1352 return comp
1353
1353
1354 def magic_config_matches(self, text:str) -> List[str]:
1354 def magic_config_matches(self, text:str) -> List[str]:
1355 """ Match class names and attributes for %config magic """
1355 """ Match class names and attributes for %config magic """
1356 texts = text.strip().split()
1356 texts = text.strip().split()
1357
1357
1358 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1358 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1359 # get all configuration classes
1359 # get all configuration classes
1360 classes = sorted(set([ c for c in self.shell.configurables
1360 classes = sorted(set([ c for c in self.shell.configurables
1361 if c.__class__.class_traits(config=True)
1361 if c.__class__.class_traits(config=True)
1362 ]), key=lambda x: x.__class__.__name__)
1362 ]), key=lambda x: x.__class__.__name__)
1363 classnames = [ c.__class__.__name__ for c in classes ]
1363 classnames = [ c.__class__.__name__ for c in classes ]
1364
1364
1365 # return all classnames if config or %config is given
1365 # return all classnames if config or %config is given
1366 if len(texts) == 1:
1366 if len(texts) == 1:
1367 return classnames
1367 return classnames
1368
1368
1369 # match classname
1369 # match classname
1370 classname_texts = texts[1].split('.')
1370 classname_texts = texts[1].split('.')
1371 classname = classname_texts[0]
1371 classname = classname_texts[0]
1372 classname_matches = [ c for c in classnames
1372 classname_matches = [ c for c in classnames
1373 if c.startswith(classname) ]
1373 if c.startswith(classname) ]
1374
1374
1375 # return matched classes or the matched class with attributes
1375 # return matched classes or the matched class with attributes
1376 if texts[1].find('.') < 0:
1376 if texts[1].find('.') < 0:
1377 return classname_matches
1377 return classname_matches
1378 elif len(classname_matches) == 1 and \
1378 elif len(classname_matches) == 1 and \
1379 classname_matches[0] == classname:
1379 classname_matches[0] == classname:
1380 cls = classes[classnames.index(classname)].__class__
1380 cls = classes[classnames.index(classname)].__class__
1381 help = cls.class_get_help()
1381 help = cls.class_get_help()
1382 # strip leading '--' from cl-args:
1382 # strip leading '--' from cl-args:
1383 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1383 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1384 return [ attr.split('=')[0]
1384 return [ attr.split('=')[0]
1385 for attr in help.strip().splitlines()
1385 for attr in help.strip().splitlines()
1386 if attr.startswith(texts[1]) ]
1386 if attr.startswith(texts[1]) ]
1387 return []
1387 return []
1388
1388
1389 def magic_color_matches(self, text:str) -> List[str] :
1389 def magic_color_matches(self, text:str) -> List[str] :
1390 """ Match color schemes for %colors magic"""
1390 """ Match color schemes for %colors magic"""
1391 texts = text.split()
1391 texts = text.split()
1392 if text.endswith(' '):
1392 if text.endswith(' '):
1393 # .split() strips off the trailing whitespace. Add '' back
1393 # .split() strips off the trailing whitespace. Add '' back
1394 # so that: '%colors ' -> ['%colors', '']
1394 # so that: '%colors ' -> ['%colors', '']
1395 texts.append('')
1395 texts.append('')
1396
1396
1397 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1397 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1398 prefix = texts[1]
1398 prefix = texts[1]
1399 return [ color for color in InspectColors.keys()
1399 return [ color for color in InspectColors.keys()
1400 if color.startswith(prefix) ]
1400 if color.startswith(prefix) ]
1401 return []
1401 return []
1402
1402
1403 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str) -> Iterable[Any]:
1403 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str) -> Iterable[Any]:
1404 """
1404 """
1405 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1405 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1406 cursor position.
1406 cursor position.
1407
1407
1408 Parameters
1408 Parameters
1409 ----------
1409 ----------
1410 cursor_column : int
1410 cursor_column : int
1411 column position of the cursor in ``text``, 0-indexed.
1411 column position of the cursor in ``text``, 0-indexed.
1412 cursor_line : int
1412 cursor_line : int
1413 line position of the cursor in ``text``, 0-indexed
1413 line position of the cursor in ``text``, 0-indexed
1414 text : str
1414 text : str
1415 text to complete
1415 text to complete
1416
1416
1417 Notes
1417 Notes
1418 -----
1418 -----
1419 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1419 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1420 object containing a string with the Jedi debug information attached.
1420 object containing a string with the Jedi debug information attached.
1421 """
1421 """
1422 namespaces = [self.namespace]
1422 namespaces = [self.namespace]
1423 if self.global_namespace is not None:
1423 if self.global_namespace is not None:
1424 namespaces.append(self.global_namespace)
1424 namespaces.append(self.global_namespace)
1425
1425
1426 completion_filter = lambda x:x
1426 completion_filter = lambda x:x
1427 offset = cursor_to_position(text, cursor_line, cursor_column)
1427 offset = cursor_to_position(text, cursor_line, cursor_column)
1428 # filter output if we are completing for object members
1428 # filter output if we are completing for object members
1429 if offset:
1429 if offset:
1430 pre = text[offset-1]
1430 pre = text[offset-1]
1431 if pre == '.':
1431 if pre == '.':
1432 if self.omit__names == 2:
1432 if self.omit__names == 2:
1433 completion_filter = lambda c:not c.name.startswith('_')
1433 completion_filter = lambda c:not c.name.startswith('_')
1434 elif self.omit__names == 1:
1434 elif self.omit__names == 1:
1435 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1435 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1436 elif self.omit__names == 0:
1436 elif self.omit__names == 0:
1437 completion_filter = lambda x:x
1437 completion_filter = lambda x:x
1438 else:
1438 else:
1439 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1439 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1440
1440
1441 interpreter = jedi.Interpreter(text[:offset], namespaces)
1441 interpreter = jedi.Interpreter(text[:offset], namespaces)
1442 try_jedi = True
1442 try_jedi = True
1443
1443
1444 try:
1444 try:
1445 # find the first token in the current tree -- if it is a ' or " then we are in a string
1445 # find the first token in the current tree -- if it is a ' or " then we are in a string
1446 completing_string = False
1446 completing_string = False
1447 try:
1447 try:
1448 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1448 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1449 except StopIteration:
1449 except StopIteration:
1450 pass
1450 pass
1451 else:
1451 else:
1452 # note the value may be ', ", or it may also be ''' or """, or
1452 # note the value may be ', ", or it may also be ''' or """, or
1453 # in some cases, """what/you/typed..., but all of these are
1453 # in some cases, """what/you/typed..., but all of these are
1454 # strings.
1454 # strings.
1455 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1455 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1456
1456
1457 # if we are in a string jedi is likely not the right candidate for
1457 # if we are in a string jedi is likely not the right candidate for
1458 # now. Skip it.
1458 # now. Skip it.
1459 try_jedi = not completing_string
1459 try_jedi = not completing_string
1460 except Exception as e:
1460 except Exception as e:
1461 # many of things can go wrong, we are using private API just don't crash.
1461 # many of things can go wrong, we are using private API just don't crash.
1462 if self.debug:
1462 if self.debug:
1463 print("Error detecting if completing a non-finished string :", e, '|')
1463 print("Error detecting if completing a non-finished string :", e, '|')
1464
1464
1465 if not try_jedi:
1465 if not try_jedi:
1466 return []
1466 return []
1467 try:
1467 try:
1468 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1468 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1469 except Exception as e:
1469 except Exception as e:
1470 if self.debug:
1470 if self.debug:
1471 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1471 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1472 else:
1472 else:
1473 return []
1473 return []
1474
1474
1475 def python_matches(self, text:str)->List[str]:
1475 def python_matches(self, text:str)->List[str]:
1476 """Match attributes or global python names"""
1476 """Match attributes or global python names"""
1477 if "." in text:
1477 if "." in text:
1478 try:
1478 try:
1479 matches = self.attr_matches(text)
1479 matches = self.attr_matches(text)
1480 if text.endswith('.') and self.omit__names:
1480 if text.endswith('.') and self.omit__names:
1481 if self.omit__names == 1:
1481 if self.omit__names == 1:
1482 # true if txt is _not_ a __ name, false otherwise:
1482 # true if txt is _not_ a __ name, false otherwise:
1483 no__name = (lambda txt:
1483 no__name = (lambda txt:
1484 re.match(r'.*\.__.*?__',txt) is None)
1484 re.match(r'.*\.__.*?__',txt) is None)
1485 else:
1485 else:
1486 # true if txt is _not_ a _ name, false otherwise:
1486 # true if txt is _not_ a _ name, false otherwise:
1487 no__name = (lambda txt:
1487 no__name = (lambda txt:
1488 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1488 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1489 matches = filter(no__name, matches)
1489 matches = filter(no__name, matches)
1490 except NameError:
1490 except NameError:
1491 # catches <undefined attributes>.<tab>
1491 # catches <undefined attributes>.<tab>
1492 matches = []
1492 matches = []
1493 else:
1493 else:
1494 matches = self.global_matches(text)
1494 matches = self.global_matches(text)
1495 return matches
1495 return matches
1496
1496
1497 def _default_arguments_from_docstring(self, doc):
1497 def _default_arguments_from_docstring(self, doc):
1498 """Parse the first line of docstring for call signature.
1498 """Parse the first line of docstring for call signature.
1499
1499
1500 Docstring should be of the form 'min(iterable[, key=func])\n'.
1500 Docstring should be of the form 'min(iterable[, key=func])\n'.
1501 It can also parse cython docstring of the form
1501 It can also parse cython docstring of the form
1502 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1502 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1503 """
1503 """
1504 if doc is None:
1504 if doc is None:
1505 return []
1505 return []
1506
1506
1507 #care only the firstline
1507 #care only the firstline
1508 line = doc.lstrip().splitlines()[0]
1508 line = doc.lstrip().splitlines()[0]
1509
1509
1510 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1510 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1511 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1511 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1512 sig = self.docstring_sig_re.search(line)
1512 sig = self.docstring_sig_re.search(line)
1513 if sig is None:
1513 if sig is None:
1514 return []
1514 return []
1515 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1515 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1516 sig = sig.groups()[0].split(',')
1516 sig = sig.groups()[0].split(',')
1517 ret = []
1517 ret = []
1518 for s in sig:
1518 for s in sig:
1519 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1519 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1520 ret += self.docstring_kwd_re.findall(s)
1520 ret += self.docstring_kwd_re.findall(s)
1521 return ret
1521 return ret
1522
1522
1523 def _default_arguments(self, obj):
1523 def _default_arguments(self, obj):
1524 """Return the list of default arguments of obj if it is callable,
1524 """Return the list of default arguments of obj if it is callable,
1525 or empty list otherwise."""
1525 or empty list otherwise."""
1526 call_obj = obj
1526 call_obj = obj
1527 ret = []
1527 ret = []
1528 if inspect.isbuiltin(obj):
1528 if inspect.isbuiltin(obj):
1529 pass
1529 pass
1530 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1530 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1531 if inspect.isclass(obj):
1531 if inspect.isclass(obj):
1532 #for cython embedsignature=True the constructor docstring
1532 #for cython embedsignature=True the constructor docstring
1533 #belongs to the object itself not __init__
1533 #belongs to the object itself not __init__
1534 ret += self._default_arguments_from_docstring(
1534 ret += self._default_arguments_from_docstring(
1535 getattr(obj, '__doc__', ''))
1535 getattr(obj, '__doc__', ''))
1536 # for classes, check for __init__,__new__
1536 # for classes, check for __init__,__new__
1537 call_obj = (getattr(obj, '__init__', None) or
1537 call_obj = (getattr(obj, '__init__', None) or
1538 getattr(obj, '__new__', None))
1538 getattr(obj, '__new__', None))
1539 # for all others, check if they are __call__able
1539 # for all others, check if they are __call__able
1540 elif hasattr(obj, '__call__'):
1540 elif hasattr(obj, '__call__'):
1541 call_obj = obj.__call__
1541 call_obj = obj.__call__
1542 ret += self._default_arguments_from_docstring(
1542 ret += self._default_arguments_from_docstring(
1543 getattr(call_obj, '__doc__', ''))
1543 getattr(call_obj, '__doc__', ''))
1544
1544
1545 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1545 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1546 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1546 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1547
1547
1548 try:
1548 try:
1549 sig = inspect.signature(obj)
1549 sig = inspect.signature(obj)
1550 ret.extend(k for k, v in sig.parameters.items() if
1550 ret.extend(k for k, v in sig.parameters.items() if
1551 v.kind in _keeps)
1551 v.kind in _keeps)
1552 except ValueError:
1552 except ValueError:
1553 pass
1553 pass
1554
1554
1555 return list(set(ret))
1555 return list(set(ret))
1556
1556
1557 def python_func_kw_matches(self, text):
1557 def python_func_kw_matches(self, text):
1558 """Match named parameters (kwargs) of the last open function"""
1558 """Match named parameters (kwargs) of the last open function"""
1559
1559
1560 if "." in text: # a parameter cannot be dotted
1560 if "." in text: # a parameter cannot be dotted
1561 return []
1561 return []
1562 try: regexp = self.__funcParamsRegex
1562 try: regexp = self.__funcParamsRegex
1563 except AttributeError:
1563 except AttributeError:
1564 regexp = self.__funcParamsRegex = re.compile(r'''
1564 regexp = self.__funcParamsRegex = re.compile(r'''
1565 '.*?(?<!\\)' | # single quoted strings or
1565 '.*?(?<!\\)' | # single quoted strings or
1566 ".*?(?<!\\)" | # double quoted strings or
1566 ".*?(?<!\\)" | # double quoted strings or
1567 \w+ | # identifier
1567 \w+ | # identifier
1568 \S # other characters
1568 \S # other characters
1569 ''', re.VERBOSE | re.DOTALL)
1569 ''', re.VERBOSE | re.DOTALL)
1570 # 1. find the nearest identifier that comes before an unclosed
1570 # 1. find the nearest identifier that comes before an unclosed
1571 # parenthesis before the cursor
1571 # parenthesis before the cursor
1572 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1572 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1573 tokens = regexp.findall(self.text_until_cursor)
1573 tokens = regexp.findall(self.text_until_cursor)
1574 iterTokens = reversed(tokens); openPar = 0
1574 iterTokens = reversed(tokens); openPar = 0
1575
1575
1576 for token in iterTokens:
1576 for token in iterTokens:
1577 if token == ')':
1577 if token == ')':
1578 openPar -= 1
1578 openPar -= 1
1579 elif token == '(':
1579 elif token == '(':
1580 openPar += 1
1580 openPar += 1
1581 if openPar > 0:
1581 if openPar > 0:
1582 # found the last unclosed parenthesis
1582 # found the last unclosed parenthesis
1583 break
1583 break
1584 else:
1584 else:
1585 return []
1585 return []
1586 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1586 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1587 ids = []
1587 ids = []
1588 isId = re.compile(r'\w+$').match
1588 isId = re.compile(r'\w+$').match
1589
1589
1590 while True:
1590 while True:
1591 try:
1591 try:
1592 ids.append(next(iterTokens))
1592 ids.append(next(iterTokens))
1593 if not isId(ids[-1]):
1593 if not isId(ids[-1]):
1594 ids.pop(); break
1594 ids.pop(); break
1595 if not next(iterTokens) == '.':
1595 if not next(iterTokens) == '.':
1596 break
1596 break
1597 except StopIteration:
1597 except StopIteration:
1598 break
1598 break
1599
1599
1600 # Find all named arguments already assigned to, as to avoid suggesting
1600 # Find all named arguments already assigned to, as to avoid suggesting
1601 # them again
1601 # them again
1602 usedNamedArgs = set()
1602 usedNamedArgs = set()
1603 par_level = -1
1603 par_level = -1
1604 for token, next_token in zip(tokens, tokens[1:]):
1604 for token, next_token in zip(tokens, tokens[1:]):
1605 if token == '(':
1605 if token == '(':
1606 par_level += 1
1606 par_level += 1
1607 elif token == ')':
1607 elif token == ')':
1608 par_level -= 1
1608 par_level -= 1
1609
1609
1610 if par_level != 0:
1610 if par_level != 0:
1611 continue
1611 continue
1612
1612
1613 if next_token != '=':
1613 if next_token != '=':
1614 continue
1614 continue
1615
1615
1616 usedNamedArgs.add(token)
1616 usedNamedArgs.add(token)
1617
1617
1618 argMatches = []
1618 argMatches = []
1619 try:
1619 try:
1620 callableObj = '.'.join(ids[::-1])
1620 callableObj = '.'.join(ids[::-1])
1621 namedArgs = self._default_arguments(eval(callableObj,
1621 namedArgs = self._default_arguments(eval(callableObj,
1622 self.namespace))
1622 self.namespace))
1623
1623
1624 # Remove used named arguments from the list, no need to show twice
1624 # Remove used named arguments from the list, no need to show twice
1625 for namedArg in set(namedArgs) - usedNamedArgs:
1625 for namedArg in set(namedArgs) - usedNamedArgs:
1626 if namedArg.startswith(text):
1626 if namedArg.startswith(text):
1627 argMatches.append("%s=" %namedArg)
1627 argMatches.append("%s=" %namedArg)
1628 except:
1628 except:
1629 pass
1629 pass
1630
1630
1631 return argMatches
1631 return argMatches
1632
1632
1633 @staticmethod
1633 @staticmethod
1634 def _get_keys(obj: Any) -> List[Any]:
1634 def _get_keys(obj: Any) -> List[Any]:
1635 # Objects can define their own completions by defining an
1635 # Objects can define their own completions by defining an
1636 # _ipy_key_completions_() method.
1636 # _ipy_key_completions_() method.
1637 method = get_real_method(obj, '_ipython_key_completions_')
1637 method = get_real_method(obj, '_ipython_key_completions_')
1638 if method is not None:
1638 if method is not None:
1639 return method()
1639 return method()
1640
1640
1641 # Special case some common in-memory dict-like types
1641 # Special case some common in-memory dict-like types
1642 if isinstance(obj, dict) or\
1642 if isinstance(obj, dict) or\
1643 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1643 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1644 try:
1644 try:
1645 return list(obj.keys())
1645 return list(obj.keys())
1646 except Exception:
1646 except Exception:
1647 return []
1647 return []
1648 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1648 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1649 _safe_isinstance(obj, 'numpy', 'void'):
1649 _safe_isinstance(obj, 'numpy', 'void'):
1650 return obj.dtype.names or []
1650 return obj.dtype.names or []
1651 return []
1651 return []
1652
1652
1653 def dict_key_matches(self, text:str) -> List[str]:
1653 def dict_key_matches(self, text:str) -> List[str]:
1654 "Match string keys in a dictionary, after e.g. 'foo[' "
1654 "Match string keys in a dictionary, after e.g. 'foo[' "
1655
1655
1656
1656
1657 if self.__dict_key_regexps is not None:
1657 if self.__dict_key_regexps is not None:
1658 regexps = self.__dict_key_regexps
1658 regexps = self.__dict_key_regexps
1659 else:
1659 else:
1660 dict_key_re_fmt = r'''(?x)
1660 dict_key_re_fmt = r'''(?x)
1661 ( # match dict-referring expression wrt greedy setting
1661 ( # match dict-referring expression wrt greedy setting
1662 %s
1662 %s
1663 )
1663 )
1664 \[ # open bracket
1664 \[ # open bracket
1665 \s* # and optional whitespace
1665 \s* # and optional whitespace
1666 # Capture any number of str-like objects (e.g. "a", "b", 'c')
1666 # Capture any number of str-like objects (e.g. "a", "b", 'c')
1667 ((?:[uUbB]? # string prefix (r not handled)
1667 ((?:[uUbB]? # string prefix (r not handled)
1668 (?:
1668 (?:
1669 '(?:[^']|(?<!\\)\\')*'
1669 '(?:[^']|(?<!\\)\\')*'
1670 |
1670 |
1671 "(?:[^"]|(?<!\\)\\")*"
1671 "(?:[^"]|(?<!\\)\\")*"
1672 )
1672 )
1673 \s*,\s*
1673 \s*,\s*
1674 )*)
1674 )*)
1675 ([uUbB]? # string prefix (r not handled)
1675 ([uUbB]? # string prefix (r not handled)
1676 (?: # unclosed string
1676 (?: # unclosed string
1677 '(?:[^']|(?<!\\)\\')*
1677 '(?:[^']|(?<!\\)\\')*
1678 |
1678 |
1679 "(?:[^"]|(?<!\\)\\")*
1679 "(?:[^"]|(?<!\\)\\")*
1680 )
1680 )
1681 )?
1681 )?
1682 $
1682 $
1683 '''
1683 '''
1684 regexps = self.__dict_key_regexps = {
1684 regexps = self.__dict_key_regexps = {
1685 False: re.compile(dict_key_re_fmt % r'''
1685 False: re.compile(dict_key_re_fmt % r'''
1686 # identifiers separated by .
1686 # identifiers separated by .
1687 (?!\d)\w+
1687 (?!\d)\w+
1688 (?:\.(?!\d)\w+)*
1688 (?:\.(?!\d)\w+)*
1689 '''),
1689 '''),
1690 True: re.compile(dict_key_re_fmt % '''
1690 True: re.compile(dict_key_re_fmt % '''
1691 .+
1691 .+
1692 ''')
1692 ''')
1693 }
1693 }
1694
1694
1695 match = regexps[self.greedy].search(self.text_until_cursor)
1695 match = regexps[self.greedy].search(self.text_until_cursor)
1696
1696
1697 if match is None:
1697 if match is None:
1698 return []
1698 return []
1699
1699
1700 expr, prefix0, prefix = match.groups()
1700 expr, prefix0, prefix = match.groups()
1701 try:
1701 try:
1702 obj = eval(expr, self.namespace)
1702 obj = eval(expr, self.namespace)
1703 except Exception:
1703 except Exception:
1704 try:
1704 try:
1705 obj = eval(expr, self.global_namespace)
1705 obj = eval(expr, self.global_namespace)
1706 except Exception:
1706 except Exception:
1707 return []
1707 return []
1708
1708
1709 keys = self._get_keys(obj)
1709 keys = self._get_keys(obj)
1710 if not keys:
1710 if not keys:
1711 return keys
1711 return keys
1712
1712
1713 extra_prefix = eval(prefix0) if prefix0 != '' else None
1713 extra_prefix = eval(prefix0) if prefix0 != '' else None
1714
1714
1715 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
1715 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims, extra_prefix=extra_prefix)
1716 if not matches:
1716 if not matches:
1717 return matches
1717 return matches
1718
1718
1719 # get the cursor position of
1719 # get the cursor position of
1720 # - the text being completed
1720 # - the text being completed
1721 # - the start of the key text
1721 # - the start of the key text
1722 # - the start of the completion
1722 # - the start of the completion
1723 text_start = len(self.text_until_cursor) - len(text)
1723 text_start = len(self.text_until_cursor) - len(text)
1724 if prefix:
1724 if prefix:
1725 key_start = match.start(3)
1725 key_start = match.start(3)
1726 completion_start = key_start + token_offset
1726 completion_start = key_start + token_offset
1727 else:
1727 else:
1728 key_start = completion_start = match.end()
1728 key_start = completion_start = match.end()
1729
1729
1730 # grab the leading prefix, to make sure all completions start with `text`
1730 # grab the leading prefix, to make sure all completions start with `text`
1731 if text_start > key_start:
1731 if text_start > key_start:
1732 leading = ''
1732 leading = ''
1733 else:
1733 else:
1734 leading = text[text_start:completion_start]
1734 leading = text[text_start:completion_start]
1735
1735
1736 # the index of the `[` character
1736 # the index of the `[` character
1737 bracket_idx = match.end(1)
1737 bracket_idx = match.end(1)
1738
1738
1739 # append closing quote and bracket as appropriate
1739 # append closing quote and bracket as appropriate
1740 # this is *not* appropriate if the opening quote or bracket is outside
1740 # this is *not* appropriate if the opening quote or bracket is outside
1741 # the text given to this method
1741 # the text given to this method
1742 suf = ''
1742 suf = ''
1743 continuation = self.line_buffer[len(self.text_until_cursor):]
1743 continuation = self.line_buffer[len(self.text_until_cursor):]
1744 if key_start > text_start and closing_quote:
1744 if key_start > text_start and closing_quote:
1745 # quotes were opened inside text, maybe close them
1745 # quotes were opened inside text, maybe close them
1746 if continuation.startswith(closing_quote):
1746 if continuation.startswith(closing_quote):
1747 continuation = continuation[len(closing_quote):]
1747 continuation = continuation[len(closing_quote):]
1748 else:
1748 else:
1749 suf += closing_quote
1749 suf += closing_quote
1750 if bracket_idx > text_start:
1750 if bracket_idx > text_start:
1751 # brackets were opened inside text, maybe close them
1751 # brackets were opened inside text, maybe close them
1752 if not continuation.startswith(']'):
1752 if not continuation.startswith(']'):
1753 suf += ']'
1753 suf += ']'
1754
1754
1755 return [leading + k + suf for k in matches]
1755 return [leading + k + suf for k in matches]
1756
1756
1757 @staticmethod
1757 @staticmethod
1758 def unicode_name_matches(text:str) -> Tuple[str, List[str]] :
1758 def unicode_name_matches(text:str) -> Tuple[str, List[str]] :
1759 """Match Latex-like syntax for unicode characters base
1759 """Match Latex-like syntax for unicode characters base
1760 on the name of the character.
1760 on the name of the character.
1761
1761
1762 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1762 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1763
1763
1764 Works only on valid python 3 identifier, or on combining characters that
1764 Works only on valid python 3 identifier, or on combining characters that
1765 will combine to form a valid identifier.
1765 will combine to form a valid identifier.
1766 """
1766 """
1767 slashpos = text.rfind('\\')
1767 slashpos = text.rfind('\\')
1768 if slashpos > -1:
1768 if slashpos > -1:
1769 s = text[slashpos+1:]
1769 s = text[slashpos+1:]
1770 try :
1770 try :
1771 unic = unicodedata.lookup(s)
1771 unic = unicodedata.lookup(s)
1772 # allow combining chars
1772 # allow combining chars
1773 if ('a'+unic).isidentifier():
1773 if ('a'+unic).isidentifier():
1774 return '\\'+s,[unic]
1774 return '\\'+s,[unic]
1775 except KeyError:
1775 except KeyError:
1776 pass
1776 pass
1777 return '', []
1777 return '', []
1778
1778
1779
1779
1780 def latex_matches(self, text:str) -> Tuple[str, Sequence[str]]:
1780 def latex_matches(self, text:str) -> Tuple[str, Sequence[str]]:
1781 """Match Latex syntax for unicode characters.
1781 """Match Latex syntax for unicode characters.
1782
1782
1783 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1783 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1784 """
1784 """
1785 slashpos = text.rfind('\\')
1785 slashpos = text.rfind('\\')
1786 if slashpos > -1:
1786 if slashpos > -1:
1787 s = text[slashpos:]
1787 s = text[slashpos:]
1788 if s in latex_symbols:
1788 if s in latex_symbols:
1789 # Try to complete a full latex symbol to unicode
1789 # Try to complete a full latex symbol to unicode
1790 # \\alpha -> Ξ±
1790 # \\alpha -> Ξ±
1791 return s, [latex_symbols[s]]
1791 return s, [latex_symbols[s]]
1792 else:
1792 else:
1793 # If a user has partially typed a latex symbol, give them
1793 # If a user has partially typed a latex symbol, give them
1794 # a full list of options \al -> [\aleph, \alpha]
1794 # a full list of options \al -> [\aleph, \alpha]
1795 matches = [k for k in latex_symbols if k.startswith(s)]
1795 matches = [k for k in latex_symbols if k.startswith(s)]
1796 if matches:
1796 if matches:
1797 return s, matches
1797 return s, matches
1798 return '', ()
1798 return '', ()
1799
1799
1800 def dispatch_custom_completer(self, text):
1800 def dispatch_custom_completer(self, text):
1801 if not self.custom_completers:
1801 if not self.custom_completers:
1802 return
1802 return
1803
1803
1804 line = self.line_buffer
1804 line = self.line_buffer
1805 if not line.strip():
1805 if not line.strip():
1806 return None
1806 return None
1807
1807
1808 # Create a little structure to pass all the relevant information about
1808 # Create a little structure to pass all the relevant information about
1809 # the current completion to any custom completer.
1809 # the current completion to any custom completer.
1810 event = SimpleNamespace()
1810 event = SimpleNamespace()
1811 event.line = line
1811 event.line = line
1812 event.symbol = text
1812 event.symbol = text
1813 cmd = line.split(None,1)[0]
1813 cmd = line.split(None,1)[0]
1814 event.command = cmd
1814 event.command = cmd
1815 event.text_until_cursor = self.text_until_cursor
1815 event.text_until_cursor = self.text_until_cursor
1816
1816
1817 # for foo etc, try also to find completer for %foo
1817 # for foo etc, try also to find completer for %foo
1818 if not cmd.startswith(self.magic_escape):
1818 if not cmd.startswith(self.magic_escape):
1819 try_magic = self.custom_completers.s_matches(
1819 try_magic = self.custom_completers.s_matches(
1820 self.magic_escape + cmd)
1820 self.magic_escape + cmd)
1821 else:
1821 else:
1822 try_magic = []
1822 try_magic = []
1823
1823
1824 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1824 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1825 try_magic,
1825 try_magic,
1826 self.custom_completers.flat_matches(self.text_until_cursor)):
1826 self.custom_completers.flat_matches(self.text_until_cursor)):
1827 try:
1827 try:
1828 res = c(event)
1828 res = c(event)
1829 if res:
1829 if res:
1830 # first, try case sensitive match
1830 # first, try case sensitive match
1831 withcase = [r for r in res if r.startswith(text)]
1831 withcase = [r for r in res if r.startswith(text)]
1832 if withcase:
1832 if withcase:
1833 return withcase
1833 return withcase
1834 # if none, then case insensitive ones are ok too
1834 # if none, then case insensitive ones are ok too
1835 text_low = text.lower()
1835 text_low = text.lower()
1836 return [r for r in res if r.lower().startswith(text_low)]
1836 return [r for r in res if r.lower().startswith(text_low)]
1837 except TryNext:
1837 except TryNext:
1838 pass
1838 pass
1839 except KeyboardInterrupt:
1839 except KeyboardInterrupt:
1840 """
1840 """
1841 If custom completer take too long,
1841 If custom completer take too long,
1842 let keyboard interrupt abort and return nothing.
1842 let keyboard interrupt abort and return nothing.
1843 """
1843 """
1844 break
1844 break
1845
1845
1846 return None
1846 return None
1847
1847
1848 def completions(self, text: str, offset: int)->Iterator[Completion]:
1848 def completions(self, text: str, offset: int)->Iterator[Completion]:
1849 """
1849 """
1850 Returns an iterator over the possible completions
1850 Returns an iterator over the possible completions
1851
1851
1852 .. warning::
1852 .. warning::
1853
1853
1854 Unstable
1854 Unstable
1855
1855
1856 This function is unstable, API may change without warning.
1856 This function is unstable, API may change without warning.
1857 It will also raise unless use in proper context manager.
1857 It will also raise unless use in proper context manager.
1858
1858
1859 Parameters
1859 Parameters
1860 ----------
1860 ----------
1861 text : str
1861 text : str
1862 Full text of the current input, multi line string.
1862 Full text of the current input, multi line string.
1863 offset : int
1863 offset : int
1864 Integer representing the position of the cursor in ``text``. Offset
1864 Integer representing the position of the cursor in ``text``. Offset
1865 is 0-based indexed.
1865 is 0-based indexed.
1866
1866
1867 Yields
1867 Yields
1868 ------
1868 ------
1869 Completion
1869 Completion
1870
1870
1871 Notes
1871 Notes
1872 -----
1872 -----
1873 The cursor on a text can either be seen as being "in between"
1873 The cursor on a text can either be seen as being "in between"
1874 characters or "On" a character depending on the interface visible to
1874 characters or "On" a character depending on the interface visible to
1875 the user. For consistency the cursor being on "in between" characters X
1875 the user. For consistency the cursor being on "in between" characters X
1876 and Y is equivalent to the cursor being "on" character Y, that is to say
1876 and Y is equivalent to the cursor being "on" character Y, that is to say
1877 the character the cursor is on is considered as being after the cursor.
1877 the character the cursor is on is considered as being after the cursor.
1878
1878
1879 Combining characters may span more that one position in the
1879 Combining characters may span more that one position in the
1880 text.
1880 text.
1881
1881
1882 .. note::
1882 .. note::
1883
1883
1884 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1884 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1885 fake Completion token to distinguish completion returned by Jedi
1885 fake Completion token to distinguish completion returned by Jedi
1886 and usual IPython completion.
1886 and usual IPython completion.
1887
1887
1888 .. note::
1888 .. note::
1889
1889
1890 Completions are not completely deduplicated yet. If identical
1890 Completions are not completely deduplicated yet. If identical
1891 completions are coming from different sources this function does not
1891 completions are coming from different sources this function does not
1892 ensure that each completion object will only be present once.
1892 ensure that each completion object will only be present once.
1893 """
1893 """
1894 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1894 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1895 "It may change without warnings. "
1895 "It may change without warnings. "
1896 "Use in corresponding context manager.",
1896 "Use in corresponding context manager.",
1897 category=ProvisionalCompleterWarning, stacklevel=2)
1897 category=ProvisionalCompleterWarning, stacklevel=2)
1898
1898
1899 seen = set()
1899 seen = set()
1900 profiler:Optional[cProfile.Profile]
1900 profiler:Optional[cProfile.Profile]
1901 try:
1901 try:
1902 if self.profile_completions:
1902 if self.profile_completions:
1903 import cProfile
1903 import cProfile
1904 profiler = cProfile.Profile()
1904 profiler = cProfile.Profile()
1905 profiler.enable()
1905 profiler.enable()
1906 else:
1906 else:
1907 profiler = None
1907 profiler = None
1908
1908
1909 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1909 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1910 if c and (c in seen):
1910 if c and (c in seen):
1911 continue
1911 continue
1912 yield c
1912 yield c
1913 seen.add(c)
1913 seen.add(c)
1914 except KeyboardInterrupt:
1914 except KeyboardInterrupt:
1915 """if completions take too long and users send keyboard interrupt,
1915 """if completions take too long and users send keyboard interrupt,
1916 do not crash and return ASAP. """
1916 do not crash and return ASAP. """
1917 pass
1917 pass
1918 finally:
1918 finally:
1919 if profiler is not None:
1919 if profiler is not None:
1920 profiler.disable()
1920 profiler.disable()
1921 ensure_dir_exists(self.profiler_output_dir)
1921 ensure_dir_exists(self.profiler_output_dir)
1922 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
1922 output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
1923 print("Writing profiler output to", output_path)
1923 print("Writing profiler output to", output_path)
1924 profiler.dump_stats(output_path)
1924 profiler.dump_stats(output_path)
1925
1925
1926 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
1926 def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
1927 """
1927 """
1928 Core completion module.Same signature as :any:`completions`, with the
1928 Core completion module.Same signature as :any:`completions`, with the
1929 extra `timeout` parameter (in seconds).
1929 extra `timeout` parameter (in seconds).
1930
1930
1931 Computing jedi's completion ``.type`` can be quite expensive (it is a
1931 Computing jedi's completion ``.type`` can be quite expensive (it is a
1932 lazy property) and can require some warm-up, more warm up than just
1932 lazy property) and can require some warm-up, more warm up than just
1933 computing the ``name`` of a completion. The warm-up can be :
1933 computing the ``name`` of a completion. The warm-up can be :
1934
1934
1935 - Long warm-up the first time a module is encountered after
1935 - Long warm-up the first time a module is encountered after
1936 install/update: actually build parse/inference tree.
1936 install/update: actually build parse/inference tree.
1937
1937
1938 - first time the module is encountered in a session: load tree from
1938 - first time the module is encountered in a session: load tree from
1939 disk.
1939 disk.
1940
1940
1941 We don't want to block completions for tens of seconds so we give the
1941 We don't want to block completions for tens of seconds so we give the
1942 completer a "budget" of ``_timeout`` seconds per invocation to compute
1942 completer a "budget" of ``_timeout`` seconds per invocation to compute
1943 completions types, the completions that have not yet been computed will
1943 completions types, the completions that have not yet been computed will
1944 be marked as "unknown" an will have a chance to be computed next round
1944 be marked as "unknown" an will have a chance to be computed next round
1945 are things get cached.
1945 are things get cached.
1946
1946
1947 Keep in mind that Jedi is not the only thing treating the completion so
1947 Keep in mind that Jedi is not the only thing treating the completion so
1948 keep the timeout short-ish as if we take more than 0.3 second we still
1948 keep the timeout short-ish as if we take more than 0.3 second we still
1949 have lots of processing to do.
1949 have lots of processing to do.
1950
1950
1951 """
1951 """
1952 deadline = time.monotonic() + _timeout
1952 deadline = time.monotonic() + _timeout
1953
1953
1954
1954
1955 before = full_text[:offset]
1955 before = full_text[:offset]
1956 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1956 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1957
1957
1958 matched_text, matches, matches_origin, jedi_matches = self._complete(
1958 matched_text, matches, matches_origin, jedi_matches = self._complete(
1959 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1959 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1960
1960
1961 iter_jm = iter(jedi_matches)
1961 iter_jm = iter(jedi_matches)
1962 if _timeout:
1962 if _timeout:
1963 for jm in iter_jm:
1963 for jm in iter_jm:
1964 try:
1964 try:
1965 type_ = jm.type
1965 type_ = jm.type
1966 except Exception:
1966 except Exception:
1967 if self.debug:
1967 if self.debug:
1968 print("Error in Jedi getting type of ", jm)
1968 print("Error in Jedi getting type of ", jm)
1969 type_ = None
1969 type_ = None
1970 delta = len(jm.name_with_symbols) - len(jm.complete)
1970 delta = len(jm.name_with_symbols) - len(jm.complete)
1971 if type_ == 'function':
1971 if type_ == 'function':
1972 signature = _make_signature(jm)
1972 signature = _make_signature(jm)
1973 else:
1973 else:
1974 signature = ''
1974 signature = ''
1975 yield Completion(start=offset - delta,
1975 yield Completion(start=offset - delta,
1976 end=offset,
1976 end=offset,
1977 text=jm.name_with_symbols,
1977 text=jm.name_with_symbols,
1978 type=type_,
1978 type=type_,
1979 signature=signature,
1979 signature=signature,
1980 _origin='jedi')
1980 _origin='jedi')
1981
1981
1982 if time.monotonic() > deadline:
1982 if time.monotonic() > deadline:
1983 break
1983 break
1984
1984
1985 for jm in iter_jm:
1985 for jm in iter_jm:
1986 delta = len(jm.name_with_symbols) - len(jm.complete)
1986 delta = len(jm.name_with_symbols) - len(jm.complete)
1987 yield Completion(start=offset - delta,
1987 yield Completion(start=offset - delta,
1988 end=offset,
1988 end=offset,
1989 text=jm.name_with_symbols,
1989 text=jm.name_with_symbols,
1990 type='<unknown>', # don't compute type for speed
1990 type='<unknown>', # don't compute type for speed
1991 _origin='jedi',
1991 _origin='jedi',
1992 signature='')
1992 signature='')
1993
1993
1994
1994
1995 start_offset = before.rfind(matched_text)
1995 start_offset = before.rfind(matched_text)
1996
1996
1997 # TODO:
1997 # TODO:
1998 # Suppress this, right now just for debug.
1998 # Suppress this, right now just for debug.
1999 if jedi_matches and matches and self.debug:
1999 if jedi_matches and matches and self.debug:
2000 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
2000 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
2001 _origin='debug', type='none', signature='')
2001 _origin='debug', type='none', signature='')
2002
2002
2003 # I'm unsure if this is always true, so let's assert and see if it
2003 # I'm unsure if this is always true, so let's assert and see if it
2004 # crash
2004 # crash
2005 assert before.endswith(matched_text)
2005 assert before.endswith(matched_text)
2006 for m, t in zip(matches, matches_origin):
2006 for m, t in zip(matches, matches_origin):
2007 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
2007 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
2008
2008
2009
2009
2010 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2010 def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
2011 """Find completions for the given text and line context.
2011 """Find completions for the given text and line context.
2012
2012
2013 Note that both the text and the line_buffer are optional, but at least
2013 Note that both the text and the line_buffer are optional, but at least
2014 one of them must be given.
2014 one of them must be given.
2015
2015
2016 Parameters
2016 Parameters
2017 ----------
2017 ----------
2018 text : string, optional
2018 text : string, optional
2019 Text to perform the completion on. If not given, the line buffer
2019 Text to perform the completion on. If not given, the line buffer
2020 is split using the instance's CompletionSplitter object.
2020 is split using the instance's CompletionSplitter object.
2021 line_buffer : string, optional
2021 line_buffer : string, optional
2022 If not given, the completer attempts to obtain the current line
2022 If not given, the completer attempts to obtain the current line
2023 buffer via readline. This keyword allows clients which are
2023 buffer via readline. This keyword allows clients which are
2024 requesting for text completions in non-readline contexts to inform
2024 requesting for text completions in non-readline contexts to inform
2025 the completer of the entire text.
2025 the completer of the entire text.
2026 cursor_pos : int, optional
2026 cursor_pos : int, optional
2027 Index of the cursor in the full line buffer. Should be provided by
2027 Index of the cursor in the full line buffer. Should be provided by
2028 remote frontends where kernel has no access to frontend state.
2028 remote frontends where kernel has no access to frontend state.
2029
2029
2030 Returns
2030 Returns
2031 -------
2031 -------
2032 Tuple of two items:
2032 Tuple of two items:
2033 text : str
2033 text : str
2034 Text that was actually used in the completion.
2034 Text that was actually used in the completion.
2035 matches : list
2035 matches : list
2036 A list of completion matches.
2036 A list of completion matches.
2037
2037
2038 Notes
2038 Notes
2039 -----
2039 -----
2040 This API is likely to be deprecated and replaced by
2040 This API is likely to be deprecated and replaced by
2041 :any:`IPCompleter.completions` in the future.
2041 :any:`IPCompleter.completions` in the future.
2042
2042
2043 """
2043 """
2044 warnings.warn('`Completer.complete` is pending deprecation since '
2044 warnings.warn('`Completer.complete` is pending deprecation since '
2045 'IPython 6.0 and will be replaced by `Completer.completions`.',
2045 'IPython 6.0 and will be replaced by `Completer.completions`.',
2046 PendingDeprecationWarning)
2046 PendingDeprecationWarning)
2047 # potential todo, FOLD the 3rd throw away argument of _complete
2047 # potential todo, FOLD the 3rd throw away argument of _complete
2048 # into the first 2 one.
2048 # into the first 2 one.
2049 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
2049 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
2050
2050
2051 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2051 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
2052 full_text=None) -> _CompleteResult:
2052 full_text=None) -> _CompleteResult:
2053 """
2053 """
2054 Like complete but can also returns raw jedi completions as well as the
2054 Like complete but can also returns raw jedi completions as well as the
2055 origin of the completion text. This could (and should) be made much
2055 origin of the completion text. This could (and should) be made much
2056 cleaner but that will be simpler once we drop the old (and stateful)
2056 cleaner but that will be simpler once we drop the old (and stateful)
2057 :any:`complete` API.
2057 :any:`complete` API.
2058
2058
2059 With current provisional API, cursor_pos act both (depending on the
2059 With current provisional API, cursor_pos act both (depending on the
2060 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2060 caller) as the offset in the ``text`` or ``line_buffer``, or as the
2061 ``column`` when passing multiline strings this could/should be renamed
2061 ``column`` when passing multiline strings this could/should be renamed
2062 but would add extra noise.
2062 but would add extra noise.
2063
2063
2064 Parameters
2064 Parameters
2065 ----------
2065 ----------
2066 cursor_line
2066 cursor_line
2067 Index of the line the cursor is on. 0 indexed.
2067 Index of the line the cursor is on. 0 indexed.
2068 cursor_pos
2068 cursor_pos
2069 Position of the cursor in the current line/line_buffer/text. 0
2069 Position of the cursor in the current line/line_buffer/text. 0
2070 indexed.
2070 indexed.
2071 line_buffer : optional, str
2071 line_buffer : optional, str
2072 The current line the cursor is in, this is mostly due to legacy
2072 The current line the cursor is in, this is mostly due to legacy
2073 reason that readline could only give a us the single current line.
2073 reason that readline could only give a us the single current line.
2074 Prefer `full_text`.
2074 Prefer `full_text`.
2075 text : str
2075 text : str
2076 The current "token" the cursor is in, mostly also for historical
2076 The current "token" the cursor is in, mostly also for historical
2077 reasons. as the completer would trigger only after the current line
2077 reasons. as the completer would trigger only after the current line
2078 was parsed.
2078 was parsed.
2079 full_text : str
2079 full_text : str
2080 Full text of the current cell.
2080 Full text of the current cell.
2081
2081
2082 Returns
2082 Returns
2083 -------
2083 -------
2084 A tuple of N elements which are (likely):
2084 A tuple of N elements which are (likely):
2085 matched_text: ? the text that the complete matched
2085 matched_text: ? the text that the complete matched
2086 matches: list of completions ?
2086 matches: list of completions ?
2087 matches_origin: ? list same length as matches, and where each completion came from
2087 matches_origin: ? list same length as matches, and where each completion came from
2088 jedi_matches: list of Jedi matches, have it's own structure.
2088 jedi_matches: list of Jedi matches, have it's own structure.
2089 """
2089 """
2090
2090
2091
2091
2092 # if the cursor position isn't given, the only sane assumption we can
2092 # if the cursor position isn't given, the only sane assumption we can
2093 # make is that it's at the end of the line (the common case)
2093 # make is that it's at the end of the line (the common case)
2094 if cursor_pos is None:
2094 if cursor_pos is None:
2095 cursor_pos = len(line_buffer) if text is None else len(text)
2095 cursor_pos = len(line_buffer) if text is None else len(text)
2096
2096
2097 if self.use_main_ns:
2097 if self.use_main_ns:
2098 self.namespace = __main__.__dict__
2098 self.namespace = __main__.__dict__
2099
2099
2100 # if text is either None or an empty string, rely on the line buffer
2100 # if text is either None or an empty string, rely on the line buffer
2101 if (not line_buffer) and full_text:
2101 if (not line_buffer) and full_text:
2102 line_buffer = full_text.split('\n')[cursor_line]
2102 line_buffer = full_text.split('\n')[cursor_line]
2103 if not text: # issue #11508: check line_buffer before calling split_line
2103 if not text: # issue #11508: check line_buffer before calling split_line
2104 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2104 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2105
2105
2106 if self.backslash_combining_completions:
2106 if self.backslash_combining_completions:
2107 # allow deactivation of these on windows.
2107 # allow deactivation of these on windows.
2108 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2108 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2109
2109
2110 for meth in (self.latex_matches,
2110 for meth in (self.latex_matches,
2111 self.unicode_name_matches,
2111 self.unicode_name_matches,
2112 back_latex_name_matches,
2112 back_latex_name_matches,
2113 back_unicode_name_matches,
2113 back_unicode_name_matches,
2114 self.fwd_unicode_match):
2114 self.fwd_unicode_match):
2115 name_text, name_matches = meth(base_text)
2115 name_text, name_matches = meth(base_text)
2116 if name_text:
2116 if name_text:
2117 return _CompleteResult(name_text, name_matches[:MATCHES_LIMIT], \
2117 return _CompleteResult(name_text, name_matches[:MATCHES_LIMIT], \
2118 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ())
2118 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ())
2119
2119
2120
2120
2121 # If no line buffer is given, assume the input text is all there was
2121 # If no line buffer is given, assume the input text is all there was
2122 if line_buffer is None:
2122 if line_buffer is None:
2123 line_buffer = text
2123 line_buffer = text
2124
2124
2125 self.line_buffer = line_buffer
2125 self.line_buffer = line_buffer
2126 self.text_until_cursor = self.line_buffer[:cursor_pos]
2126 self.text_until_cursor = self.line_buffer[:cursor_pos]
2127
2127
2128 # Do magic arg matches
2128 # Do magic arg matches
2129 for matcher in self.magic_arg_matchers:
2129 for matcher in self.magic_arg_matchers:
2130 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2130 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2131 if matches:
2131 if matches:
2132 origins = [matcher.__qualname__] * len(matches)
2132 origins = [matcher.__qualname__] * len(matches)
2133 return _CompleteResult(text, matches, origins, ())
2133 return _CompleteResult(text, matches, origins, ())
2134
2134
2135 # Start with a clean slate of completions
2135 # Start with a clean slate of completions
2136 matches = []
2136 matches = []
2137
2137
2138 # FIXME: we should extend our api to return a dict with completions for
2138 # FIXME: we should extend our api to return a dict with completions for
2139 # different types of objects. The rlcomplete() method could then
2139 # different types of objects. The rlcomplete() method could then
2140 # simply collapse the dict into a list for readline, but we'd have
2140 # simply collapse the dict into a list for readline, but we'd have
2141 # richer completion semantics in other environments.
2141 # richer completion semantics in other environments.
2142 is_magic_prefix = len(text) > 0 and text[0] == "%"
2142 is_magic_prefix = len(text) > 0 and text[0] == "%"
2143 completions: Iterable[Any] = []
2143 completions: Iterable[Any] = []
2144 if self.use_jedi and not is_magic_prefix:
2144 if self.use_jedi and not is_magic_prefix:
2145 if not full_text:
2145 if not full_text:
2146 full_text = line_buffer
2146 full_text = line_buffer
2147 completions = self._jedi_matches(
2147 completions = self._jedi_matches(
2148 cursor_pos, cursor_line, full_text)
2148 cursor_pos, cursor_line, full_text)
2149
2149
2150 if self.merge_completions:
2150 if self.merge_completions:
2151 matches = []
2151 matches = []
2152 for matcher in self.matchers:
2152 for matcher in self.matchers:
2153 try:
2153 try:
2154 matches.extend([(m, matcher.__qualname__)
2154 matches.extend([(m, matcher.__qualname__)
2155 for m in matcher(text)])
2155 for m in matcher(text)])
2156 except:
2156 except:
2157 # Show the ugly traceback if the matcher causes an
2157 # Show the ugly traceback if the matcher causes an
2158 # exception, but do NOT crash the kernel!
2158 # exception, but do NOT crash the kernel!
2159 sys.excepthook(*sys.exc_info())
2159 sys.excepthook(*sys.exc_info())
2160 else:
2160 else:
2161 for matcher in self.matchers:
2161 for matcher in self.matchers:
2162 matches = [(m, matcher.__qualname__)
2162 matches = [(m, matcher.__qualname__)
2163 for m in matcher(text)]
2163 for m in matcher(text)]
2164 if matches:
2164 if matches:
2165 break
2165 break
2166
2166
2167 seen = set()
2167 seen = set()
2168 filtered_matches = set()
2168 filtered_matches = set()
2169 for m in matches:
2169 for m in matches:
2170 t, c = m
2170 t, c = m
2171 if t not in seen:
2171 if t not in seen:
2172 filtered_matches.add(m)
2172 filtered_matches.add(m)
2173 seen.add(t)
2173 seen.add(t)
2174
2174
2175 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2175 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2176
2176
2177 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2177 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2178
2178
2179 _filtered_matches = custom_res or _filtered_matches
2179 _filtered_matches = custom_res or _filtered_matches
2180
2180
2181 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2181 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2182 _matches = [m[0] for m in _filtered_matches]
2182 _matches = [m[0] for m in _filtered_matches]
2183 origins = [m[1] for m in _filtered_matches]
2183 origins = [m[1] for m in _filtered_matches]
2184
2184
2185 self.matches = _matches
2185 self.matches = _matches
2186
2186
2187 return _CompleteResult(text, _matches, origins, completions)
2187 return _CompleteResult(text, _matches, origins, completions)
2188
2188
2189 def fwd_unicode_match(self, text:str) -> Tuple[str, Sequence[str]]:
2189 def fwd_unicode_match(self, text:str) -> Tuple[str, Sequence[str]]:
2190 """
2190 """
2191 Forward match a string starting with a backslash with a list of
2191 Forward match a string starting with a backslash with a list of
2192 potential Unicode completions.
2192 potential Unicode completions.
2193
2193
2194 Will compute list list of Unicode character names on first call and cache it.
2194 Will compute list list of Unicode character names on first call and cache it.
2195
2195
2196 Returns
2196 Returns
2197 -------
2197 -------
2198 At tuple with:
2198 At tuple with:
2199 - matched text (empty if no matches)
2199 - matched text (empty if no matches)
2200 - list of potential completions, empty tuple otherwise)
2200 - list of potential completions, empty tuple otherwise)
2201 """
2201 """
2202 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2202 # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
2203 # We could do a faster match using a Trie.
2203 # We could do a faster match using a Trie.
2204
2204
2205 # Using pygtrie the following seem to work:
2205 # Using pygtrie the following seem to work:
2206
2206
2207 # s = PrefixSet()
2207 # s = PrefixSet()
2208
2208
2209 # for c in range(0,0x10FFFF + 1):
2209 # for c in range(0,0x10FFFF + 1):
2210 # try:
2210 # try:
2211 # s.add(unicodedata.name(chr(c)))
2211 # s.add(unicodedata.name(chr(c)))
2212 # except ValueError:
2212 # except ValueError:
2213 # pass
2213 # pass
2214 # [''.join(k) for k in s.iter(prefix)]
2214 # [''.join(k) for k in s.iter(prefix)]
2215
2215
2216 # But need to be timed and adds an extra dependency.
2216 # But need to be timed and adds an extra dependency.
2217
2217
2218 slashpos = text.rfind('\\')
2218 slashpos = text.rfind('\\')
2219 # if text starts with slash
2219 # if text starts with slash
2220 if slashpos > -1:
2220 if slashpos > -1:
2221 # PERF: It's important that we don't access self._unicode_names
2221 # PERF: It's important that we don't access self._unicode_names
2222 # until we're inside this if-block. _unicode_names is lazily
2222 # until we're inside this if-block. _unicode_names is lazily
2223 # initialized, and it takes a user-noticeable amount of time to
2223 # initialized, and it takes a user-noticeable amount of time to
2224 # initialize it, so we don't want to initialize it unless we're
2224 # initialize it, so we don't want to initialize it unless we're
2225 # actually going to use it.
2225 # actually going to use it.
2226 s = text[slashpos + 1 :]
2226 s = text[slashpos + 1 :]
2227 sup = s.upper()
2227 sup = s.upper()
2228 candidates = [x for x in self.unicode_names if x.startswith(sup)]
2228 candidates = [x for x in self.unicode_names if x.startswith(sup)]
2229 if candidates:
2229 if candidates:
2230 return s, candidates
2230 return s, candidates
2231 candidates = [x for x in self.unicode_names if sup in x]
2231 candidates = [x for x in self.unicode_names if sup in x]
2232 if candidates:
2232 if candidates:
2233 return s, candidates
2233 return s, candidates
2234 splitsup = sup.split(" ")
2234 splitsup = sup.split(" ")
2235 candidates = [
2235 candidates = [
2236 x for x in self.unicode_names if all(u in x for u in splitsup)
2236 x for x in self.unicode_names if all(u in x for u in splitsup)
2237 ]
2237 ]
2238 if candidates:
2238 if candidates:
2239 return s, candidates
2239 return s, candidates
2240
2240
2241 return "", ()
2241 return "", ()
2242
2242
2243 # if text does not start with slash
2243 # if text does not start with slash
2244 else:
2244 else:
2245 return '', ()
2245 return '', ()
2246
2246
2247 @property
2247 @property
2248 def unicode_names(self) -> List[str]:
2248 def unicode_names(self) -> List[str]:
2249 """List of names of unicode code points that can be completed.
2249 """List of names of unicode code points that can be completed.
2250
2250
2251 The list is lazily initialized on first access.
2251 The list is lazily initialized on first access.
2252 """
2252 """
2253 if self._unicode_names is None:
2253 if self._unicode_names is None:
2254 names = []
2254 names = []
2255 for c in range(0,0x10FFFF + 1):
2255 for c in range(0,0x10FFFF + 1):
2256 try:
2256 try:
2257 names.append(unicodedata.name(chr(c)))
2257 names.append(unicodedata.name(chr(c)))
2258 except ValueError:
2258 except ValueError:
2259 pass
2259 pass
2260 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2260 self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
2261
2261
2262 return self._unicode_names
2262 return self._unicode_names
2263
2263
2264 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2264 def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
2265 names = []
2265 names = []
2266 for start,stop in ranges:
2266 for start,stop in ranges:
2267 for c in range(start, stop) :
2267 for c in range(start, stop) :
2268 try:
2268 try:
2269 names.append(unicodedata.name(chr(c)))
2269 names.append(unicodedata.name(chr(c)))
2270 except ValueError:
2270 except ValueError:
2271 pass
2271 pass
2272 return names
2272 return names
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,677 +1,677 b''
1 """Various display related classes.
1 """Various display related classes.
2
2
3 Authors : MinRK, gregcaporaso, dannystaple
3 Authors : MinRK, gregcaporaso, dannystaple
4 """
4 """
5 from html import escape as html_escape
5 from html import escape as html_escape
6 from os.path import exists, isfile, splitext, abspath, join, isdir
6 from os.path import exists, isfile, splitext, abspath, join, isdir
7 from os import walk, sep, fsdecode
7 from os import walk, sep, fsdecode
8
8
9 from IPython.core.display import DisplayObject, TextDisplayObject
9 from IPython.core.display import DisplayObject, TextDisplayObject
10
10
11 from typing import Tuple, Iterable
11 from typing import Tuple, Iterable
12
12
13 __all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument',
13 __all__ = ['Audio', 'IFrame', 'YouTubeVideo', 'VimeoVideo', 'ScribdDocument',
14 'FileLink', 'FileLinks', 'Code']
14 'FileLink', 'FileLinks', 'Code']
15
15
16
16
17 class Audio(DisplayObject):
17 class Audio(DisplayObject):
18 """Create an audio object.
18 """Create an audio object.
19
19
20 When this object is returned by an input cell or passed to the
20 When this object is returned by an input cell or passed to the
21 display function, it will result in Audio controls being displayed
21 display function, it will result in Audio controls being displayed
22 in the frontend (only works in the notebook).
22 in the frontend (only works in the notebook).
23
23
24 Parameters
24 Parameters
25 ----------
25 ----------
26 data : numpy array, list, unicode, str or bytes
26 data : numpy array, list, unicode, str or bytes
27 Can be one of
27 Can be one of
28
28
29 * Numpy 1d array containing the desired waveform (mono)
29 * Numpy 1d array containing the desired waveform (mono)
30 * Numpy 2d array containing waveforms for each channel.
30 * Numpy 2d array containing waveforms for each channel.
31 Shape=(NCHAN, NSAMPLES). For the standard channel order, see
31 Shape=(NCHAN, NSAMPLES). For the standard channel order, see
32 http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
32 http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
33 * List of float or integer representing the waveform (mono)
33 * List of float or integer representing the waveform (mono)
34 * String containing the filename
34 * String containing the filename
35 * Bytestring containing raw PCM data or
35 * Bytestring containing raw PCM data or
36 * URL pointing to a file on the web.
36 * URL pointing to a file on the web.
37
37
38 If the array option is used, the waveform will be normalized.
38 If the array option is used, the waveform will be normalized.
39
39
40 If a filename or url is used, the format support will be browser
40 If a filename or url is used, the format support will be browser
41 dependent.
41 dependent.
42 url : unicode
42 url : unicode
43 A URL to download the data from.
43 A URL to download the data from.
44 filename : unicode
44 filename : unicode
45 Path to a local file to load the data from.
45 Path to a local file to load the data from.
46 embed : boolean
46 embed : boolean
47 Should the audio data be embedded using a data URI (True) or should
47 Should the audio data be embedded using a data URI (True) or should
48 the original source be referenced. Set this to True if you want the
48 the original source be referenced. Set this to True if you want the
49 audio to playable later with no internet connection in the notebook.
49 audio to playable later with no internet connection in the notebook.
50
50
51 Default is `True`, unless the keyword argument `url` is set, then
51 Default is `True`, unless the keyword argument `url` is set, then
52 default value is `False`.
52 default value is `False`.
53 rate : integer
53 rate : integer
54 The sampling rate of the raw data.
54 The sampling rate of the raw data.
55 Only required when data parameter is being used as an array
55 Only required when data parameter is being used as an array
56 autoplay : bool
56 autoplay : bool
57 Set to True if the audio should immediately start playing.
57 Set to True if the audio should immediately start playing.
58 Default is `False`.
58 Default is `False`.
59 normalize : bool
59 normalize : bool
60 Whether audio should be normalized (rescaled) to the maximum possible
60 Whether audio should be normalized (rescaled) to the maximum possible
61 range. Default is `True`. When set to `False`, `data` must be between
61 range. Default is `True`. When set to `False`, `data` must be between
62 -1 and 1 (inclusive), otherwise an error is raised.
62 -1 and 1 (inclusive), otherwise an error is raised.
63 Applies only when `data` is a list or array of samples; other types of
63 Applies only when `data` is a list or array of samples; other types of
64 audio are never normalized.
64 audio are never normalized.
65
65
66 Examples
66 Examples
67 --------
67 --------
68
68
69 >>> import pytest
69 >>> import pytest
70 >>> np = pytest.importorskip("numpy")
70 >>> np = pytest.importorskip("numpy")
71
71
72 Generate a sound
72 Generate a sound
73
73
74 >>> import numpy as np
74 >>> import numpy as np
75 >>> framerate = 44100
75 >>> framerate = 44100
76 >>> t = np.linspace(0,5,framerate*5)
76 >>> t = np.linspace(0,5,framerate*5)
77 >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
77 >>> data = np.sin(2*np.pi*220*t) + np.sin(2*np.pi*224*t)
78 >>> Audio(data, rate=framerate)
78 >>> Audio(data, rate=framerate)
79 <IPython.lib.display.Audio object>
79 <IPython.lib.display.Audio object>
80
80
81 Can also do stereo or more channels
81 Can also do stereo or more channels
82
82
83 >>> dataleft = np.sin(2*np.pi*220*t)
83 >>> dataleft = np.sin(2*np.pi*220*t)
84 >>> dataright = np.sin(2*np.pi*224*t)
84 >>> dataright = np.sin(2*np.pi*224*t)
85 >>> Audio([dataleft, dataright], rate=framerate)
85 >>> Audio([dataleft, dataright], rate=framerate)
86 <IPython.lib.display.Audio object>
86 <IPython.lib.display.Audio object>
87
87
88 From URL:
88 From URL:
89
89
90 >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP
90 >>> Audio("http://www.nch.com.au/acm/8k16bitpcm.wav") # doctest: +SKIP
91 >>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP
91 >>> Audio(url="http://www.w3schools.com/html/horse.ogg") # doctest: +SKIP
92
92
93 From a File:
93 From a File:
94
94
95 >>> Audio('/path/to/sound.wav') # doctest: +SKIP
95 >>> Audio('IPython/lib/tests/test.wav') # doctest: +SKIP
96 >>> Audio(filename='/path/to/sound.ogg') # doctest: +SKIP
96 >>> Audio(filename='IPython/lib/tests/test.wav') # doctest: +SKIP
97
97
98 From Bytes:
98 From Bytes:
99
99
100 >>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP
100 >>> Audio(b'RAW_WAV_DATA..') # doctest: +SKIP
101 >>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP
101 >>> Audio(data=b'RAW_WAV_DATA..') # doctest: +SKIP
102
102
103 See Also
103 See Also
104 --------
104 --------
105 ipywidgets.Audio
105 ipywidgets.Audio
106
106
107 AUdio widget with more more flexibility and options.
107 AUdio widget with more more flexibility and options.
108
108
109 """
109 """
110 _read_flags = 'rb'
110 _read_flags = 'rb'
111
111
112 def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False, normalize=True, *,
112 def __init__(self, data=None, filename=None, url=None, embed=None, rate=None, autoplay=False, normalize=True, *,
113 element_id=None):
113 element_id=None):
114 if filename is None and url is None and data is None:
114 if filename is None and url is None and data is None:
115 raise ValueError("No audio data found. Expecting filename, url, or data.")
115 raise ValueError("No audio data found. Expecting filename, url, or data.")
116 if embed is False and url is None:
116 if embed is False and url is None:
117 raise ValueError("No url found. Expecting url when embed=False")
117 raise ValueError("No url found. Expecting url when embed=False")
118
118
119 if url is not None and embed is not True:
119 if url is not None and embed is not True:
120 self.embed = False
120 self.embed = False
121 else:
121 else:
122 self.embed = True
122 self.embed = True
123 self.autoplay = autoplay
123 self.autoplay = autoplay
124 self.element_id = element_id
124 self.element_id = element_id
125 super(Audio, self).__init__(data=data, url=url, filename=filename)
125 super(Audio, self).__init__(data=data, url=url, filename=filename)
126
126
127 if self.data is not None and not isinstance(self.data, bytes):
127 if self.data is not None and not isinstance(self.data, bytes):
128 if rate is None:
128 if rate is None:
129 raise ValueError("rate must be specified when data is a numpy array or list of audio samples.")
129 raise ValueError("rate must be specified when data is a numpy array or list of audio samples.")
130 self.data = Audio._make_wav(data, rate, normalize)
130 self.data = Audio._make_wav(data, rate, normalize)
131
131
132 def reload(self):
132 def reload(self):
133 """Reload the raw data from file or URL."""
133 """Reload the raw data from file or URL."""
134 import mimetypes
134 import mimetypes
135 if self.embed:
135 if self.embed:
136 super(Audio, self).reload()
136 super(Audio, self).reload()
137
137
138 if self.filename is not None:
138 if self.filename is not None:
139 self.mimetype = mimetypes.guess_type(self.filename)[0]
139 self.mimetype = mimetypes.guess_type(self.filename)[0]
140 elif self.url is not None:
140 elif self.url is not None:
141 self.mimetype = mimetypes.guess_type(self.url)[0]
141 self.mimetype = mimetypes.guess_type(self.url)[0]
142 else:
142 else:
143 self.mimetype = "audio/wav"
143 self.mimetype = "audio/wav"
144
144
145 @staticmethod
145 @staticmethod
146 def _make_wav(data, rate, normalize):
146 def _make_wav(data, rate, normalize):
147 """ Transform a numpy array to a PCM bytestring """
147 """ Transform a numpy array to a PCM bytestring """
148 from io import BytesIO
148 from io import BytesIO
149 import wave
149 import wave
150
150
151 try:
151 try:
152 scaled, nchan = Audio._validate_and_normalize_with_numpy(data, normalize)
152 scaled, nchan = Audio._validate_and_normalize_with_numpy(data, normalize)
153 except ImportError:
153 except ImportError:
154 scaled, nchan = Audio._validate_and_normalize_without_numpy(data, normalize)
154 scaled, nchan = Audio._validate_and_normalize_without_numpy(data, normalize)
155
155
156 fp = BytesIO()
156 fp = BytesIO()
157 waveobj = wave.open(fp,mode='wb')
157 waveobj = wave.open(fp,mode='wb')
158 waveobj.setnchannels(nchan)
158 waveobj.setnchannels(nchan)
159 waveobj.setframerate(rate)
159 waveobj.setframerate(rate)
160 waveobj.setsampwidth(2)
160 waveobj.setsampwidth(2)
161 waveobj.setcomptype('NONE','NONE')
161 waveobj.setcomptype('NONE','NONE')
162 waveobj.writeframes(scaled)
162 waveobj.writeframes(scaled)
163 val = fp.getvalue()
163 val = fp.getvalue()
164 waveobj.close()
164 waveobj.close()
165
165
166 return val
166 return val
167
167
168 @staticmethod
168 @staticmethod
169 def _validate_and_normalize_with_numpy(data, normalize) -> Tuple[bytes, int]:
169 def _validate_and_normalize_with_numpy(data, normalize) -> Tuple[bytes, int]:
170 import numpy as np
170 import numpy as np
171
171
172 data = np.array(data, dtype=float)
172 data = np.array(data, dtype=float)
173 if len(data.shape) == 1:
173 if len(data.shape) == 1:
174 nchan = 1
174 nchan = 1
175 elif len(data.shape) == 2:
175 elif len(data.shape) == 2:
176 # In wave files,channels are interleaved. E.g.,
176 # In wave files,channels are interleaved. E.g.,
177 # "L1R1L2R2..." for stereo. See
177 # "L1R1L2R2..." for stereo. See
178 # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
178 # http://msdn.microsoft.com/en-us/library/windows/hardware/dn653308(v=vs.85).aspx
179 # for channel ordering
179 # for channel ordering
180 nchan = data.shape[0]
180 nchan = data.shape[0]
181 data = data.T.ravel()
181 data = data.T.ravel()
182 else:
182 else:
183 raise ValueError('Array audio input must be a 1D or 2D array')
183 raise ValueError('Array audio input must be a 1D or 2D array')
184
184
185 max_abs_value = np.max(np.abs(data))
185 max_abs_value = np.max(np.abs(data))
186 normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
186 normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
187 scaled = data / normalization_factor * 32767
187 scaled = data / normalization_factor * 32767
188 return scaled.astype("<h").tobytes(), nchan
188 return scaled.astype("<h").tobytes(), nchan
189
189
190 @staticmethod
190 @staticmethod
191 def _validate_and_normalize_without_numpy(data, normalize):
191 def _validate_and_normalize_without_numpy(data, normalize):
192 import array
192 import array
193 import sys
193 import sys
194
194
195 data = array.array('f', data)
195 data = array.array('f', data)
196
196
197 try:
197 try:
198 max_abs_value = float(max([abs(x) for x in data]))
198 max_abs_value = float(max([abs(x) for x in data]))
199 except TypeError as e:
199 except TypeError as e:
200 raise TypeError('Only lists of mono audio are '
200 raise TypeError('Only lists of mono audio are '
201 'supported if numpy is not installed') from e
201 'supported if numpy is not installed') from e
202
202
203 normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
203 normalization_factor = Audio._get_normalization_factor(max_abs_value, normalize)
204 scaled = array.array('h', [int(x / normalization_factor * 32767) for x in data])
204 scaled = array.array('h', [int(x / normalization_factor * 32767) for x in data])
205 if sys.byteorder == 'big':
205 if sys.byteorder == 'big':
206 scaled.byteswap()
206 scaled.byteswap()
207 nchan = 1
207 nchan = 1
208 return scaled.tobytes(), nchan
208 return scaled.tobytes(), nchan
209
209
210 @staticmethod
210 @staticmethod
211 def _get_normalization_factor(max_abs_value, normalize):
211 def _get_normalization_factor(max_abs_value, normalize):
212 if not normalize and max_abs_value > 1:
212 if not normalize and max_abs_value > 1:
213 raise ValueError('Audio data must be between -1 and 1 when normalize=False.')
213 raise ValueError('Audio data must be between -1 and 1 when normalize=False.')
214 return max_abs_value if normalize else 1
214 return max_abs_value if normalize else 1
215
215
216 def _data_and_metadata(self):
216 def _data_and_metadata(self):
217 """shortcut for returning metadata with url information, if defined"""
217 """shortcut for returning metadata with url information, if defined"""
218 md = {}
218 md = {}
219 if self.url:
219 if self.url:
220 md['url'] = self.url
220 md['url'] = self.url
221 if md:
221 if md:
222 return self.data, md
222 return self.data, md
223 else:
223 else:
224 return self.data
224 return self.data
225
225
226 def _repr_html_(self):
226 def _repr_html_(self):
227 src = """
227 src = """
228 <audio {element_id} controls="controls" {autoplay}>
228 <audio {element_id} controls="controls" {autoplay}>
229 <source src="{src}" type="{type}" />
229 <source src="{src}" type="{type}" />
230 Your browser does not support the audio element.
230 Your browser does not support the audio element.
231 </audio>
231 </audio>
232 """
232 """
233 return src.format(src=self.src_attr(), type=self.mimetype, autoplay=self.autoplay_attr(),
233 return src.format(src=self.src_attr(), type=self.mimetype, autoplay=self.autoplay_attr(),
234 element_id=self.element_id_attr())
234 element_id=self.element_id_attr())
235
235
236 def src_attr(self):
236 def src_attr(self):
237 import base64
237 import base64
238 if self.embed and (self.data is not None):
238 if self.embed and (self.data is not None):
239 data = base64=base64.b64encode(self.data).decode('ascii')
239 data = base64=base64.b64encode(self.data).decode('ascii')
240 return """data:{type};base64,{base64}""".format(type=self.mimetype,
240 return """data:{type};base64,{base64}""".format(type=self.mimetype,
241 base64=data)
241 base64=data)
242 elif self.url is not None:
242 elif self.url is not None:
243 return self.url
243 return self.url
244 else:
244 else:
245 return ""
245 return ""
246
246
247 def autoplay_attr(self):
247 def autoplay_attr(self):
248 if(self.autoplay):
248 if(self.autoplay):
249 return 'autoplay="autoplay"'
249 return 'autoplay="autoplay"'
250 else:
250 else:
251 return ''
251 return ''
252
252
253 def element_id_attr(self):
253 def element_id_attr(self):
254 if (self.element_id):
254 if (self.element_id):
255 return 'id="{element_id}"'.format(element_id=self.element_id)
255 return 'id="{element_id}"'.format(element_id=self.element_id)
256 else:
256 else:
257 return ''
257 return ''
258
258
259 class IFrame(object):
259 class IFrame(object):
260 """
260 """
261 Generic class to embed an iframe in an IPython notebook
261 Generic class to embed an iframe in an IPython notebook
262 """
262 """
263
263
264 iframe = """
264 iframe = """
265 <iframe
265 <iframe
266 width="{width}"
266 width="{width}"
267 height="{height}"
267 height="{height}"
268 src="{src}{params}"
268 src="{src}{params}"
269 frameborder="0"
269 frameborder="0"
270 allowfullscreen
270 allowfullscreen
271 {extras}
271 {extras}
272 ></iframe>
272 ></iframe>
273 """
273 """
274
274
275 def __init__(self, src, width, height, extras: Iterable[str] = None, **kwargs):
275 def __init__(self, src, width, height, extras: Iterable[str] = None, **kwargs):
276 if extras is None:
276 if extras is None:
277 extras = []
277 extras = []
278
278
279 self.src = src
279 self.src = src
280 self.width = width
280 self.width = width
281 self.height = height
281 self.height = height
282 self.extras = extras
282 self.extras = extras
283 self.params = kwargs
283 self.params = kwargs
284
284
285 def _repr_html_(self):
285 def _repr_html_(self):
286 """return the embed iframe"""
286 """return the embed iframe"""
287 if self.params:
287 if self.params:
288 from urllib.parse import urlencode
288 from urllib.parse import urlencode
289 params = "?" + urlencode(self.params)
289 params = "?" + urlencode(self.params)
290 else:
290 else:
291 params = ""
291 params = ""
292 return self.iframe.format(
292 return self.iframe.format(
293 src=self.src,
293 src=self.src,
294 width=self.width,
294 width=self.width,
295 height=self.height,
295 height=self.height,
296 params=params,
296 params=params,
297 extras=" ".join(self.extras),
297 extras=" ".join(self.extras),
298 )
298 )
299
299
300
300
301 class YouTubeVideo(IFrame):
301 class YouTubeVideo(IFrame):
302 """Class for embedding a YouTube Video in an IPython session, based on its video id.
302 """Class for embedding a YouTube Video in an IPython session, based on its video id.
303
303
304 e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
304 e.g. to embed the video from https://www.youtube.com/watch?v=foo , you would
305 do::
305 do::
306
306
307 vid = YouTubeVideo("foo")
307 vid = YouTubeVideo("foo")
308 display(vid)
308 display(vid)
309
309
310 To start from 30 seconds::
310 To start from 30 seconds::
311
311
312 vid = YouTubeVideo("abc", start=30)
312 vid = YouTubeVideo("abc", start=30)
313 display(vid)
313 display(vid)
314
314
315 To calculate seconds from time as hours, minutes, seconds use
315 To calculate seconds from time as hours, minutes, seconds use
316 :class:`datetime.timedelta`::
316 :class:`datetime.timedelta`::
317
317
318 start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
318 start=int(timedelta(hours=1, minutes=46, seconds=40).total_seconds())
319
319
320 Other parameters can be provided as documented at
320 Other parameters can be provided as documented at
321 https://developers.google.com/youtube/player_parameters#Parameters
321 https://developers.google.com/youtube/player_parameters#Parameters
322
322
323 When converting the notebook using nbconvert, a jpeg representation of the video
323 When converting the notebook using nbconvert, a jpeg representation of the video
324 will be inserted in the document.
324 will be inserted in the document.
325 """
325 """
326
326
327 def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs):
327 def __init__(self, id, width=400, height=300, allow_autoplay=False, **kwargs):
328 self.id=id
328 self.id=id
329 src = "https://www.youtube.com/embed/{0}".format(id)
329 src = "https://www.youtube.com/embed/{0}".format(id)
330 if allow_autoplay:
330 if allow_autoplay:
331 extras = list(kwargs.get("extras", [])) + ['allow="autoplay"']
331 extras = list(kwargs.get("extras", [])) + ['allow="autoplay"']
332 kwargs.update(autoplay=1, extras=extras)
332 kwargs.update(autoplay=1, extras=extras)
333 super(YouTubeVideo, self).__init__(src, width, height, **kwargs)
333 super(YouTubeVideo, self).__init__(src, width, height, **kwargs)
334
334
335 def _repr_jpeg_(self):
335 def _repr_jpeg_(self):
336 # Deferred import
336 # Deferred import
337 from urllib.request import urlopen
337 from urllib.request import urlopen
338
338
339 try:
339 try:
340 return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read()
340 return urlopen("https://img.youtube.com/vi/{id}/hqdefault.jpg".format(id=self.id)).read()
341 except IOError:
341 except IOError:
342 return None
342 return None
343
343
344 class VimeoVideo(IFrame):
344 class VimeoVideo(IFrame):
345 """
345 """
346 Class for embedding a Vimeo video in an IPython session, based on its video id.
346 Class for embedding a Vimeo video in an IPython session, based on its video id.
347 """
347 """
348
348
349 def __init__(self, id, width=400, height=300, **kwargs):
349 def __init__(self, id, width=400, height=300, **kwargs):
350 src="https://player.vimeo.com/video/{0}".format(id)
350 src="https://player.vimeo.com/video/{0}".format(id)
351 super(VimeoVideo, self).__init__(src, width, height, **kwargs)
351 super(VimeoVideo, self).__init__(src, width, height, **kwargs)
352
352
353 class ScribdDocument(IFrame):
353 class ScribdDocument(IFrame):
354 """
354 """
355 Class for embedding a Scribd document in an IPython session
355 Class for embedding a Scribd document in an IPython session
356
356
357 Use the start_page params to specify a starting point in the document
357 Use the start_page params to specify a starting point in the document
358 Use the view_mode params to specify display type one off scroll | slideshow | book
358 Use the view_mode params to specify display type one off scroll | slideshow | book
359
359
360 e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
360 e.g to Display Wes' foundational paper about PANDAS in book mode from page 3
361
361
362 ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
362 ScribdDocument(71048089, width=800, height=400, start_page=3, view_mode="book")
363 """
363 """
364
364
365 def __init__(self, id, width=400, height=300, **kwargs):
365 def __init__(self, id, width=400, height=300, **kwargs):
366 src="https://www.scribd.com/embeds/{0}/content".format(id)
366 src="https://www.scribd.com/embeds/{0}/content".format(id)
367 super(ScribdDocument, self).__init__(src, width, height, **kwargs)
367 super(ScribdDocument, self).__init__(src, width, height, **kwargs)
368
368
369 class FileLink(object):
369 class FileLink(object):
370 """Class for embedding a local file link in an IPython session, based on path
370 """Class for embedding a local file link in an IPython session, based on path
371
371
372 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
372 e.g. to embed a link that was generated in the IPython notebook as my/data.txt
373
373
374 you would do::
374 you would do::
375
375
376 local_file = FileLink("my/data.txt")
376 local_file = FileLink("my/data.txt")
377 display(local_file)
377 display(local_file)
378
378
379 or in the HTML notebook, just::
379 or in the HTML notebook, just::
380
380
381 FileLink("my/data.txt")
381 FileLink("my/data.txt")
382 """
382 """
383
383
384 html_link_str = "<a href='%s' target='_blank'>%s</a>"
384 html_link_str = "<a href='%s' target='_blank'>%s</a>"
385
385
386 def __init__(self,
386 def __init__(self,
387 path,
387 path,
388 url_prefix='',
388 url_prefix='',
389 result_html_prefix='',
389 result_html_prefix='',
390 result_html_suffix='<br>'):
390 result_html_suffix='<br>'):
391 """
391 """
392 Parameters
392 Parameters
393 ----------
393 ----------
394 path : str
394 path : str
395 path to the file or directory that should be formatted
395 path to the file or directory that should be formatted
396 url_prefix : str
396 url_prefix : str
397 prefix to be prepended to all files to form a working link [default:
397 prefix to be prepended to all files to form a working link [default:
398 '']
398 '']
399 result_html_prefix : str
399 result_html_prefix : str
400 text to append to beginning to link [default: '']
400 text to append to beginning to link [default: '']
401 result_html_suffix : str
401 result_html_suffix : str
402 text to append at the end of link [default: '<br>']
402 text to append at the end of link [default: '<br>']
403 """
403 """
404 if isdir(path):
404 if isdir(path):
405 raise ValueError("Cannot display a directory using FileLink. "
405 raise ValueError("Cannot display a directory using FileLink. "
406 "Use FileLinks to display '%s'." % path)
406 "Use FileLinks to display '%s'." % path)
407 self.path = fsdecode(path)
407 self.path = fsdecode(path)
408 self.url_prefix = url_prefix
408 self.url_prefix = url_prefix
409 self.result_html_prefix = result_html_prefix
409 self.result_html_prefix = result_html_prefix
410 self.result_html_suffix = result_html_suffix
410 self.result_html_suffix = result_html_suffix
411
411
412 def _format_path(self):
412 def _format_path(self):
413 fp = ''.join([self.url_prefix, html_escape(self.path)])
413 fp = ''.join([self.url_prefix, html_escape(self.path)])
414 return ''.join([self.result_html_prefix,
414 return ''.join([self.result_html_prefix,
415 self.html_link_str % \
415 self.html_link_str % \
416 (fp, html_escape(self.path, quote=False)),
416 (fp, html_escape(self.path, quote=False)),
417 self.result_html_suffix])
417 self.result_html_suffix])
418
418
419 def _repr_html_(self):
419 def _repr_html_(self):
420 """return html link to file
420 """return html link to file
421 """
421 """
422 if not exists(self.path):
422 if not exists(self.path):
423 return ("Path (<tt>%s</tt>) doesn't exist. "
423 return ("Path (<tt>%s</tt>) doesn't exist. "
424 "It may still be in the process of "
424 "It may still be in the process of "
425 "being generated, or you may have the "
425 "being generated, or you may have the "
426 "incorrect path." % self.path)
426 "incorrect path." % self.path)
427
427
428 return self._format_path()
428 return self._format_path()
429
429
430 def __repr__(self):
430 def __repr__(self):
431 """return absolute path to file
431 """return absolute path to file
432 """
432 """
433 return abspath(self.path)
433 return abspath(self.path)
434
434
435 class FileLinks(FileLink):
435 class FileLinks(FileLink):
436 """Class for embedding local file links in an IPython session, based on path
436 """Class for embedding local file links in an IPython session, based on path
437
437
438 e.g. to embed links to files that were generated in the IPython notebook
438 e.g. to embed links to files that were generated in the IPython notebook
439 under ``my/data``, you would do::
439 under ``my/data``, you would do::
440
440
441 local_files = FileLinks("my/data")
441 local_files = FileLinks("my/data")
442 display(local_files)
442 display(local_files)
443
443
444 or in the HTML notebook, just::
444 or in the HTML notebook, just::
445
445
446 FileLinks("my/data")
446 FileLinks("my/data")
447 """
447 """
448 def __init__(self,
448 def __init__(self,
449 path,
449 path,
450 url_prefix='',
450 url_prefix='',
451 included_suffixes=None,
451 included_suffixes=None,
452 result_html_prefix='',
452 result_html_prefix='',
453 result_html_suffix='<br>',
453 result_html_suffix='<br>',
454 notebook_display_formatter=None,
454 notebook_display_formatter=None,
455 terminal_display_formatter=None,
455 terminal_display_formatter=None,
456 recursive=True):
456 recursive=True):
457 """
457 """
458 See :class:`FileLink` for the ``path``, ``url_prefix``,
458 See :class:`FileLink` for the ``path``, ``url_prefix``,
459 ``result_html_prefix`` and ``result_html_suffix`` parameters.
459 ``result_html_prefix`` and ``result_html_suffix`` parameters.
460
460
461 included_suffixes : list
461 included_suffixes : list
462 Filename suffixes to include when formatting output [default: include
462 Filename suffixes to include when formatting output [default: include
463 all files]
463 all files]
464
464
465 notebook_display_formatter : function
465 notebook_display_formatter : function
466 Used to format links for display in the notebook. See discussion of
466 Used to format links for display in the notebook. See discussion of
467 formatter functions below.
467 formatter functions below.
468
468
469 terminal_display_formatter : function
469 terminal_display_formatter : function
470 Used to format links for display in the terminal. See discussion of
470 Used to format links for display in the terminal. See discussion of
471 formatter functions below.
471 formatter functions below.
472
472
473 Formatter functions must be of the form::
473 Formatter functions must be of the form::
474
474
475 f(dirname, fnames, included_suffixes)
475 f(dirname, fnames, included_suffixes)
476
476
477 dirname : str
477 dirname : str
478 The name of a directory
478 The name of a directory
479 fnames : list
479 fnames : list
480 The files in that directory
480 The files in that directory
481 included_suffixes : list
481 included_suffixes : list
482 The file suffixes that should be included in the output (passing None
482 The file suffixes that should be included in the output (passing None
483 meansto include all suffixes in the output in the built-in formatters)
483 meansto include all suffixes in the output in the built-in formatters)
484 recursive : boolean
484 recursive : boolean
485 Whether to recurse into subdirectories. Default is True.
485 Whether to recurse into subdirectories. Default is True.
486
486
487 The function should return a list of lines that will be printed in the
487 The function should return a list of lines that will be printed in the
488 notebook (if passing notebook_display_formatter) or the terminal (if
488 notebook (if passing notebook_display_formatter) or the terminal (if
489 passing terminal_display_formatter). This function is iterated over for
489 passing terminal_display_formatter). This function is iterated over for
490 each directory in self.path. Default formatters are in place, can be
490 each directory in self.path. Default formatters are in place, can be
491 passed here to support alternative formatting.
491 passed here to support alternative formatting.
492
492
493 """
493 """
494 if isfile(path):
494 if isfile(path):
495 raise ValueError("Cannot display a file using FileLinks. "
495 raise ValueError("Cannot display a file using FileLinks. "
496 "Use FileLink to display '%s'." % path)
496 "Use FileLink to display '%s'." % path)
497 self.included_suffixes = included_suffixes
497 self.included_suffixes = included_suffixes
498 # remove trailing slashes for more consistent output formatting
498 # remove trailing slashes for more consistent output formatting
499 path = path.rstrip('/')
499 path = path.rstrip('/')
500
500
501 self.path = path
501 self.path = path
502 self.url_prefix = url_prefix
502 self.url_prefix = url_prefix
503 self.result_html_prefix = result_html_prefix
503 self.result_html_prefix = result_html_prefix
504 self.result_html_suffix = result_html_suffix
504 self.result_html_suffix = result_html_suffix
505
505
506 self.notebook_display_formatter = \
506 self.notebook_display_formatter = \
507 notebook_display_formatter or self._get_notebook_display_formatter()
507 notebook_display_formatter or self._get_notebook_display_formatter()
508 self.terminal_display_formatter = \
508 self.terminal_display_formatter = \
509 terminal_display_formatter or self._get_terminal_display_formatter()
509 terminal_display_formatter or self._get_terminal_display_formatter()
510
510
511 self.recursive = recursive
511 self.recursive = recursive
512
512
513 def _get_display_formatter(self,
513 def _get_display_formatter(self,
514 dirname_output_format,
514 dirname_output_format,
515 fname_output_format,
515 fname_output_format,
516 fp_format,
516 fp_format,
517 fp_cleaner=None):
517 fp_cleaner=None):
518 """ generate built-in formatter function
518 """ generate built-in formatter function
519
519
520 this is used to define both the notebook and terminal built-in
520 this is used to define both the notebook and terminal built-in
521 formatters as they only differ by some wrapper text for each entry
521 formatters as they only differ by some wrapper text for each entry
522
522
523 dirname_output_format: string to use for formatting directory
523 dirname_output_format: string to use for formatting directory
524 names, dirname will be substituted for a single "%s" which
524 names, dirname will be substituted for a single "%s" which
525 must appear in this string
525 must appear in this string
526 fname_output_format: string to use for formatting file names,
526 fname_output_format: string to use for formatting file names,
527 if a single "%s" appears in the string, fname will be substituted
527 if a single "%s" appears in the string, fname will be substituted
528 if two "%s" appear in the string, the path to fname will be
528 if two "%s" appear in the string, the path to fname will be
529 substituted for the first and fname will be substituted for the
529 substituted for the first and fname will be substituted for the
530 second
530 second
531 fp_format: string to use for formatting filepaths, must contain
531 fp_format: string to use for formatting filepaths, must contain
532 exactly two "%s" and the dirname will be substituted for the first
532 exactly two "%s" and the dirname will be substituted for the first
533 and fname will be substituted for the second
533 and fname will be substituted for the second
534 """
534 """
535 def f(dirname, fnames, included_suffixes=None):
535 def f(dirname, fnames, included_suffixes=None):
536 result = []
536 result = []
537 # begin by figuring out which filenames, if any,
537 # begin by figuring out which filenames, if any,
538 # are going to be displayed
538 # are going to be displayed
539 display_fnames = []
539 display_fnames = []
540 for fname in fnames:
540 for fname in fnames:
541 if (isfile(join(dirname,fname)) and
541 if (isfile(join(dirname,fname)) and
542 (included_suffixes is None or
542 (included_suffixes is None or
543 splitext(fname)[1] in included_suffixes)):
543 splitext(fname)[1] in included_suffixes)):
544 display_fnames.append(fname)
544 display_fnames.append(fname)
545
545
546 if len(display_fnames) == 0:
546 if len(display_fnames) == 0:
547 # if there are no filenames to display, don't print anything
547 # if there are no filenames to display, don't print anything
548 # (not even the directory name)
548 # (not even the directory name)
549 pass
549 pass
550 else:
550 else:
551 # otherwise print the formatted directory name followed by
551 # otherwise print the formatted directory name followed by
552 # the formatted filenames
552 # the formatted filenames
553 dirname_output_line = dirname_output_format % dirname
553 dirname_output_line = dirname_output_format % dirname
554 result.append(dirname_output_line)
554 result.append(dirname_output_line)
555 for fname in display_fnames:
555 for fname in display_fnames:
556 fp = fp_format % (dirname,fname)
556 fp = fp_format % (dirname,fname)
557 if fp_cleaner is not None:
557 if fp_cleaner is not None:
558 fp = fp_cleaner(fp)
558 fp = fp_cleaner(fp)
559 try:
559 try:
560 # output can include both a filepath and a filename...
560 # output can include both a filepath and a filename...
561 fname_output_line = fname_output_format % (fp, fname)
561 fname_output_line = fname_output_format % (fp, fname)
562 except TypeError:
562 except TypeError:
563 # ... or just a single filepath
563 # ... or just a single filepath
564 fname_output_line = fname_output_format % fname
564 fname_output_line = fname_output_format % fname
565 result.append(fname_output_line)
565 result.append(fname_output_line)
566 return result
566 return result
567 return f
567 return f
568
568
569 def _get_notebook_display_formatter(self,
569 def _get_notebook_display_formatter(self,
570 spacer="&nbsp;&nbsp;"):
570 spacer="&nbsp;&nbsp;"):
571 """ generate function to use for notebook formatting
571 """ generate function to use for notebook formatting
572 """
572 """
573 dirname_output_format = \
573 dirname_output_format = \
574 self.result_html_prefix + "%s/" + self.result_html_suffix
574 self.result_html_prefix + "%s/" + self.result_html_suffix
575 fname_output_format = \
575 fname_output_format = \
576 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
576 self.result_html_prefix + spacer + self.html_link_str + self.result_html_suffix
577 fp_format = self.url_prefix + '%s/%s'
577 fp_format = self.url_prefix + '%s/%s'
578 if sep == "\\":
578 if sep == "\\":
579 # Working on a platform where the path separator is "\", so
579 # Working on a platform where the path separator is "\", so
580 # must convert these to "/" for generating a URI
580 # must convert these to "/" for generating a URI
581 def fp_cleaner(fp):
581 def fp_cleaner(fp):
582 # Replace all occurrences of backslash ("\") with a forward
582 # Replace all occurrences of backslash ("\") with a forward
583 # slash ("/") - this is necessary on windows when a path is
583 # slash ("/") - this is necessary on windows when a path is
584 # provided as input, but we must link to a URI
584 # provided as input, but we must link to a URI
585 return fp.replace('\\','/')
585 return fp.replace('\\','/')
586 else:
586 else:
587 fp_cleaner = None
587 fp_cleaner = None
588
588
589 return self._get_display_formatter(dirname_output_format,
589 return self._get_display_formatter(dirname_output_format,
590 fname_output_format,
590 fname_output_format,
591 fp_format,
591 fp_format,
592 fp_cleaner)
592 fp_cleaner)
593
593
594 def _get_terminal_display_formatter(self,
594 def _get_terminal_display_formatter(self,
595 spacer=" "):
595 spacer=" "):
596 """ generate function to use for terminal formatting
596 """ generate function to use for terminal formatting
597 """
597 """
598 dirname_output_format = "%s/"
598 dirname_output_format = "%s/"
599 fname_output_format = spacer + "%s"
599 fname_output_format = spacer + "%s"
600 fp_format = '%s/%s'
600 fp_format = '%s/%s'
601
601
602 return self._get_display_formatter(dirname_output_format,
602 return self._get_display_formatter(dirname_output_format,
603 fname_output_format,
603 fname_output_format,
604 fp_format)
604 fp_format)
605
605
606 def _format_path(self):
606 def _format_path(self):
607 result_lines = []
607 result_lines = []
608 if self.recursive:
608 if self.recursive:
609 walked_dir = list(walk(self.path))
609 walked_dir = list(walk(self.path))
610 else:
610 else:
611 walked_dir = [next(walk(self.path))]
611 walked_dir = [next(walk(self.path))]
612 walked_dir.sort()
612 walked_dir.sort()
613 for dirname, subdirs, fnames in walked_dir:
613 for dirname, subdirs, fnames in walked_dir:
614 result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
614 result_lines += self.notebook_display_formatter(dirname, fnames, self.included_suffixes)
615 return '\n'.join(result_lines)
615 return '\n'.join(result_lines)
616
616
617 def __repr__(self):
617 def __repr__(self):
618 """return newline-separated absolute paths
618 """return newline-separated absolute paths
619 """
619 """
620 result_lines = []
620 result_lines = []
621 if self.recursive:
621 if self.recursive:
622 walked_dir = list(walk(self.path))
622 walked_dir = list(walk(self.path))
623 else:
623 else:
624 walked_dir = [next(walk(self.path))]
624 walked_dir = [next(walk(self.path))]
625 walked_dir.sort()
625 walked_dir.sort()
626 for dirname, subdirs, fnames in walked_dir:
626 for dirname, subdirs, fnames in walked_dir:
627 result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
627 result_lines += self.terminal_display_formatter(dirname, fnames, self.included_suffixes)
628 return '\n'.join(result_lines)
628 return '\n'.join(result_lines)
629
629
630
630
631 class Code(TextDisplayObject):
631 class Code(TextDisplayObject):
632 """Display syntax-highlighted source code.
632 """Display syntax-highlighted source code.
633
633
634 This uses Pygments to highlight the code for HTML and Latex output.
634 This uses Pygments to highlight the code for HTML and Latex output.
635
635
636 Parameters
636 Parameters
637 ----------
637 ----------
638 data : str
638 data : str
639 The code as a string
639 The code as a string
640 url : str
640 url : str
641 A URL to fetch the code from
641 A URL to fetch the code from
642 filename : str
642 filename : str
643 A local filename to load the code from
643 A local filename to load the code from
644 language : str
644 language : str
645 The short name of a Pygments lexer to use for highlighting.
645 The short name of a Pygments lexer to use for highlighting.
646 If not specified, it will guess the lexer based on the filename
646 If not specified, it will guess the lexer based on the filename
647 or the code. Available lexers: http://pygments.org/docs/lexers/
647 or the code. Available lexers: http://pygments.org/docs/lexers/
648 """
648 """
649 def __init__(self, data=None, url=None, filename=None, language=None):
649 def __init__(self, data=None, url=None, filename=None, language=None):
650 self.language = language
650 self.language = language
651 super().__init__(data=data, url=url, filename=filename)
651 super().__init__(data=data, url=url, filename=filename)
652
652
653 def _get_lexer(self):
653 def _get_lexer(self):
654 if self.language:
654 if self.language:
655 from pygments.lexers import get_lexer_by_name
655 from pygments.lexers import get_lexer_by_name
656 return get_lexer_by_name(self.language)
656 return get_lexer_by_name(self.language)
657 elif self.filename:
657 elif self.filename:
658 from pygments.lexers import get_lexer_for_filename
658 from pygments.lexers import get_lexer_for_filename
659 return get_lexer_for_filename(self.filename)
659 return get_lexer_for_filename(self.filename)
660 else:
660 else:
661 from pygments.lexers import guess_lexer
661 from pygments.lexers import guess_lexer
662 return guess_lexer(self.data)
662 return guess_lexer(self.data)
663
663
664 def __repr__(self):
664 def __repr__(self):
665 return self.data
665 return self.data
666
666
667 def _repr_html_(self):
667 def _repr_html_(self):
668 from pygments import highlight
668 from pygments import highlight
669 from pygments.formatters import HtmlFormatter
669 from pygments.formatters import HtmlFormatter
670 fmt = HtmlFormatter()
670 fmt = HtmlFormatter()
671 style = '<style>{}</style>'.format(fmt.get_style_defs('.output_html'))
671 style = '<style>{}</style>'.format(fmt.get_style_defs('.output_html'))
672 return style + highlight(self.data, self._get_lexer(), fmt)
672 return style + highlight(self.data, self._get_lexer(), fmt)
673
673
674 def _repr_latex_(self):
674 def _repr_latex_(self):
675 from pygments import highlight
675 from pygments import highlight
676 from pygments.formatters import LatexFormatter
676 from pygments.formatters import LatexFormatter
677 return highlight(self.data, self._get_lexer(), LatexFormatter())
677 return highlight(self.data, self._get_lexer(), LatexFormatter())
@@ -1,342 +1,342 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The :class:`~IPython.core.application.Application` object for the command
4 The :class:`~traitlets.config.application.Application` object for the command
5 line :command:`ipython` program.
5 line :command:`ipython` program.
6 """
6 """
7
7
8 # Copyright (c) IPython Development Team.
8 # Copyright (c) IPython Development Team.
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10
10
11
11
12 import logging
12 import logging
13 import os
13 import os
14 import sys
14 import sys
15 import warnings
15 import warnings
16
16
17 from traitlets.config.loader import Config
17 from traitlets.config.loader import Config
18 from traitlets.config.application import boolean_flag, catch_config_error
18 from traitlets.config.application import boolean_flag, catch_config_error
19 from IPython.core import release
19 from IPython.core import release
20 from IPython.core import usage
20 from IPython.core import usage
21 from IPython.core.completer import IPCompleter
21 from IPython.core.completer import IPCompleter
22 from IPython.core.crashhandler import CrashHandler
22 from IPython.core.crashhandler import CrashHandler
23 from IPython.core.formatters import PlainTextFormatter
23 from IPython.core.formatters import PlainTextFormatter
24 from IPython.core.history import HistoryManager
24 from IPython.core.history import HistoryManager
25 from IPython.core.application import (
25 from IPython.core.application import (
26 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
26 ProfileDir, BaseIPythonApplication, base_flags, base_aliases
27 )
27 )
28 from IPython.core.magic import MagicsManager
28 from IPython.core.magic import MagicsManager
29 from IPython.core.magics import (
29 from IPython.core.magics import (
30 ScriptMagics, LoggingMagics
30 ScriptMagics, LoggingMagics
31 )
31 )
32 from IPython.core.shellapp import (
32 from IPython.core.shellapp import (
33 InteractiveShellApp, shell_flags, shell_aliases
33 InteractiveShellApp, shell_flags, shell_aliases
34 )
34 )
35 from IPython.extensions.storemagic import StoreMagics
35 from IPython.extensions.storemagic import StoreMagics
36 from .interactiveshell import TerminalInteractiveShell
36 from .interactiveshell import TerminalInteractiveShell
37 from IPython.paths import get_ipython_dir
37 from IPython.paths import get_ipython_dir
38 from traitlets import (
38 from traitlets import (
39 Bool, List, default, observe, Type
39 Bool, List, default, observe, Type
40 )
40 )
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Globals, utilities and helpers
43 # Globals, utilities and helpers
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45
45
46 _examples = """
46 _examples = """
47 ipython --matplotlib # enable matplotlib integration
47 ipython --matplotlib # enable matplotlib integration
48 ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
48 ipython --matplotlib=qt # enable matplotlib integration with qt4 backend
49
49
50 ipython --log-level=DEBUG # set logging to DEBUG
50 ipython --log-level=DEBUG # set logging to DEBUG
51 ipython --profile=foo # start with profile foo
51 ipython --profile=foo # start with profile foo
52
52
53 ipython profile create foo # create profile foo w/ default config files
53 ipython profile create foo # create profile foo w/ default config files
54 ipython help profile # show the help for the profile subcmd
54 ipython help profile # show the help for the profile subcmd
55
55
56 ipython locate # print the path to the IPython directory
56 ipython locate # print the path to the IPython directory
57 ipython locate profile foo # print the path to the directory for profile `foo`
57 ipython locate profile foo # print the path to the directory for profile `foo`
58 """
58 """
59
59
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61 # Crash handler for this application
61 # Crash handler for this application
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63
63
64 class IPAppCrashHandler(CrashHandler):
64 class IPAppCrashHandler(CrashHandler):
65 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
65 """sys.excepthook for IPython itself, leaves a detailed report on disk."""
66
66
67 def __init__(self, app):
67 def __init__(self, app):
68 contact_name = release.author
68 contact_name = release.author
69 contact_email = release.author_email
69 contact_email = release.author_email
70 bug_tracker = 'https://github.com/ipython/ipython/issues'
70 bug_tracker = 'https://github.com/ipython/ipython/issues'
71 super(IPAppCrashHandler,self).__init__(
71 super(IPAppCrashHandler,self).__init__(
72 app, contact_name, contact_email, bug_tracker
72 app, contact_name, contact_email, bug_tracker
73 )
73 )
74
74
75 def make_report(self,traceback):
75 def make_report(self,traceback):
76 """Return a string containing a crash report."""
76 """Return a string containing a crash report."""
77
77
78 sec_sep = self.section_sep
78 sec_sep = self.section_sep
79 # Start with parent report
79 # Start with parent report
80 report = [super(IPAppCrashHandler, self).make_report(traceback)]
80 report = [super(IPAppCrashHandler, self).make_report(traceback)]
81 # Add interactive-specific info we may have
81 # Add interactive-specific info we may have
82 rpt_add = report.append
82 rpt_add = report.append
83 try:
83 try:
84 rpt_add(sec_sep+"History of session input:")
84 rpt_add(sec_sep+"History of session input:")
85 for line in self.app.shell.user_ns['_ih']:
85 for line in self.app.shell.user_ns['_ih']:
86 rpt_add(line)
86 rpt_add(line)
87 rpt_add('\n*** Last line of input (may not be in above history):\n')
87 rpt_add('\n*** Last line of input (may not be in above history):\n')
88 rpt_add(self.app.shell._last_input_line+'\n')
88 rpt_add(self.app.shell._last_input_line+'\n')
89 except:
89 except:
90 pass
90 pass
91
91
92 return ''.join(report)
92 return ''.join(report)
93
93
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95 # Aliases and Flags
95 # Aliases and Flags
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 flags = dict(base_flags)
97 flags = dict(base_flags)
98 flags.update(shell_flags)
98 flags.update(shell_flags)
99 frontend_flags = {}
99 frontend_flags = {}
100 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
100 addflag = lambda *args: frontend_flags.update(boolean_flag(*args))
101 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
101 addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
102 'Turn on auto editing of files with syntax errors.',
102 'Turn on auto editing of files with syntax errors.',
103 'Turn off auto editing of files with syntax errors.'
103 'Turn off auto editing of files with syntax errors.'
104 )
104 )
105 addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
105 addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
106 "Force simple minimal prompt using `raw_input`",
106 "Force simple minimal prompt using `raw_input`",
107 "Use a rich interactive prompt with prompt_toolkit",
107 "Use a rich interactive prompt with prompt_toolkit",
108 )
108 )
109
109
110 addflag('banner', 'TerminalIPythonApp.display_banner',
110 addflag('banner', 'TerminalIPythonApp.display_banner',
111 "Display a banner upon starting IPython.",
111 "Display a banner upon starting IPython.",
112 "Don't display a banner upon starting IPython."
112 "Don't display a banner upon starting IPython."
113 )
113 )
114 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
114 addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit',
115 """Set to confirm when you try to exit IPython with an EOF (Control-D
115 """Set to confirm when you try to exit IPython with an EOF (Control-D
116 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
116 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
117 you can force a direct exit without any confirmation.""",
117 you can force a direct exit without any confirmation.""",
118 "Don't prompt the user when exiting."
118 "Don't prompt the user when exiting."
119 )
119 )
120 addflag('term-title', 'TerminalInteractiveShell.term_title',
120 addflag('term-title', 'TerminalInteractiveShell.term_title',
121 "Enable auto setting the terminal title.",
121 "Enable auto setting the terminal title.",
122 "Disable auto setting the terminal title."
122 "Disable auto setting the terminal title."
123 )
123 )
124 classic_config = Config()
124 classic_config = Config()
125 classic_config.InteractiveShell.cache_size = 0
125 classic_config.InteractiveShell.cache_size = 0
126 classic_config.PlainTextFormatter.pprint = False
126 classic_config.PlainTextFormatter.pprint = False
127 classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
127 classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
128 classic_config.InteractiveShell.separate_in = ''
128 classic_config.InteractiveShell.separate_in = ''
129 classic_config.InteractiveShell.separate_out = ''
129 classic_config.InteractiveShell.separate_out = ''
130 classic_config.InteractiveShell.separate_out2 = ''
130 classic_config.InteractiveShell.separate_out2 = ''
131 classic_config.InteractiveShell.colors = 'NoColor'
131 classic_config.InteractiveShell.colors = 'NoColor'
132 classic_config.InteractiveShell.xmode = 'Plain'
132 classic_config.InteractiveShell.xmode = 'Plain'
133
133
134 frontend_flags['classic']=(
134 frontend_flags['classic']=(
135 classic_config,
135 classic_config,
136 "Gives IPython a similar feel to the classic Python prompt."
136 "Gives IPython a similar feel to the classic Python prompt."
137 )
137 )
138 # # log doesn't make so much sense this way anymore
138 # # log doesn't make so much sense this way anymore
139 # paa('--log','-l',
139 # paa('--log','-l',
140 # action='store_true', dest='InteractiveShell.logstart',
140 # action='store_true', dest='InteractiveShell.logstart',
141 # help="Start logging to the default log file (./ipython_log.py).")
141 # help="Start logging to the default log file (./ipython_log.py).")
142 #
142 #
143 # # quick is harder to implement
143 # # quick is harder to implement
144 frontend_flags['quick']=(
144 frontend_flags['quick']=(
145 {'TerminalIPythonApp' : {'quick' : True}},
145 {'TerminalIPythonApp' : {'quick' : True}},
146 "Enable quick startup with no config files."
146 "Enable quick startup with no config files."
147 )
147 )
148
148
149 frontend_flags['i'] = (
149 frontend_flags['i'] = (
150 {'TerminalIPythonApp' : {'force_interact' : True}},
150 {'TerminalIPythonApp' : {'force_interact' : True}},
151 """If running code from the command line, become interactive afterwards.
151 """If running code from the command line, become interactive afterwards.
152 It is often useful to follow this with `--` to treat remaining flags as
152 It is often useful to follow this with `--` to treat remaining flags as
153 script arguments.
153 script arguments.
154 """
154 """
155 )
155 )
156 flags.update(frontend_flags)
156 flags.update(frontend_flags)
157
157
158 aliases = dict(base_aliases)
158 aliases = dict(base_aliases)
159 aliases.update(shell_aliases)
159 aliases.update(shell_aliases)
160
160
161 #-----------------------------------------------------------------------------
161 #-----------------------------------------------------------------------------
162 # Main classes and functions
162 # Main classes and functions
163 #-----------------------------------------------------------------------------
163 #-----------------------------------------------------------------------------
164
164
165
165
166 class LocateIPythonApp(BaseIPythonApplication):
166 class LocateIPythonApp(BaseIPythonApplication):
167 description = """print the path to the IPython dir"""
167 description = """print the path to the IPython dir"""
168 subcommands = dict(
168 subcommands = dict(
169 profile=('IPython.core.profileapp.ProfileLocate',
169 profile=('IPython.core.profileapp.ProfileLocate',
170 "print the path to an IPython profile directory",
170 "print the path to an IPython profile directory",
171 ),
171 ),
172 )
172 )
173 def start(self):
173 def start(self):
174 if self.subapp is not None:
174 if self.subapp is not None:
175 return self.subapp.start()
175 return self.subapp.start()
176 else:
176 else:
177 print(self.ipython_dir)
177 print(self.ipython_dir)
178
178
179
179
180 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
180 class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
181 name = u'ipython'
181 name = u'ipython'
182 description = usage.cl_usage
182 description = usage.cl_usage
183 crash_handler_class = IPAppCrashHandler
183 crash_handler_class = IPAppCrashHandler
184 examples = _examples
184 examples = _examples
185
185
186 flags = flags
186 flags = flags
187 aliases = aliases
187 aliases = aliases
188 classes = List()
188 classes = List()
189
189
190 interactive_shell_class = Type(
190 interactive_shell_class = Type(
191 klass=object, # use default_value otherwise which only allow subclasses.
191 klass=object, # use default_value otherwise which only allow subclasses.
192 default_value=TerminalInteractiveShell,
192 default_value=TerminalInteractiveShell,
193 help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends"
193 help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends"
194 ).tag(config=True)
194 ).tag(config=True)
195
195
196 @default('classes')
196 @default('classes')
197 def _classes_default(self):
197 def _classes_default(self):
198 """This has to be in a method, for TerminalIPythonApp to be available."""
198 """This has to be in a method, for TerminalIPythonApp to be available."""
199 return [
199 return [
200 InteractiveShellApp, # ShellApp comes before TerminalApp, because
200 InteractiveShellApp, # ShellApp comes before TerminalApp, because
201 self.__class__, # it will also affect subclasses (e.g. QtConsole)
201 self.__class__, # it will also affect subclasses (e.g. QtConsole)
202 TerminalInteractiveShell,
202 TerminalInteractiveShell,
203 HistoryManager,
203 HistoryManager,
204 MagicsManager,
204 MagicsManager,
205 ProfileDir,
205 ProfileDir,
206 PlainTextFormatter,
206 PlainTextFormatter,
207 IPCompleter,
207 IPCompleter,
208 ScriptMagics,
208 ScriptMagics,
209 LoggingMagics,
209 LoggingMagics,
210 StoreMagics,
210 StoreMagics,
211 ]
211 ]
212
212
213 subcommands = dict(
213 subcommands = dict(
214 profile = ("IPython.core.profileapp.ProfileApp",
214 profile = ("IPython.core.profileapp.ProfileApp",
215 "Create and manage IPython profiles."
215 "Create and manage IPython profiles."
216 ),
216 ),
217 kernel = ("ipykernel.kernelapp.IPKernelApp",
217 kernel = ("ipykernel.kernelapp.IPKernelApp",
218 "Start a kernel without an attached frontend."
218 "Start a kernel without an attached frontend."
219 ),
219 ),
220 locate=('IPython.terminal.ipapp.LocateIPythonApp',
220 locate=('IPython.terminal.ipapp.LocateIPythonApp',
221 LocateIPythonApp.description
221 LocateIPythonApp.description
222 ),
222 ),
223 history=('IPython.core.historyapp.HistoryApp',
223 history=('IPython.core.historyapp.HistoryApp',
224 "Manage the IPython history database."
224 "Manage the IPython history database."
225 ),
225 ),
226 )
226 )
227
227
228
228
229 # *do* autocreate requested profile, but don't create the config file.
229 # *do* autocreate requested profile, but don't create the config file.
230 auto_create=Bool(True)
230 auto_create=Bool(True)
231 # configurables
231 # configurables
232 quick = Bool(False,
232 quick = Bool(False,
233 help="""Start IPython quickly by skipping the loading of config files."""
233 help="""Start IPython quickly by skipping the loading of config files."""
234 ).tag(config=True)
234 ).tag(config=True)
235 @observe('quick')
235 @observe('quick')
236 def _quick_changed(self, change):
236 def _quick_changed(self, change):
237 if change['new']:
237 if change['new']:
238 self.load_config_file = lambda *a, **kw: None
238 self.load_config_file = lambda *a, **kw: None
239
239
240 display_banner = Bool(True,
240 display_banner = Bool(True,
241 help="Whether to display a banner upon starting IPython."
241 help="Whether to display a banner upon starting IPython."
242 ).tag(config=True)
242 ).tag(config=True)
243
243
244 # if there is code of files to run from the cmd line, don't interact
244 # if there is code of files to run from the cmd line, don't interact
245 # unless the --i flag (App.force_interact) is true.
245 # unless the --i flag (App.force_interact) is true.
246 force_interact = Bool(False,
246 force_interact = Bool(False,
247 help="""If a command or file is given via the command-line,
247 help="""If a command or file is given via the command-line,
248 e.g. 'ipython foo.py', start an interactive shell after executing the
248 e.g. 'ipython foo.py', start an interactive shell after executing the
249 file or command."""
249 file or command."""
250 ).tag(config=True)
250 ).tag(config=True)
251 @observe('force_interact')
251 @observe('force_interact')
252 def _force_interact_changed(self, change):
252 def _force_interact_changed(self, change):
253 if change['new']:
253 if change['new']:
254 self.interact = True
254 self.interact = True
255
255
256 @observe('file_to_run', 'code_to_run', 'module_to_run')
256 @observe('file_to_run', 'code_to_run', 'module_to_run')
257 def _file_to_run_changed(self, change):
257 def _file_to_run_changed(self, change):
258 new = change['new']
258 new = change['new']
259 if new:
259 if new:
260 self.something_to_run = True
260 self.something_to_run = True
261 if new and not self.force_interact:
261 if new and not self.force_interact:
262 self.interact = False
262 self.interact = False
263
263
264 # internal, not-configurable
264 # internal, not-configurable
265 something_to_run=Bool(False)
265 something_to_run=Bool(False)
266
266
267 @catch_config_error
267 @catch_config_error
268 def initialize(self, argv=None):
268 def initialize(self, argv=None):
269 """Do actions after construct, but before starting the app."""
269 """Do actions after construct, but before starting the app."""
270 super(TerminalIPythonApp, self).initialize(argv)
270 super(TerminalIPythonApp, self).initialize(argv)
271 if self.subapp is not None:
271 if self.subapp is not None:
272 # don't bother initializing further, starting subapp
272 # don't bother initializing further, starting subapp
273 return
273 return
274 # print self.extra_args
274 # print self.extra_args
275 if self.extra_args and not self.something_to_run:
275 if self.extra_args and not self.something_to_run:
276 self.file_to_run = self.extra_args[0]
276 self.file_to_run = self.extra_args[0]
277 self.init_path()
277 self.init_path()
278 # create the shell
278 # create the shell
279 self.init_shell()
279 self.init_shell()
280 # and draw the banner
280 # and draw the banner
281 self.init_banner()
281 self.init_banner()
282 # Now a variety of things that happen after the banner is printed.
282 # Now a variety of things that happen after the banner is printed.
283 self.init_gui_pylab()
283 self.init_gui_pylab()
284 self.init_extensions()
284 self.init_extensions()
285 self.init_code()
285 self.init_code()
286
286
287 def init_shell(self):
287 def init_shell(self):
288 """initialize the InteractiveShell instance"""
288 """initialize the InteractiveShell instance"""
289 # Create an InteractiveShell instance.
289 # Create an InteractiveShell instance.
290 # shell.display_banner should always be False for the terminal
290 # shell.display_banner should always be False for the terminal
291 # based app, because we call shell.show_banner() by hand below
291 # based app, because we call shell.show_banner() by hand below
292 # so the banner shows *before* all extension loading stuff.
292 # so the banner shows *before* all extension loading stuff.
293 self.shell = self.interactive_shell_class.instance(parent=self,
293 self.shell = self.interactive_shell_class.instance(parent=self,
294 profile_dir=self.profile_dir,
294 profile_dir=self.profile_dir,
295 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
295 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
296 self.shell.configurables.append(self)
296 self.shell.configurables.append(self)
297
297
298 def init_banner(self):
298 def init_banner(self):
299 """optionally display the banner"""
299 """optionally display the banner"""
300 if self.display_banner and self.interact:
300 if self.display_banner and self.interact:
301 self.shell.show_banner()
301 self.shell.show_banner()
302 # Make sure there is a space below the banner.
302 # Make sure there is a space below the banner.
303 if self.log_level <= logging.INFO: print()
303 if self.log_level <= logging.INFO: print()
304
304
305 def _pylab_changed(self, name, old, new):
305 def _pylab_changed(self, name, old, new):
306 """Replace --pylab='inline' with --pylab='auto'"""
306 """Replace --pylab='inline' with --pylab='auto'"""
307 if new == 'inline':
307 if new == 'inline':
308 warnings.warn("'inline' not available as pylab backend, "
308 warnings.warn("'inline' not available as pylab backend, "
309 "using 'auto' instead.")
309 "using 'auto' instead.")
310 self.pylab = 'auto'
310 self.pylab = 'auto'
311
311
312 def start(self):
312 def start(self):
313 if self.subapp is not None:
313 if self.subapp is not None:
314 return self.subapp.start()
314 return self.subapp.start()
315 # perform any prexec steps:
315 # perform any prexec steps:
316 if self.interact:
316 if self.interact:
317 self.log.debug("Starting IPython's mainloop...")
317 self.log.debug("Starting IPython's mainloop...")
318 self.shell.mainloop()
318 self.shell.mainloop()
319 else:
319 else:
320 self.log.debug("IPython not interactive...")
320 self.log.debug("IPython not interactive...")
321 if not self.shell.last_execution_succeeded:
321 if not self.shell.last_execution_succeeded:
322 sys.exit(1)
322 sys.exit(1)
323
323
324 def load_default_config(ipython_dir=None):
324 def load_default_config(ipython_dir=None):
325 """Load the default config file from the default ipython_dir.
325 """Load the default config file from the default ipython_dir.
326
326
327 This is useful for embedded shells.
327 This is useful for embedded shells.
328 """
328 """
329 if ipython_dir is None:
329 if ipython_dir is None:
330 ipython_dir = get_ipython_dir()
330 ipython_dir = get_ipython_dir()
331
331
332 profile_dir = os.path.join(ipython_dir, 'profile_default')
332 profile_dir = os.path.join(ipython_dir, 'profile_default')
333 app = TerminalIPythonApp()
333 app = TerminalIPythonApp()
334 app.config_file_paths.append(profile_dir)
334 app.config_file_paths.append(profile_dir)
335 app.load_config_file()
335 app.load_config_file()
336 return app.config
336 return app.config
337
337
338 launch_new_instance = TerminalIPythonApp.launch_instance
338 launch_new_instance = TerminalIPythonApp.launch_instance
339
339
340
340
341 if __name__ == '__main__':
341 if __name__ == '__main__':
342 launch_new_instance()
342 launch_new_instance()
@@ -1,99 +1,113 b''
1 .. _events:
1 .. _events:
2 .. _callbacks:
2 .. _callbacks:
3
3
4 ==============
4 ==============
5 IPython Events
5 IPython Events
6 ==============
6 ==============
7
7
8 Extension code can register callbacks functions which will be called on specific
8 Extension code can register callbacks functions which will be called on specific
9 events within the IPython code. You can see the current list of available
9 events within the IPython code. You can see the current list of available
10 callbacks, and the parameters that will be passed with each, in the callback
10 callbacks, and the parameters that will be passed with each, in the callback
11 prototype functions defined in :mod:`IPython.core.events`.
11 prototype functions defined in :mod:`IPython.core.events`.
12
12
13 To register callbacks, use :meth:`IPython.core.events.EventManager.register`.
13 To register callbacks, use :meth:`IPython.core.events.EventManager.register`.
14 For example::
14 For example::
15
15
16 class VarWatcher(object):
16 class VarWatcher(object):
17 def __init__(self, ip):
17 def __init__(self, ip):
18 self.shell = ip
18 self.shell = ip
19 self.last_x = None
19 self.last_x = None
20
20
21 def pre_execute(self):
21 def pre_execute(self):
22 self.last_x = self.shell.user_ns.get('x', None)
22 self.last_x = self.shell.user_ns.get('x', None)
23
23
24 def pre_run_cell(self, info):
24 def pre_run_cell(self, info):
25 print('Cell code: "%s"' % info.raw_cell)
25 print('info.raw_cell =', info.raw_cell)
26
26 print('info.store_history =', info.store_history)
27 print('info.silent =', info.silent)
28 print('info.shell_futures =', info.shell_futures)
29 print('info.cell_id =', info.cell_id)
30 print(dir(info))
31
27 def post_execute(self):
32 def post_execute(self):
28 if self.shell.user_ns.get('x', None) != self.last_x:
33 if self.shell.user_ns.get('x', None) != self.last_x:
29 print("x changed!")
34 print("x changed!")
30
35
31 def post_run_cell(self, result):
36 def post_run_cell(self, result):
32 print('Cell code: "%s"' % result.info.raw_cell)
37 print('result.execution_count = ', result.execution_count)
33 if result.error_before_exec:
38 print('result.error_before_exec = ', result.error_before_exec)
34 print('Error before execution: %s' % result.error_before_exec)
39 print('result.error_in_exec = ', result.error_in_exec)
35
40 print('result.info = ', result.info)
41 print('result.result = ', result.result)
42
36 def load_ipython_extension(ip):
43 def load_ipython_extension(ip):
37 vw = VarWatcher(ip)
44 vw = VarWatcher(ip)
38 ip.events.register('pre_execute', vw.pre_execute)
45 ip.events.register('pre_execute', vw.pre_execute)
39 ip.events.register('pre_run_cell', vw.pre_run_cell)
46 ip.events.register('pre_run_cell', vw.pre_run_cell)
40 ip.events.register('post_execute', vw.post_execute)
47 ip.events.register('post_execute', vw.post_execute)
41 ip.events.register('post_run_cell', vw.post_run_cell)
48 ip.events.register('post_run_cell', vw.post_run_cell)
42
49
50 .. versionadded:: 8.3
51
52 Since IPython 8.3 and ipykernel 6.12.1, the ``info`` objects in the callback
53 now have a the ``cell_id`` that will be set to the value sent by the
54 frontened, when those send it.
55
56
43
57
44 Events
58 Events
45 ======
59 ======
46
60
47 These are the events IPython will emit. Callbacks will be passed no arguments, unless otherwise specified.
61 These are the events IPython will emit. Callbacks will be passed no arguments, unless otherwise specified.
48
62
49 shell_initialized
63 shell_initialized
50 -----------------
64 -----------------
51
65
52 .. code-block:: python
66 .. code-block:: python
53
67
54 def shell_initialized(ipython):
68 def shell_initialized(ipython):
55 ...
69 ...
56
70
57 This event is triggered only once, at the end of setting up IPython.
71 This event is triggered only once, at the end of setting up IPython.
58 Extensions registered to load by default as part of configuration can use this to execute code to finalize setup.
72 Extensions registered to load by default as part of configuration can use this to execute code to finalize setup.
59 Callbacks will be passed the InteractiveShell instance.
73 Callbacks will be passed the InteractiveShell instance.
60
74
61 pre_run_cell
75 pre_run_cell
62 ------------
76 ------------
63
77
64 ``pre_run_cell`` fires prior to interactive execution (e.g. a cell in a notebook).
78 ``pre_run_cell`` fires prior to interactive execution (e.g. a cell in a notebook).
65 It can be used to note the state prior to execution, and keep track of changes.
79 It can be used to note the state prior to execution, and keep track of changes.
66 An object containing information used for the code execution is provided as an argument.
80 An object containing information used for the code execution is provided as an argument.
67
81
68 pre_execute
82 pre_execute
69 -----------
83 -----------
70
84
71 ``pre_execute`` is like ``pre_run_cell``, but is triggered prior to *any* execution.
85 ``pre_execute`` is like ``pre_run_cell``, but is triggered prior to *any* execution.
72 Sometimes code can be executed by libraries, etc. which
86 Sometimes code can be executed by libraries, etc. which
73 skipping the history/display mechanisms, in which cases ``pre_run_cell`` will not fire.
87 skipping the history/display mechanisms, in which cases ``pre_run_cell`` will not fire.
74
88
75 post_run_cell
89 post_run_cell
76 -------------
90 -------------
77
91
78 ``post_run_cell`` runs after interactive execution (e.g. a cell in a notebook).
92 ``post_run_cell`` runs after interactive execution (e.g. a cell in a notebook).
79 It can be used to cleanup or notify or perform operations on any side effects produced during execution.
93 It can be used to cleanup or notify or perform operations on any side effects produced during execution.
80 For instance, the inline matplotlib backend uses this event to display any figures created but not explicitly displayed during the course of the cell.
94 For instance, the inline matplotlib backend uses this event to display any figures created but not explicitly displayed during the course of the cell.
81 The object which will be returned as the execution result is provided as an
95 The object which will be returned as the execution result is provided as an
82 argument.
96 argument.
83
97
84 post_execute
98 post_execute
85 ------------
99 ------------
86
100
87 The same as ``pre_execute``, ``post_execute`` is like ``post_run_cell``,
101 The same as ``pre_execute``, ``post_execute`` is like ``post_run_cell``,
88 but fires for *all* executions, not just interactive ones.
102 but fires for *all* executions, not just interactive ones.
89
103
90
104
91 .. seealso::
105 .. seealso::
92
106
93 Module :mod:`IPython.core.hooks`
107 Module :mod:`IPython.core.hooks`
94 The older 'hooks' system allows end users to customise some parts of
108 The older 'hooks' system allows end users to customise some parts of
95 IPython's behaviour.
109 IPython's behaviour.
96
110
97 :doc:`inputtransforms`
111 :doc:`inputtransforms`
98 By registering input transformers that don't change code, you can monitor
112 By registering input transformers that don't change code, you can monitor
99 what is being executed.
113 what is being executed.
@@ -1,1051 +1,1059 b''
1 ============
1 ============
2 8.x Series
2 8.x Series
3 ============
3 ============
4
4
5
5
6 .. _version 8.3.0:
7
8 IPython 8.3.0
9 -------------
10
11 - :ghpull:`13600`, ``pre_run_*``-hooks will now have a ``cell_id`` attribute on
12 the info object when frontend provide it.
13
6 .. _version 8.2.0:
14 .. _version 8.2.0:
7
15
8 IPython 8.2.0
16 IPython 8.2.0
9 -------------
17 -------------
10
18
11 IPython 8.2 mostly bring bugfixes to IPython.
19 IPython 8.2 mostly bring bugfixes to IPython.
12
20
13 - Auto-suggestion can now be elected with the ``end`` key. :ghpull:`13566`
21 - Auto-suggestion can now be elected with the ``end`` key. :ghpull:`13566`
14 - Some traceback issues with ``assert etb is not None`` have been fixed. :ghpull:`13588`
22 - Some traceback issues with ``assert etb is not None`` have been fixed. :ghpull:`13588`
15 - History is now pulled from the sqitel database and not from in-memory.
23 - History is now pulled from the sqitel database and not from in-memory.
16 In particular when using the ``%paste`` magic, the content of the pasted text will
24 In particular when using the ``%paste`` magic, the content of the pasted text will
17 be part of the history and not the verbatim text ``%paste`` anymore. :ghpull:`13592`
25 be part of the history and not the verbatim text ``%paste`` anymore. :ghpull:`13592`
18 - Fix ``Ctrl-\\`` exit cleanup :ghpull:`13603`
26 - Fix ``Ctrl-\\`` exit cleanup :ghpull:`13603`
19 - Fixes to ``ultratb`` ipdb support when used outside of IPython. :ghpull:`13498`
27 - Fixes to ``ultratb`` ipdb support when used outside of IPython. :ghpull:`13498`
20
28
21
29
22 I am still trying to fix and investigate :ghissue:`13598`, which seem to be
30 I am still trying to fix and investigate :ghissue:`13598`, which seem to be
23 random, and would appreciate help if you find reproducible minimal case. I've
31 random, and would appreciate help if you find reproducible minimal case. I've
24 tried to make various changes to the codebase to mitigate it, but a proper fix
32 tried to make various changes to the codebase to mitigate it, but a proper fix
25 will be difficult without understanding the cause.
33 will be difficult without understanding the cause.
26
34
27
35
28 All the issues on pull-requests for this release can be found in the `8.2
36 All the issues on pull-requests for this release can be found in the `8.2
29 milestone. <https://github.com/ipython/ipython/milestone/100>`__ . And some
37 milestone. <https://github.com/ipython/ipython/milestone/100>`__ . And some
30 documentation only PR can be found as part of the `7.33 milestone
38 documentation only PR can be found as part of the `7.33 milestone
31 <https://github.com/ipython/ipython/milestone/101>`__ (currently not released).
39 <https://github.com/ipython/ipython/milestone/101>`__ (currently not released).
32
40
33 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
41 Thanks to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
34 work on IPython and related libraries.
42 work on IPython and related libraries.
35
43
36 .. _version 8.1.1:
44 .. _version 8.1.1:
37
45
38 IPython 8.1.1
46 IPython 8.1.1
39 -------------
47 -------------
40
48
41 Fix an issue with virtualenv and Python 3.8 introduced in 8.1
49 Fix an issue with virtualenv and Python 3.8 introduced in 8.1
42
50
43 Revert :ghpull:`13537` (fix an issue with symlinks in virtualenv) that raises an
51 Revert :ghpull:`13537` (fix an issue with symlinks in virtualenv) that raises an
44 error in Python 3.8, and fixed in a different way in :ghpull:`13559`.
52 error in Python 3.8, and fixed in a different way in :ghpull:`13559`.
45
53
46 .. _version 8.1:
54 .. _version 8.1:
47
55
48 IPython 8.1.0
56 IPython 8.1.0
49 -------------
57 -------------
50
58
51 IPython 8.1 is the first minor release after 8.0 and fixes a number of bugs and
59 IPython 8.1 is the first minor release after 8.0 and fixes a number of bugs and
52 Update a few behavior that were problematic with the 8.0 as with many new major
60 Update a few behavior that were problematic with the 8.0 as with many new major
53 release.
61 release.
54
62
55 Note that beyond the changes listed here, IPython 8.1.0 also contains all the
63 Note that beyond the changes listed here, IPython 8.1.0 also contains all the
56 features listed in :ref:`version 7.32`.
64 features listed in :ref:`version 7.32`.
57
65
58 - Misc and multiple fixes around quotation auto-closing. It is now disabled by
66 - Misc and multiple fixes around quotation auto-closing. It is now disabled by
59 default. Run with ``TerminalInteractiveShell.auto_match=True`` to re-enabled
67 default. Run with ``TerminalInteractiveShell.auto_match=True`` to re-enabled
60 - Require pygments>=2.4.0 :ghpull:`13459`, this was implicit in the code, but
68 - Require pygments>=2.4.0 :ghpull:`13459`, this was implicit in the code, but
61 is now explicit in ``setup.cfg``/``setup.py``
69 is now explicit in ``setup.cfg``/``setup.py``
62 - Docs improvement of ``core.magic_arguments`` examples. :ghpull:`13433`
70 - Docs improvement of ``core.magic_arguments`` examples. :ghpull:`13433`
63 - Multi-line edit executes too early with await. :ghpull:`13424`
71 - Multi-line edit executes too early with await. :ghpull:`13424`
64
72
65 - ``black`` is back as an optional dependency, and autoformatting disabled by
73 - ``black`` is back as an optional dependency, and autoformatting disabled by
66 default until some fixes are implemented (black improperly reformat magics).
74 default until some fixes are implemented (black improperly reformat magics).
67 :ghpull:`13471` Additionally the ability to use ``yapf`` as a code
75 :ghpull:`13471` Additionally the ability to use ``yapf`` as a code
68 reformatter has been added :ghpull:`13528` . You can use
76 reformatter has been added :ghpull:`13528` . You can use
69 ``TerminalInteractiveShell.autoformatter="black"``,
77 ``TerminalInteractiveShell.autoformatter="black"``,
70 ``TerminalInteractiveShell.autoformatter="yapf"`` to re-enable auto formating
78 ``TerminalInteractiveShell.autoformatter="yapf"`` to re-enable auto formating
71 with black, or switch to yapf.
79 with black, or switch to yapf.
72
80
73 - Fix and issue where ``display`` was not defined.
81 - Fix and issue where ``display`` was not defined.
74
82
75 - Auto suggestions are now configurable. Currently only
83 - Auto suggestions are now configurable. Currently only
76 ``AutoSuggestFromHistory`` (default) and ``None``. new provider contribution
84 ``AutoSuggestFromHistory`` (default) and ``None``. new provider contribution
77 welcomed. :ghpull:`13475`
85 welcomed. :ghpull:`13475`
78
86
79 - multiple packaging/testing improvement to simplify downstream packaging
87 - multiple packaging/testing improvement to simplify downstream packaging
80 (xfail with reasons, try to not access network...).
88 (xfail with reasons, try to not access network...).
81
89
82 - Update deprecation. ``InteractiveShell.magic`` internal method has been
90 - Update deprecation. ``InteractiveShell.magic`` internal method has been
83 deprecated for many years but did not emit a warning until now.
91 deprecated for many years but did not emit a warning until now.
84
92
85 - internal ``appended_to_syspath`` context manager has been deprecated.
93 - internal ``appended_to_syspath`` context manager has been deprecated.
86
94
87 - fix an issue with symlinks in virtualenv :ghpull:`13537` (Reverted in 8.1.1)
95 - fix an issue with symlinks in virtualenv :ghpull:`13537` (Reverted in 8.1.1)
88
96
89 - Fix an issue with vim mode, where cursor would not be reset on exit :ghpull:`13472`
97 - Fix an issue with vim mode, where cursor would not be reset on exit :ghpull:`13472`
90
98
91 - ipython directive now remove only known pseudo-decorators :ghpull:`13532`
99 - ipython directive now remove only known pseudo-decorators :ghpull:`13532`
92
100
93 - ``IPython/lib/security`` which used to be used for jupyter notebook has been
101 - ``IPython/lib/security`` which used to be used for jupyter notebook has been
94 removed.
102 removed.
95
103
96 - Fix an issue where ``async with`` would execute on new lines. :ghpull:`13436`
104 - Fix an issue where ``async with`` would execute on new lines. :ghpull:`13436`
97
105
98
106
99 We want to remind users that IPython is part of the Jupyter organisations, and
107 We want to remind users that IPython is part of the Jupyter organisations, and
100 thus governed by a Code of Conduct. Some of the behavior we have seen on GitHub is not acceptable.
108 thus governed by a Code of Conduct. Some of the behavior we have seen on GitHub is not acceptable.
101 Abuse and non-respectful comments on discussion will not be tolerated.
109 Abuse and non-respectful comments on discussion will not be tolerated.
102
110
103 Many thanks to all the contributors to this release, many of the above fixed issue and
111 Many thanks to all the contributors to this release, many of the above fixed issue and
104 new features where done by first time contributors, showing there is still
112 new features where done by first time contributors, showing there is still
105 plenty of easy contribution possible in IPython
113 plenty of easy contribution possible in IPython
106 . You can find all individual contributions
114 . You can find all individual contributions
107 to this milestone `on github <https://github.com/ipython/ipython/milestone/91>`__.
115 to this milestone `on github <https://github.com/ipython/ipython/milestone/91>`__.
108
116
109 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
117 Thanks as well to the `D. E. Shaw group <https://deshaw.com/>`__ for sponsoring
110 work on IPython and related libraries. In particular the Lazy autoloading of
118 work on IPython and related libraries. In particular the Lazy autoloading of
111 magics that you will find described in the 7.32 release notes.
119 magics that you will find described in the 7.32 release notes.
112
120
113
121
114 .. _version 8.0.1:
122 .. _version 8.0.1:
115
123
116 IPython 8.0.1 (CVE-2022-21699)
124 IPython 8.0.1 (CVE-2022-21699)
117 ------------------------------
125 ------------------------------
118
126
119 IPython 8.0.1, 7.31.1 and 5.11 are security releases that change some default
127 IPython 8.0.1, 7.31.1 and 5.11 are security releases that change some default
120 values in order to prevent potential Execution with Unnecessary Privileges.
128 values in order to prevent potential Execution with Unnecessary Privileges.
121
129
122 Almost all version of IPython looks for configuration and profiles in current
130 Almost all version of IPython looks for configuration and profiles in current
123 working directory. Since IPython was developed before pip and environments
131 working directory. Since IPython was developed before pip and environments
124 existed it was used a convenient way to load code/packages in a project
132 existed it was used a convenient way to load code/packages in a project
125 dependant way.
133 dependant way.
126
134
127 In 2022, it is not necessary anymore, and can lead to confusing behavior where
135 In 2022, it is not necessary anymore, and can lead to confusing behavior where
128 for example cloning a repository and starting IPython or loading a notebook from
136 for example cloning a repository and starting IPython or loading a notebook from
129 any Jupyter-Compatible interface that has ipython set as a kernel can lead to
137 any Jupyter-Compatible interface that has ipython set as a kernel can lead to
130 code execution.
138 code execution.
131
139
132
140
133 I did not find any standard way for packaged to advertise CVEs they fix, I'm
141 I did not find any standard way for packaged to advertise CVEs they fix, I'm
134 thus trying to add a ``__patched_cves__`` attribute to the IPython module that
142 thus trying to add a ``__patched_cves__`` attribute to the IPython module that
135 list the CVEs that should have been fixed. This attribute is informational only
143 list the CVEs that should have been fixed. This attribute is informational only
136 as if a executable has a flaw, this value can always be changed by an attacker.
144 as if a executable has a flaw, this value can always be changed by an attacker.
137
145
138 .. code::
146 .. code::
139
147
140 In [1]: import IPython
148 In [1]: import IPython
141
149
142 In [2]: IPython.__patched_cves__
150 In [2]: IPython.__patched_cves__
143 Out[2]: {'CVE-2022-21699'}
151 Out[2]: {'CVE-2022-21699'}
144
152
145 In [3]: 'CVE-2022-21699' in IPython.__patched_cves__
153 In [3]: 'CVE-2022-21699' in IPython.__patched_cves__
146 Out[3]: True
154 Out[3]: True
147
155
148 Thus starting with this version:
156 Thus starting with this version:
149
157
150 - The current working directory is not searched anymore for profiles or
158 - The current working directory is not searched anymore for profiles or
151 configurations files.
159 configurations files.
152 - Added a ``__patched_cves__`` attribute (set of strings) to IPython module that contain
160 - Added a ``__patched_cves__`` attribute (set of strings) to IPython module that contain
153 the list of fixed CVE. This is informational only.
161 the list of fixed CVE. This is informational only.
154
162
155 Further details can be read on the `GitHub Advisory <https://github.com/ipython/ipython/security/advisories/GHSA-pq7m-3gw7-gq5x>`__
163 Further details can be read on the `GitHub Advisory <https://github.com/ipython/ipython/security/advisories/GHSA-pq7m-3gw7-gq5x>`__
156
164
157
165
158 .. _version 8.0:
166 .. _version 8.0:
159
167
160 IPython 8.0
168 IPython 8.0
161 -----------
169 -----------
162
170
163 IPython 8.0 is bringing a large number of new features and improvements to both the
171 IPython 8.0 is bringing a large number of new features and improvements to both the
164 user of the terminal and of the kernel via Jupyter. The removal of compatibility
172 user of the terminal and of the kernel via Jupyter. The removal of compatibility
165 with older version of Python is also the opportunity to do a couple of
173 with older version of Python is also the opportunity to do a couple of
166 performance improvements in particular with respect to startup time.
174 performance improvements in particular with respect to startup time.
167 The 8.x branch started diverging from its predecessor around IPython 7.12
175 The 8.x branch started diverging from its predecessor around IPython 7.12
168 (January 2020).
176 (January 2020).
169
177
170 This release contains 250+ pull requests, in addition to many of the features
178 This release contains 250+ pull requests, in addition to many of the features
171 and backports that have made it to the 7.x branch. Please see the
179 and backports that have made it to the 7.x branch. Please see the
172 `8.0 milestone <https://github.com/ipython/ipython/milestone/73?closed=1>`__ for the full list of pull requests.
180 `8.0 milestone <https://github.com/ipython/ipython/milestone/73?closed=1>`__ for the full list of pull requests.
173
181
174 Please feel free to send pull requests to updates those notes after release,
182 Please feel free to send pull requests to updates those notes after release,
175 I have likely forgotten a few things reviewing 250+ PRs.
183 I have likely forgotten a few things reviewing 250+ PRs.
176
184
177 Dependencies changes/downstream packaging
185 Dependencies changes/downstream packaging
178 -----------------------------------------
186 -----------------------------------------
179
187
180 Most of our building steps have been changed to be (mostly) declarative
188 Most of our building steps have been changed to be (mostly) declarative
181 and follow PEP 517. We are trying to completely remove ``setup.py`` (:ghpull:`13238`) and are
189 and follow PEP 517. We are trying to completely remove ``setup.py`` (:ghpull:`13238`) and are
182 looking for help to do so.
190 looking for help to do so.
183
191
184 - minimum supported ``traitlets`` version is now 5+
192 - minimum supported ``traitlets`` version is now 5+
185 - we now require ``stack_data``
193 - we now require ``stack_data``
186 - minimal Python is now 3.8
194 - minimal Python is now 3.8
187 - ``nose`` is not a testing requirement anymore
195 - ``nose`` is not a testing requirement anymore
188 - ``pytest`` replaces nose.
196 - ``pytest`` replaces nose.
189 - ``iptest``/``iptest3`` cli entrypoints do not exists anymore.
197 - ``iptest``/``iptest3`` cli entrypoints do not exists anymore.
190 - minimum officially support ``numpy`` version has been bumped, but this should
198 - minimum officially support ``numpy`` version has been bumped, but this should
191 not have much effect on packaging.
199 not have much effect on packaging.
192
200
193
201
194 Deprecation and removal
202 Deprecation and removal
195 -----------------------
203 -----------------------
196
204
197 We removed almost all features, arguments, functions, and modules that were
205 We removed almost all features, arguments, functions, and modules that were
198 marked as deprecated between IPython 1.0 and 5.0. As a reminder, 5.0 was released
206 marked as deprecated between IPython 1.0 and 5.0. As a reminder, 5.0 was released
199 in 2016, and 1.0 in 2013. Last release of the 5 branch was 5.10.0, in May 2020.
207 in 2016, and 1.0 in 2013. Last release of the 5 branch was 5.10.0, in May 2020.
200 The few remaining deprecated features we left have better deprecation warnings
208 The few remaining deprecated features we left have better deprecation warnings
201 or have been turned into explicit errors for better error messages.
209 or have been turned into explicit errors for better error messages.
202
210
203 I will use this occasion to add the following requests to anyone emitting a
211 I will use this occasion to add the following requests to anyone emitting a
204 deprecation warning:
212 deprecation warning:
205
213
206 - Please add at least ``stacklevel=2`` so that the warning is emitted into the
214 - Please add at least ``stacklevel=2`` so that the warning is emitted into the
207 caller context, and not the callee one.
215 caller context, and not the callee one.
208 - Please add **since which version** something is deprecated.
216 - Please add **since which version** something is deprecated.
209
217
210 As a side note, it is much easier to conditionally compare version
218 As a side note, it is much easier to conditionally compare version
211 numbers rather than using ``try/except`` when functionality changes with a version.
219 numbers rather than using ``try/except`` when functionality changes with a version.
212
220
213 I won't list all the removed features here, but modules like ``IPython.kernel``,
221 I won't list all the removed features here, but modules like ``IPython.kernel``,
214 which was just a shim module around ``ipykernel`` for the past 8 years, have been
222 which was just a shim module around ``ipykernel`` for the past 8 years, have been
215 removed, and so many other similar things that pre-date the name **Jupyter**
223 removed, and so many other similar things that pre-date the name **Jupyter**
216 itself.
224 itself.
217
225
218 We no longer need to add ``IPython.extensions`` to the PYTHONPATH because that is being
226 We no longer need to add ``IPython.extensions`` to the PYTHONPATH because that is being
219 handled by ``load_extension``.
227 handled by ``load_extension``.
220
228
221 We are also removing ``Cythonmagic``, ``sympyprinting`` and ``rmagic`` as they are now in
229 We are also removing ``Cythonmagic``, ``sympyprinting`` and ``rmagic`` as they are now in
222 other packages and no longer need to be inside IPython.
230 other packages and no longer need to be inside IPython.
223
231
224
232
225 Documentation
233 Documentation
226 -------------
234 -------------
227
235
228 The majority of our docstrings have now been reformatted and automatically fixed by
236 The majority of our docstrings have now been reformatted and automatically fixed by
229 the experimental `VΓ©lin <https://pypi.org/project/velin/>`_ project to conform
237 the experimental `VΓ©lin <https://pypi.org/project/velin/>`_ project to conform
230 to numpydoc.
238 to numpydoc.
231
239
232 Type annotations
240 Type annotations
233 ----------------
241 ----------------
234
242
235 While IPython itself is highly dynamic and can't be completely typed, many of
243 While IPython itself is highly dynamic and can't be completely typed, many of
236 the functions now have type annotations, and part of the codebase is now checked
244 the functions now have type annotations, and part of the codebase is now checked
237 by mypy.
245 by mypy.
238
246
239
247
240 Featured changes
248 Featured changes
241 ----------------
249 ----------------
242
250
243 Here is a features list of changes in IPython 8.0. This is of course non-exhaustive.
251 Here is a features list of changes in IPython 8.0. This is of course non-exhaustive.
244 Please note as well that many features have been added in the 7.x branch as well
252 Please note as well that many features have been added in the 7.x branch as well
245 (and hence why you want to read the 7.x what's new notes), in particular
253 (and hence why you want to read the 7.x what's new notes), in particular
246 features contributed by QuantStack (with respect to debugger protocol and Xeus
254 features contributed by QuantStack (with respect to debugger protocol and Xeus
247 Python), as well as many debugger features that I was pleased to implement as
255 Python), as well as many debugger features that I was pleased to implement as
248 part of my work at QuanSight and sponsored by DE Shaw.
256 part of my work at QuanSight and sponsored by DE Shaw.
249
257
250 Traceback improvements
258 Traceback improvements
251 ~~~~~~~~~~~~~~~~~~~~~~
259 ~~~~~~~~~~~~~~~~~~~~~~
252
260
253 Previously, error tracebacks for errors happening in code cells were showing a
261 Previously, error tracebacks for errors happening in code cells were showing a
254 hash, the one used for compiling the Python AST::
262 hash, the one used for compiling the Python AST::
255
263
256 In [1]: def foo():
264 In [1]: def foo():
257 ...: return 3 / 0
265 ...: return 3 / 0
258 ...:
266 ...:
259
267
260 In [2]: foo()
268 In [2]: foo()
261 ---------------------------------------------------------------------------
269 ---------------------------------------------------------------------------
262 ZeroDivisionError Traceback (most recent call last)
270 ZeroDivisionError Traceback (most recent call last)
263 <ipython-input-2-c19b6d9633cf> in <module>
271 <ipython-input-2-c19b6d9633cf> in <module>
264 ----> 1 foo()
272 ----> 1 foo()
265
273
266 <ipython-input-1-1595a74c32d5> in foo()
274 <ipython-input-1-1595a74c32d5> in foo()
267 1 def foo():
275 1 def foo():
268 ----> 2 return 3 / 0
276 ----> 2 return 3 / 0
269 3
277 3
270
278
271 ZeroDivisionError: division by zero
279 ZeroDivisionError: division by zero
272
280
273 The error traceback is now correctly formatted, showing the cell number in which the error happened::
281 The error traceback is now correctly formatted, showing the cell number in which the error happened::
274
282
275 In [1]: def foo():
283 In [1]: def foo():
276 ...: return 3 / 0
284 ...: return 3 / 0
277 ...:
285 ...:
278
286
279 Input In [2]: foo()
287 Input In [2]: foo()
280 ---------------------------------------------------------------------------
288 ---------------------------------------------------------------------------
281 ZeroDivisionError Traceback (most recent call last)
289 ZeroDivisionError Traceback (most recent call last)
282 input In [2], in <module>
290 input In [2], in <module>
283 ----> 1 foo()
291 ----> 1 foo()
284
292
285 Input In [1], in foo()
293 Input In [1], in foo()
286 1 def foo():
294 1 def foo():
287 ----> 2 return 3 / 0
295 ----> 2 return 3 / 0
288
296
289 ZeroDivisionError: division by zero
297 ZeroDivisionError: division by zero
290
298
291 The ``stack_data`` package has been integrated, which provides smarter information in the traceback;
299 The ``stack_data`` package has been integrated, which provides smarter information in the traceback;
292 in particular it will highlight the AST node where an error occurs which can help to quickly narrow down errors.
300 in particular it will highlight the AST node where an error occurs which can help to quickly narrow down errors.
293
301
294 For example in the following snippet::
302 For example in the following snippet::
295
303
296 def foo(i):
304 def foo(i):
297 x = [[[0]]]
305 x = [[[0]]]
298 return x[0][i][0]
306 return x[0][i][0]
299
307
300
308
301 def bar():
309 def bar():
302 return foo(0) + foo(
310 return foo(0) + foo(
303 1
311 1
304 ) + foo(2)
312 ) + foo(2)
305
313
306
314
307 calling ``bar()`` would raise an ``IndexError`` on the return line of ``foo``,
315 calling ``bar()`` would raise an ``IndexError`` on the return line of ``foo``,
308 and IPython 8.0 is capable of telling you where the index error occurs::
316 and IPython 8.0 is capable of telling you where the index error occurs::
309
317
310
318
311 IndexError
319 IndexError
312 Input In [2], in <module>
320 Input In [2], in <module>
313 ----> 1 bar()
321 ----> 1 bar()
314 ^^^^^
322 ^^^^^
315
323
316 Input In [1], in bar()
324 Input In [1], in bar()
317 6 def bar():
325 6 def bar():
318 ----> 7 return foo(0) + foo(
326 ----> 7 return foo(0) + foo(
319 ^^^^
327 ^^^^
320 8 1
328 8 1
321 ^^^^^^^^
329 ^^^^^^^^
322 9 ) + foo(2)
330 9 ) + foo(2)
323 ^^^^
331 ^^^^
324
332
325 Input In [1], in foo(i)
333 Input In [1], in foo(i)
326 1 def foo(i):
334 1 def foo(i):
327 2 x = [[[0]]]
335 2 x = [[[0]]]
328 ----> 3 return x[0][i][0]
336 ----> 3 return x[0][i][0]
329 ^^^^^^^
337 ^^^^^^^
330
338
331 The corresponding locations marked here with ``^`` will show up highlighted in
339 The corresponding locations marked here with ``^`` will show up highlighted in
332 the terminal and notebooks.
340 the terminal and notebooks.
333
341
334 Finally, a colon ``::`` and line number is appended after a filename in
342 Finally, a colon ``::`` and line number is appended after a filename in
335 traceback::
343 traceback::
336
344
337
345
338 ZeroDivisionError Traceback (most recent call last)
346 ZeroDivisionError Traceback (most recent call last)
339 File ~/error.py:4, in <module>
347 File ~/error.py:4, in <module>
340 1 def f():
348 1 def f():
341 2 1/0
349 2 1/0
342 ----> 4 f()
350 ----> 4 f()
343
351
344 File ~/error.py:2, in f()
352 File ~/error.py:2, in f()
345 1 def f():
353 1 def f():
346 ----> 2 1/0
354 ----> 2 1/0
347
355
348 Many terminals and editors have integrations enabling you to directly jump to the
356 Many terminals and editors have integrations enabling you to directly jump to the
349 relevant file/line when this syntax is used, so this small addition may have a high
357 relevant file/line when this syntax is used, so this small addition may have a high
350 impact on productivity.
358 impact on productivity.
351
359
352
360
353 Autosuggestions
361 Autosuggestions
354 ~~~~~~~~~~~~~~~
362 ~~~~~~~~~~~~~~~
355
363
356 Autosuggestion is a very useful feature available in `fish <https://fishshell.com/>`__, `zsh <https://en.wikipedia.org/wiki/Z_shell>`__, and `prompt-toolkit <https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#auto-suggestion>`__.
364 Autosuggestion is a very useful feature available in `fish <https://fishshell.com/>`__, `zsh <https://en.wikipedia.org/wiki/Z_shell>`__, and `prompt-toolkit <https://python-prompt-toolkit.readthedocs.io/en/master/pages/asking_for_input.html#auto-suggestion>`__.
357
365
358 `Ptpython <https://github.com/prompt-toolkit/ptpython#ptpython>`__ allows users to enable this feature in
366 `Ptpython <https://github.com/prompt-toolkit/ptpython#ptpython>`__ allows users to enable this feature in
359 `ptpython/config.py <https://github.com/prompt-toolkit/ptpython/blob/master/examples/ptpython_config/config.py#L90>`__.
367 `ptpython/config.py <https://github.com/prompt-toolkit/ptpython/blob/master/examples/ptpython_config/config.py#L90>`__.
360
368
361 This feature allows users to accept autosuggestions with ctrl e, ctrl f,
369 This feature allows users to accept autosuggestions with ctrl e, ctrl f,
362 or right arrow as described below.
370 or right arrow as described below.
363
371
364 1. Start ipython
372 1. Start ipython
365
373
366 .. image:: ../_images/8.0/auto_suggest_1_prompt_no_text.png
374 .. image:: ../_images/8.0/auto_suggest_1_prompt_no_text.png
367
375
368 2. Run ``print("hello")``
376 2. Run ``print("hello")``
369
377
370 .. image:: ../_images/8.0/auto_suggest_2_print_hello_suggest.png
378 .. image:: ../_images/8.0/auto_suggest_2_print_hello_suggest.png
371
379
372 3. start typing ``print`` again to see the autosuggestion
380 3. start typing ``print`` again to see the autosuggestion
373
381
374 .. image:: ../_images/8.0/auto_suggest_3_print_hello_suggest.png
382 .. image:: ../_images/8.0/auto_suggest_3_print_hello_suggest.png
375
383
376 4. Press ``ctrl-f``, or ``ctrl-e``, or ``right-arrow`` to accept the suggestion
384 4. Press ``ctrl-f``, or ``ctrl-e``, or ``right-arrow`` to accept the suggestion
377
385
378 .. image:: ../_images/8.0/auto_suggest_4_print_hello.png
386 .. image:: ../_images/8.0/auto_suggest_4_print_hello.png
379
387
380 You can also complete word by word:
388 You can also complete word by word:
381
389
382 1. Run ``def say_hello(): print("hello")``
390 1. Run ``def say_hello(): print("hello")``
383
391
384 .. image:: ../_images/8.0/auto_suggest_second_prompt.png
392 .. image:: ../_images/8.0/auto_suggest_second_prompt.png
385
393
386 2. Start typing the first letter if ``def`` to see the autosuggestion
394 2. Start typing the first letter if ``def`` to see the autosuggestion
387
395
388 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
396 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
389
397
390 3. Press ``alt-f`` (or ``escape`` followed by ``f``), to accept the first word of the suggestion
398 3. Press ``alt-f`` (or ``escape`` followed by ``f``), to accept the first word of the suggestion
391
399
392 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
400 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
393
401
394 Importantly, this feature does not interfere with tab completion:
402 Importantly, this feature does not interfere with tab completion:
395
403
396 1. After running ``def say_hello(): print("hello")``, press d
404 1. After running ``def say_hello(): print("hello")``, press d
397
405
398 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
406 .. image:: ../_images/8.0/auto_suggest_d_phantom.png
399
407
400 2. Press Tab to start tab completion
408 2. Press Tab to start tab completion
401
409
402 .. image:: ../_images/8.0/auto_suggest_d_completions.png
410 .. image:: ../_images/8.0/auto_suggest_d_completions.png
403
411
404 3A. Press Tab again to select the first option
412 3A. Press Tab again to select the first option
405
413
406 .. image:: ../_images/8.0/auto_suggest_def_completions.png
414 .. image:: ../_images/8.0/auto_suggest_def_completions.png
407
415
408 3B. Press ``alt f`` (``escape``, ``f``) to accept to accept the first word of the suggestion
416 3B. Press ``alt f`` (``escape``, ``f``) to accept to accept the first word of the suggestion
409
417
410 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
418 .. image:: ../_images/8.0/auto_suggest_def_phantom.png
411
419
412 3C. Press ``ctrl-f`` or ``ctrl-e`` to accept the entire suggestion
420 3C. Press ``ctrl-f`` or ``ctrl-e`` to accept the entire suggestion
413
421
414 .. image:: ../_images/8.0/auto_suggest_match_parens.png
422 .. image:: ../_images/8.0/auto_suggest_match_parens.png
415
423
416
424
417 Currently, autosuggestions are only shown in the emacs or vi insert editing modes:
425 Currently, autosuggestions are only shown in the emacs or vi insert editing modes:
418
426
419 - The ctrl e, ctrl f, and alt f shortcuts work by default in emacs mode.
427 - The ctrl e, ctrl f, and alt f shortcuts work by default in emacs mode.
420 - To use these shortcuts in vi insert mode, you will have to create `custom keybindings in your config.py <https://github.com/mskar/setup/commit/2892fcee46f9f80ef7788f0749edc99daccc52f4/>`__.
428 - To use these shortcuts in vi insert mode, you will have to create `custom keybindings in your config.py <https://github.com/mskar/setup/commit/2892fcee46f9f80ef7788f0749edc99daccc52f4/>`__.
421
429
422
430
423 Show pinfo information in ipdb using "?" and "??"
431 Show pinfo information in ipdb using "?" and "??"
424 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
432 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
425
433
426 In IPDB, it is now possible to show the information about an object using "?"
434 In IPDB, it is now possible to show the information about an object using "?"
427 and "??", in much the same way that it can be done when using the IPython prompt::
435 and "??", in much the same way that it can be done when using the IPython prompt::
428
436
429 ipdb> partial?
437 ipdb> partial?
430 Init signature: partial(self, /, *args, **kwargs)
438 Init signature: partial(self, /, *args, **kwargs)
431 Docstring:
439 Docstring:
432 partial(func, *args, **keywords) - new function with partial application
440 partial(func, *args, **keywords) - new function with partial application
433 of the given arguments and keywords.
441 of the given arguments and keywords.
434 File: ~/.pyenv/versions/3.8.6/lib/python3.8/functools.py
442 File: ~/.pyenv/versions/3.8.6/lib/python3.8/functools.py
435 Type: type
443 Type: type
436 Subclasses:
444 Subclasses:
437
445
438 Previously, ``pinfo`` or ``pinfo2`` command had to be used for this purpose.
446 Previously, ``pinfo`` or ``pinfo2`` command had to be used for this purpose.
439
447
440
448
441 Autoreload 3 feature
449 Autoreload 3 feature
442 ~~~~~~~~~~~~~~~~~~~~
450 ~~~~~~~~~~~~~~~~~~~~
443
451
444 Example: When an IPython session is run with the 'autoreload' extension loaded,
452 Example: When an IPython session is run with the 'autoreload' extension loaded,
445 you will now have the option '3' to select, which means the following:
453 you will now have the option '3' to select, which means the following:
446
454
447 1. replicate all functionality from option 2
455 1. replicate all functionality from option 2
448 2. autoload all new funcs/classes/enums/globals from the module when they are added
456 2. autoload all new funcs/classes/enums/globals from the module when they are added
449 3. autoload all newly imported funcs/classes/enums/globals from external modules
457 3. autoload all newly imported funcs/classes/enums/globals from external modules
450
458
451 Try ``%autoreload 3`` in an IPython session after running ``%load_ext autoreload``.
459 Try ``%autoreload 3`` in an IPython session after running ``%load_ext autoreload``.
452
460
453 For more information please see the following unit test : ``extensions/tests/test_autoreload.py:test_autoload_newly_added_objects``
461 For more information please see the following unit test : ``extensions/tests/test_autoreload.py:test_autoload_newly_added_objects``
454
462
455 Auto formatting with black in the CLI
463 Auto formatting with black in the CLI
456 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
464 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
457
465
458 This feature was present in 7.x, but disabled by default.
466 This feature was present in 7.x, but disabled by default.
459
467
460 In 8.0, input was automatically reformatted with Black when black was installed.
468 In 8.0, input was automatically reformatted with Black when black was installed.
461 This feature has been reverted for the time being.
469 This feature has been reverted for the time being.
462 You can re-enable it by setting ``TerminalInteractiveShell.autoformatter`` to ``"black"``
470 You can re-enable it by setting ``TerminalInteractiveShell.autoformatter`` to ``"black"``
463
471
464 History Range Glob feature
472 History Range Glob feature
465 ~~~~~~~~~~~~~~~~~~~~~~~~~~
473 ~~~~~~~~~~~~~~~~~~~~~~~~~~
466
474
467 Previously, when using ``%history``, users could specify either
475 Previously, when using ``%history``, users could specify either
468 a range of sessions and lines, for example:
476 a range of sessions and lines, for example:
469
477
470 .. code-block:: python
478 .. code-block:: python
471
479
472 ~8/1-~6/5 # see history from the first line of 8 sessions ago,
480 ~8/1-~6/5 # see history from the first line of 8 sessions ago,
473 # to the fifth line of 6 sessions ago.``
481 # to the fifth line of 6 sessions ago.``
474
482
475 Or users could specify a glob pattern:
483 Or users could specify a glob pattern:
476
484
477 .. code-block:: python
485 .. code-block:: python
478
486
479 -g <pattern> # glob ALL history for the specified pattern.
487 -g <pattern> # glob ALL history for the specified pattern.
480
488
481 However users could *not* specify both.
489 However users could *not* specify both.
482
490
483 If a user *did* specify both a range and a glob pattern,
491 If a user *did* specify both a range and a glob pattern,
484 then the glob pattern would be used (globbing *all* history) *and the range would be ignored*.
492 then the glob pattern would be used (globbing *all* history) *and the range would be ignored*.
485
493
486 With this enhancement, if a user specifies both a range and a glob pattern, then the glob pattern will be applied to the specified range of history.
494 With this enhancement, if a user specifies both a range and a glob pattern, then the glob pattern will be applied to the specified range of history.
487
495
488 Don't start a multi-line cell with sunken parenthesis
496 Don't start a multi-line cell with sunken parenthesis
489 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
490
498
491 From now on, IPython will not ask for the next line of input when given a single
499 From now on, IPython will not ask for the next line of input when given a single
492 line with more closing than opening brackets. For example, this means that if
500 line with more closing than opening brackets. For example, this means that if
493 you (mis)type ``]]`` instead of ``[]``, a ``SyntaxError`` will show up, instead of
501 you (mis)type ``]]`` instead of ``[]``, a ``SyntaxError`` will show up, instead of
494 the ``...:`` prompt continuation.
502 the ``...:`` prompt continuation.
495
503
496 IPython shell for ipdb interact
504 IPython shell for ipdb interact
497 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
505 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
498
506
499 The ipdb ``interact`` starts an IPython shell instead of Python's built-in ``code.interact()``.
507 The ipdb ``interact`` starts an IPython shell instead of Python's built-in ``code.interact()``.
500
508
501 Automatic Vi prompt stripping
509 Automatic Vi prompt stripping
502 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
510 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
503
511
504 When pasting code into IPython, it will strip the leading prompt characters if
512 When pasting code into IPython, it will strip the leading prompt characters if
505 there are any. For example, you can paste the following code into the console -
513 there are any. For example, you can paste the following code into the console -
506 it will still work, even though each line is prefixed with prompts (`In`,
514 it will still work, even though each line is prefixed with prompts (`In`,
507 `Out`)::
515 `Out`)::
508
516
509 In [1]: 2 * 2 == 4
517 In [1]: 2 * 2 == 4
510 Out[1]: True
518 Out[1]: True
511
519
512 In [2]: print("This still works as pasted")
520 In [2]: print("This still works as pasted")
513
521
514
522
515 Previously, this was not the case for the Vi-mode prompts::
523 Previously, this was not the case for the Vi-mode prompts::
516
524
517 In [1]: [ins] In [13]: 2 * 2 == 4
525 In [1]: [ins] In [13]: 2 * 2 == 4
518 ...: Out[13]: True
526 ...: Out[13]: True
519 ...:
527 ...:
520 File "<ipython-input-1-727bb88eaf33>", line 1
528 File "<ipython-input-1-727bb88eaf33>", line 1
521 [ins] In [13]: 2 * 2 == 4
529 [ins] In [13]: 2 * 2 == 4
522 ^
530 ^
523 SyntaxError: invalid syntax
531 SyntaxError: invalid syntax
524
532
525 This is now fixed, and Vi prompt prefixes - ``[ins]`` and ``[nav]`` - are
533 This is now fixed, and Vi prompt prefixes - ``[ins]`` and ``[nav]`` - are
526 skipped just as the normal ``In`` would be.
534 skipped just as the normal ``In`` would be.
527
535
528 IPython shell can be started in the Vi mode using ``ipython --TerminalInteractiveShell.editing_mode=vi``,
536 IPython shell can be started in the Vi mode using ``ipython --TerminalInteractiveShell.editing_mode=vi``,
529 You should be able to change mode dynamically with ``%config TerminalInteractiveShell.editing_mode='vi'``
537 You should be able to change mode dynamically with ``%config TerminalInteractiveShell.editing_mode='vi'``
530
538
531 Empty History Ranges
539 Empty History Ranges
532 ~~~~~~~~~~~~~~~~~~~~
540 ~~~~~~~~~~~~~~~~~~~~
533
541
534 A number of magics that take history ranges can now be used with an empty
542 A number of magics that take history ranges can now be used with an empty
535 range. These magics are:
543 range. These magics are:
536
544
537 * ``%save``
545 * ``%save``
538 * ``%load``
546 * ``%load``
539 * ``%pastebin``
547 * ``%pastebin``
540 * ``%pycat``
548 * ``%pycat``
541
549
542 Using them this way will make them take the history of the current session up
550 Using them this way will make them take the history of the current session up
543 to the point of the magic call (such that the magic itself will not be
551 to the point of the magic call (such that the magic itself will not be
544 included).
552 included).
545
553
546 Therefore it is now possible to save the whole history to a file using
554 Therefore it is now possible to save the whole history to a file using
547 ``%save <filename>``, load and edit it using ``%load`` (makes for a nice usage
555 ``%save <filename>``, load and edit it using ``%load`` (makes for a nice usage
548 when followed with :kbd:`F2`), send it to `dpaste.org <http://dpast.org>`_ using
556 when followed with :kbd:`F2`), send it to `dpaste.org <http://dpast.org>`_ using
549 ``%pastebin``, or view the whole thing syntax-highlighted with a single
557 ``%pastebin``, or view the whole thing syntax-highlighted with a single
550 ``%pycat``.
558 ``%pycat``.
551
559
552
560
553 Windows timing implementation: Switch to process_time
561 Windows timing implementation: Switch to process_time
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
562 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
555 Timing on Windows, for example with ``%%time``, was changed from being based on ``time.perf_counter``
563 Timing on Windows, for example with ``%%time``, was changed from being based on ``time.perf_counter``
556 (which counted time even when the process was sleeping) to being based on ``time.process_time`` instead
564 (which counted time even when the process was sleeping) to being based on ``time.process_time`` instead
557 (which only counts CPU time). This brings it closer to the behavior on Linux. See :ghpull:`12984`.
565 (which only counts CPU time). This brings it closer to the behavior on Linux. See :ghpull:`12984`.
558
566
559 Miscellaneous
567 Miscellaneous
560 ~~~~~~~~~~~~~
568 ~~~~~~~~~~~~~
561 - Non-text formatters are not disabled in the terminal, which should simplify
569 - Non-text formatters are not disabled in the terminal, which should simplify
562 writing extensions displaying images or other mimetypes in supporting terminals.
570 writing extensions displaying images or other mimetypes in supporting terminals.
563 :ghpull:`12315`
571 :ghpull:`12315`
564 - It is now possible to automatically insert matching brackets in Terminal IPython using the
572 - It is now possible to automatically insert matching brackets in Terminal IPython using the
565 ``TerminalInteractiveShell.auto_match=True`` option. :ghpull:`12586`
573 ``TerminalInteractiveShell.auto_match=True`` option. :ghpull:`12586`
566 - We are thinking of deprecating the current ``%%javascript`` magic in favor of a better replacement. See :ghpull:`13376`.
574 - We are thinking of deprecating the current ``%%javascript`` magic in favor of a better replacement. See :ghpull:`13376`.
567 - ``~`` is now expanded when part of a path in most magics :ghpull:`13385`
575 - ``~`` is now expanded when part of a path in most magics :ghpull:`13385`
568 - ``%/%%timeit`` magic now adds a comma every thousands to make reading a long number easier :ghpull:`13379`
576 - ``%/%%timeit`` magic now adds a comma every thousands to make reading a long number easier :ghpull:`13379`
569 - ``"info"`` messages can now be customised to hide some fields :ghpull:`13343`
577 - ``"info"`` messages can now be customised to hide some fields :ghpull:`13343`
570 - ``collections.UserList`` now pretty-prints :ghpull:`13320`
578 - ``collections.UserList`` now pretty-prints :ghpull:`13320`
571 - The debugger now has a persistent history, which should make it less
579 - The debugger now has a persistent history, which should make it less
572 annoying to retype commands :ghpull:`13246`
580 annoying to retype commands :ghpull:`13246`
573 - ``!pip`` ``!conda`` ``!cd`` or ``!ls`` are likely doing the wrong thing. We
581 - ``!pip`` ``!conda`` ``!cd`` or ``!ls`` are likely doing the wrong thing. We
574 now warn users if they use one of those commands. :ghpull:`12954`
582 now warn users if they use one of those commands. :ghpull:`12954`
575 - Make ``%precision`` work for ``numpy.float64`` type :ghpull:`12902`
583 - Make ``%precision`` work for ``numpy.float64`` type :ghpull:`12902`
576
584
577 Re-added support for XDG config directories
585 Re-added support for XDG config directories
578 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
586 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
579
587
580 XDG support through the years comes and goes. There is a tension between having
588 XDG support through the years comes and goes. There is a tension between having
581 an identical location for configuration in all platforms versus having simple instructions.
589 an identical location for configuration in all platforms versus having simple instructions.
582 After initial failures a couple of years ago, IPython was modified to automatically migrate XDG
590 After initial failures a couple of years ago, IPython was modified to automatically migrate XDG
583 config files back into ``~/.ipython``. That migration code has now been removed.
591 config files back into ``~/.ipython``. That migration code has now been removed.
584 IPython now checks the XDG locations, so if you _manually_ move your config
592 IPython now checks the XDG locations, so if you _manually_ move your config
585 files to your preferred location, IPython will not move them back.
593 files to your preferred location, IPython will not move them back.
586
594
587
595
588 Preparing for Python 3.10
596 Preparing for Python 3.10
589 -------------------------
597 -------------------------
590
598
591 To prepare for Python 3.10, we have started working on removing reliance and
599 To prepare for Python 3.10, we have started working on removing reliance and
592 any dependency that is not compatible with Python 3.10. This includes migrating our
600 any dependency that is not compatible with Python 3.10. This includes migrating our
593 test suite to pytest and starting to remove nose. This also means that the
601 test suite to pytest and starting to remove nose. This also means that the
594 ``iptest`` command is now gone and all testing is via pytest.
602 ``iptest`` command is now gone and all testing is via pytest.
595
603
596 This was in large part thanks to the NumFOCUS Small Developer grant, which enabled us to
604 This was in large part thanks to the NumFOCUS Small Developer grant, which enabled us to
597 allocate \$4000 to hire `Nikita Kniazev (@Kojoley) <https://github.com/Kojoley>`_,
605 allocate \$4000 to hire `Nikita Kniazev (@Kojoley) <https://github.com/Kojoley>`_,
598 who did a fantastic job at updating our code base, migrating to pytest, pushing
606 who did a fantastic job at updating our code base, migrating to pytest, pushing
599 our coverage, and fixing a large number of bugs. I highly recommend contacting
607 our coverage, and fixing a large number of bugs. I highly recommend contacting
600 them if you need help with C++ and Python projects.
608 them if you need help with C++ and Python projects.
601
609
602 You can find all relevant issues and PRs with the SDG 2021 tag `<https://github.com/ipython/ipython/issues?q=label%3A%22Numfocus+SDG+2021%22+>`__
610 You can find all relevant issues and PRs with the SDG 2021 tag `<https://github.com/ipython/ipython/issues?q=label%3A%22Numfocus+SDG+2021%22+>`__
603
611
604 Removing support for older Python versions
612 Removing support for older Python versions
605 ------------------------------------------
613 ------------------------------------------
606
614
607
615
608 We are removing support for Python up through 3.7, allowing internal code to use the more
616 We are removing support for Python up through 3.7, allowing internal code to use the more
609 efficient ``pathlib`` and to make better use of type annotations.
617 efficient ``pathlib`` and to make better use of type annotations.
610
618
611 .. image:: ../_images/8.0/pathlib_pathlib_everywhere.jpg
619 .. image:: ../_images/8.0/pathlib_pathlib_everywhere.jpg
612 :alt: "Meme image of Toy Story with Woody and Buzz, with the text 'pathlib, pathlib everywhere'"
620 :alt: "Meme image of Toy Story with Woody and Buzz, with the text 'pathlib, pathlib everywhere'"
613
621
614
622
615 We had about 34 PRs only to update some logic to update some functions from managing strings to
623 We had about 34 PRs only to update some logic to update some functions from managing strings to
616 using Pathlib.
624 using Pathlib.
617
625
618 The completer has also seen significant updates and now makes use of newer Jedi APIs,
626 The completer has also seen significant updates and now makes use of newer Jedi APIs,
619 offering faster and more reliable tab completion.
627 offering faster and more reliable tab completion.
620
628
621 Misc Statistics
629 Misc Statistics
622 ---------------
630 ---------------
623
631
624 Here are some numbers::
632 Here are some numbers::
625
633
626 7.x: 296 files, 12561 blank lines, 20282 comments, 35142 line of code.
634 7.x: 296 files, 12561 blank lines, 20282 comments, 35142 line of code.
627 8.0: 252 files, 12053 blank lines, 19232 comments, 34505 line of code.
635 8.0: 252 files, 12053 blank lines, 19232 comments, 34505 line of code.
628
636
629 $ git diff --stat 7.x...master | tail -1
637 $ git diff --stat 7.x...master | tail -1
630 340 files changed, 13399 insertions(+), 12421 deletions(-)
638 340 files changed, 13399 insertions(+), 12421 deletions(-)
631
639
632 We have commits from 162 authors, who contributed 1916 commits in 23 month, excluding merges (to not bias toward
640 We have commits from 162 authors, who contributed 1916 commits in 23 month, excluding merges (to not bias toward
633 maintainers pushing buttons).::
641 maintainers pushing buttons).::
634
642
635 $ git shortlog -s --no-merges 7.x...master | sort -nr
643 $ git shortlog -s --no-merges 7.x...master | sort -nr
636 535 Matthias Bussonnier
644 535 Matthias Bussonnier
637 86 Nikita Kniazev
645 86 Nikita Kniazev
638 69 Blazej Michalik
646 69 Blazej Michalik
639 49 Samuel Gaist
647 49 Samuel Gaist
640 27 Itamar Turner-Trauring
648 27 Itamar Turner-Trauring
641 18 Spas Kalaydzhisyki
649 18 Spas Kalaydzhisyki
642 17 Thomas Kluyver
650 17 Thomas Kluyver
643 17 Quentin Peter
651 17 Quentin Peter
644 17 James Morris
652 17 James Morris
645 17 Artur Svistunov
653 17 Artur Svistunov
646 15 Bart Skowron
654 15 Bart Skowron
647 14 Alex Hall
655 14 Alex Hall
648 13 rushabh-v
656 13 rushabh-v
649 13 Terry Davis
657 13 Terry Davis
650 13 Benjamin Ragan-Kelley
658 13 Benjamin Ragan-Kelley
651 8 martinRenou
659 8 martinRenou
652 8 farisachugthai
660 8 farisachugthai
653 7 dswij
661 7 dswij
654 7 Gal B
662 7 Gal B
655 7 Corentin Cadiou
663 7 Corentin Cadiou
656 6 yuji96
664 6 yuji96
657 6 Martin Skarzynski
665 6 Martin Skarzynski
658 6 Justin Palmer
666 6 Justin Palmer
659 6 Daniel Goldfarb
667 6 Daniel Goldfarb
660 6 Ben Greiner
668 6 Ben Greiner
661 5 Sammy Al Hashemi
669 5 Sammy Al Hashemi
662 5 Paul Ivanov
670 5 Paul Ivanov
663 5 Inception95
671 5 Inception95
664 5 Eyenpi
672 5 Eyenpi
665 5 Douglas Blank
673 5 Douglas Blank
666 5 Coco Mishra
674 5 Coco Mishra
667 5 Bibo Hao
675 5 Bibo Hao
668 5 AndrΓ© A. Gomes
676 5 AndrΓ© A. Gomes
669 5 Ahmed Fasih
677 5 Ahmed Fasih
670 4 takuya fujiwara
678 4 takuya fujiwara
671 4 palewire
679 4 palewire
672 4 Thomas A Caswell
680 4 Thomas A Caswell
673 4 Talley Lambert
681 4 Talley Lambert
674 4 Scott Sanderson
682 4 Scott Sanderson
675 4 Ram Rachum
683 4 Ram Rachum
676 4 Nick Muoh
684 4 Nick Muoh
677 4 Nathan Goldbaum
685 4 Nathan Goldbaum
678 4 Mithil Poojary
686 4 Mithil Poojary
679 4 Michael T
687 4 Michael T
680 4 Jakub Klus
688 4 Jakub Klus
681 4 Ian Castleden
689 4 Ian Castleden
682 4 Eli Rykoff
690 4 Eli Rykoff
683 4 Ashwin Vishnu
691 4 Ashwin Vishnu
684 3 谭九鼎
692 3 谭九鼎
685 3 sleeping
693 3 sleeping
686 3 Sylvain Corlay
694 3 Sylvain Corlay
687 3 Peter Corke
695 3 Peter Corke
688 3 Paul Bissex
696 3 Paul Bissex
689 3 Matthew Feickert
697 3 Matthew Feickert
690 3 Fernando Perez
698 3 Fernando Perez
691 3 Eric Wieser
699 3 Eric Wieser
692 3 Daniel Mietchen
700 3 Daniel Mietchen
693 3 Aditya Sathe
701 3 Aditya Sathe
694 3 007vedant
702 3 007vedant
695 2 rchiodo
703 2 rchiodo
696 2 nicolaslazo
704 2 nicolaslazo
697 2 luttik
705 2 luttik
698 2 gorogoroumaru
706 2 gorogoroumaru
699 2 foobarbyte
707 2 foobarbyte
700 2 bar-hen
708 2 bar-hen
701 2 Theo Ouzhinski
709 2 Theo Ouzhinski
702 2 Strawkage
710 2 Strawkage
703 2 Samreen Zarroug
711 2 Samreen Zarroug
704 2 Pete Blois
712 2 Pete Blois
705 2 Meysam Azad
713 2 Meysam Azad
706 2 Matthieu Ancellin
714 2 Matthieu Ancellin
707 2 Mark Schmitz
715 2 Mark Schmitz
708 2 Maor Kleinberger
716 2 Maor Kleinberger
709 2 MRCWirtz
717 2 MRCWirtz
710 2 Lumir Balhar
718 2 Lumir Balhar
711 2 Julien Rabinow
719 2 Julien Rabinow
712 2 Juan Luis Cano RodrΓ­guez
720 2 Juan Luis Cano RodrΓ­guez
713 2 Joyce Er
721 2 Joyce Er
714 2 Jakub
722 2 Jakub
715 2 Faris A Chugthai
723 2 Faris A Chugthai
716 2 Ethan Madden
724 2 Ethan Madden
717 2 Dimitri Papadopoulos
725 2 Dimitri Papadopoulos
718 2 Diego Fernandez
726 2 Diego Fernandez
719 2 Daniel Shimon
727 2 Daniel Shimon
720 2 Coco Bennett
728 2 Coco Bennett
721 2 Carlos Cordoba
729 2 Carlos Cordoba
722 2 Boyuan Liu
730 2 Boyuan Liu
723 2 BaoGiang HoangVu
731 2 BaoGiang HoangVu
724 2 Augusto
732 2 Augusto
725 2 Arthur Svistunov
733 2 Arthur Svistunov
726 2 Arthur Moreira
734 2 Arthur Moreira
727 2 Ali Nabipour
735 2 Ali Nabipour
728 2 Adam Hackbarth
736 2 Adam Hackbarth
729 1 richard
737 1 richard
730 1 linar-jether
738 1 linar-jether
731 1 lbennett
739 1 lbennett
732 1 juacrumar
740 1 juacrumar
733 1 gpotter2
741 1 gpotter2
734 1 digitalvirtuoso
742 1 digitalvirtuoso
735 1 dalthviz
743 1 dalthviz
736 1 Yonatan Goldschmidt
744 1 Yonatan Goldschmidt
737 1 Tomasz KΕ‚oczko
745 1 Tomasz KΕ‚oczko
738 1 Tobias Bengfort
746 1 Tobias Bengfort
739 1 Timur Kushukov
747 1 Timur Kushukov
740 1 Thomas
748 1 Thomas
741 1 Snir Broshi
749 1 Snir Broshi
742 1 Shao Yang Hong
750 1 Shao Yang Hong
743 1 Sanjana-03
751 1 Sanjana-03
744 1 Romulo Filho
752 1 Romulo Filho
745 1 Rodolfo Carvalho
753 1 Rodolfo Carvalho
746 1 Richard Shadrach
754 1 Richard Shadrach
747 1 Reilly Tucker Siemens
755 1 Reilly Tucker Siemens
748 1 Rakessh Roshan
756 1 Rakessh Roshan
749 1 Piers Titus van der Torren
757 1 Piers Titus van der Torren
750 1 PhanatosZou
758 1 PhanatosZou
751 1 Pavel Safronov
759 1 Pavel Safronov
752 1 Paulo S. Costa
760 1 Paulo S. Costa
753 1 Paul McCarthy
761 1 Paul McCarthy
754 1 NotWearingPants
762 1 NotWearingPants
755 1 Naelson Douglas
763 1 Naelson Douglas
756 1 Michael Tiemann
764 1 Michael Tiemann
757 1 Matt Wozniski
765 1 Matt Wozniski
758 1 Markus Wageringel
766 1 Markus Wageringel
759 1 Marcus Wirtz
767 1 Marcus Wirtz
760 1 Marcio Mazza
768 1 Marcio Mazza
761 1 LumΓ­r 'Frenzy' Balhar
769 1 LumΓ­r 'Frenzy' Balhar
762 1 Lightyagami1
770 1 Lightyagami1
763 1 Leon Anavi
771 1 Leon Anavi
764 1 LeafyLi
772 1 LeafyLi
765 1 L0uisJ0shua
773 1 L0uisJ0shua
766 1 Kyle Cutler
774 1 Kyle Cutler
767 1 Krzysztof Cybulski
775 1 Krzysztof Cybulski
768 1 Kevin Kirsche
776 1 Kevin Kirsche
769 1 KIU Shueng Chuan
777 1 KIU Shueng Chuan
770 1 Jonathan Slenders
778 1 Jonathan Slenders
771 1 Jay Qi
779 1 Jay Qi
772 1 Jake VanderPlas
780 1 Jake VanderPlas
773 1 Iwan Briquemont
781 1 Iwan Briquemont
774 1 Hussaina Begum Nandyala
782 1 Hussaina Begum Nandyala
775 1 Gordon Ball
783 1 Gordon Ball
776 1 Gabriel Simonetto
784 1 Gabriel Simonetto
777 1 Frank Tobia
785 1 Frank Tobia
778 1 Erik
786 1 Erik
779 1 Elliott Sales de Andrade
787 1 Elliott Sales de Andrade
780 1 Daniel Hahler
788 1 Daniel Hahler
781 1 Dan Green-Leipciger
789 1 Dan Green-Leipciger
782 1 Dan Green
790 1 Dan Green
783 1 Damian Yurzola
791 1 Damian Yurzola
784 1 Coon, Ethan T
792 1 Coon, Ethan T
785 1 Carol Willing
793 1 Carol Willing
786 1 Brian Lee
794 1 Brian Lee
787 1 Brendan Gerrity
795 1 Brendan Gerrity
788 1 Blake Griffin
796 1 Blake Griffin
789 1 Bastian Ebeling
797 1 Bastian Ebeling
790 1 Bartosz Telenczuk
798 1 Bartosz Telenczuk
791 1 Ankitsingh6299
799 1 Ankitsingh6299
792 1 Andrew Port
800 1 Andrew Port
793 1 Andrew J. Hesford
801 1 Andrew J. Hesford
794 1 Albert Zhang
802 1 Albert Zhang
795 1 Adam Johnson
803 1 Adam Johnson
796
804
797 This does not, of course, represent non-code contributions, for which we are also grateful.
805 This does not, of course, represent non-code contributions, for which we are also grateful.
798
806
799
807
800 API Changes using Frappuccino
808 API Changes using Frappuccino
801 -----------------------------
809 -----------------------------
802
810
803 This is an experimental exhaustive API difference using `Frappuccino <https://pypi.org/project/frappuccino/>`_
811 This is an experimental exhaustive API difference using `Frappuccino <https://pypi.org/project/frappuccino/>`_
804
812
805
813
806 The following items are new in IPython 8.0 ::
814 The following items are new in IPython 8.0 ::
807
815
808 + IPython.core.async_helpers.get_asyncio_loop()
816 + IPython.core.async_helpers.get_asyncio_loop()
809 + IPython.core.completer.Dict
817 + IPython.core.completer.Dict
810 + IPython.core.completer.Pattern
818 + IPython.core.completer.Pattern
811 + IPython.core.completer.Sequence
819 + IPython.core.completer.Sequence
812 + IPython.core.completer.__skip_doctest__
820 + IPython.core.completer.__skip_doctest__
813 + IPython.core.debugger.Pdb.precmd(self, line)
821 + IPython.core.debugger.Pdb.precmd(self, line)
814 + IPython.core.debugger.__skip_doctest__
822 + IPython.core.debugger.__skip_doctest__
815 + IPython.core.display.__getattr__(name)
823 + IPython.core.display.__getattr__(name)
816 + IPython.core.display.warn
824 + IPython.core.display.warn
817 + IPython.core.display_functions
825 + IPython.core.display_functions
818 + IPython.core.display_functions.DisplayHandle
826 + IPython.core.display_functions.DisplayHandle
819 + IPython.core.display_functions.DisplayHandle.display(self, obj, **kwargs)
827 + IPython.core.display_functions.DisplayHandle.display(self, obj, **kwargs)
820 + IPython.core.display_functions.DisplayHandle.update(self, obj, **kwargs)
828 + IPython.core.display_functions.DisplayHandle.update(self, obj, **kwargs)
821 + IPython.core.display_functions.__all__
829 + IPython.core.display_functions.__all__
822 + IPython.core.display_functions.__builtins__
830 + IPython.core.display_functions.__builtins__
823 + IPython.core.display_functions.__cached__
831 + IPython.core.display_functions.__cached__
824 + IPython.core.display_functions.__doc__
832 + IPython.core.display_functions.__doc__
825 + IPython.core.display_functions.__file__
833 + IPython.core.display_functions.__file__
826 + IPython.core.display_functions.__loader__
834 + IPython.core.display_functions.__loader__
827 + IPython.core.display_functions.__name__
835 + IPython.core.display_functions.__name__
828 + IPython.core.display_functions.__package__
836 + IPython.core.display_functions.__package__
829 + IPython.core.display_functions.__spec__
837 + IPython.core.display_functions.__spec__
830 + IPython.core.display_functions.b2a_hex
838 + IPython.core.display_functions.b2a_hex
831 + IPython.core.display_functions.clear_output(wait=False)
839 + IPython.core.display_functions.clear_output(wait=False)
832 + IPython.core.display_functions.display(*objs, include='None', exclude='None', metadata='None', transient='None', display_id='None', raw=False, clear=False, **kwargs)
840 + IPython.core.display_functions.display(*objs, include='None', exclude='None', metadata='None', transient='None', display_id='None', raw=False, clear=False, **kwargs)
833 + IPython.core.display_functions.publish_display_data(data, metadata='None', source='<deprecated>', *, transient='None', **kwargs)
841 + IPython.core.display_functions.publish_display_data(data, metadata='None', source='<deprecated>', *, transient='None', **kwargs)
834 + IPython.core.display_functions.update_display(obj, *, display_id, **kwargs)
842 + IPython.core.display_functions.update_display(obj, *, display_id, **kwargs)
835 + IPython.core.extensions.BUILTINS_EXTS
843 + IPython.core.extensions.BUILTINS_EXTS
836 + IPython.core.inputtransformer2.has_sunken_brackets(tokens)
844 + IPython.core.inputtransformer2.has_sunken_brackets(tokens)
837 + IPython.core.interactiveshell.Callable
845 + IPython.core.interactiveshell.Callable
838 + IPython.core.interactiveshell.__annotations__
846 + IPython.core.interactiveshell.__annotations__
839 + IPython.core.ultratb.List
847 + IPython.core.ultratb.List
840 + IPython.core.ultratb.Tuple
848 + IPython.core.ultratb.Tuple
841 + IPython.lib.pretty.CallExpression
849 + IPython.lib.pretty.CallExpression
842 + IPython.lib.pretty.CallExpression.factory(name)
850 + IPython.lib.pretty.CallExpression.factory(name)
843 + IPython.lib.pretty.RawStringLiteral
851 + IPython.lib.pretty.RawStringLiteral
844 + IPython.lib.pretty.RawText
852 + IPython.lib.pretty.RawText
845 + IPython.terminal.debugger.TerminalPdb.do_interact(self, arg)
853 + IPython.terminal.debugger.TerminalPdb.do_interact(self, arg)
846 + IPython.terminal.embed.Set
854 + IPython.terminal.embed.Set
847
855
848 The following items have been removed (or moved to superclass)::
856 The following items have been removed (or moved to superclass)::
849
857
850 - IPython.core.application.BaseIPythonApplication.initialize_subcommand
858 - IPython.core.application.BaseIPythonApplication.initialize_subcommand
851 - IPython.core.completer.Sentinel
859 - IPython.core.completer.Sentinel
852 - IPython.core.completer.skip_doctest
860 - IPython.core.completer.skip_doctest
853 - IPython.core.debugger.Tracer
861 - IPython.core.debugger.Tracer
854 - IPython.core.display.DisplayHandle
862 - IPython.core.display.DisplayHandle
855 - IPython.core.display.DisplayHandle.display
863 - IPython.core.display.DisplayHandle.display
856 - IPython.core.display.DisplayHandle.update
864 - IPython.core.display.DisplayHandle.update
857 - IPython.core.display.b2a_hex
865 - IPython.core.display.b2a_hex
858 - IPython.core.display.clear_output
866 - IPython.core.display.clear_output
859 - IPython.core.display.display
867 - IPython.core.display.display
860 - IPython.core.display.publish_display_data
868 - IPython.core.display.publish_display_data
861 - IPython.core.display.update_display
869 - IPython.core.display.update_display
862 - IPython.core.excolors.Deprec
870 - IPython.core.excolors.Deprec
863 - IPython.core.excolors.ExceptionColors
871 - IPython.core.excolors.ExceptionColors
864 - IPython.core.history.warn
872 - IPython.core.history.warn
865 - IPython.core.hooks.late_startup_hook
873 - IPython.core.hooks.late_startup_hook
866 - IPython.core.hooks.pre_run_code_hook
874 - IPython.core.hooks.pre_run_code_hook
867 - IPython.core.hooks.shutdown_hook
875 - IPython.core.hooks.shutdown_hook
868 - IPython.core.interactiveshell.InteractiveShell.init_deprecation_warnings
876 - IPython.core.interactiveshell.InteractiveShell.init_deprecation_warnings
869 - IPython.core.interactiveshell.InteractiveShell.init_readline
877 - IPython.core.interactiveshell.InteractiveShell.init_readline
870 - IPython.core.interactiveshell.InteractiveShell.write
878 - IPython.core.interactiveshell.InteractiveShell.write
871 - IPython.core.interactiveshell.InteractiveShell.write_err
879 - IPython.core.interactiveshell.InteractiveShell.write_err
872 - IPython.core.interactiveshell.get_default_colors
880 - IPython.core.interactiveshell.get_default_colors
873 - IPython.core.interactiveshell.removed_co_newlocals
881 - IPython.core.interactiveshell.removed_co_newlocals
874 - IPython.core.magics.execution.ExecutionMagics.profile_missing_notice
882 - IPython.core.magics.execution.ExecutionMagics.profile_missing_notice
875 - IPython.core.magics.script.PIPE
883 - IPython.core.magics.script.PIPE
876 - IPython.core.prefilter.PrefilterManager.init_transformers
884 - IPython.core.prefilter.PrefilterManager.init_transformers
877 - IPython.core.release.classifiers
885 - IPython.core.release.classifiers
878 - IPython.core.release.description
886 - IPython.core.release.description
879 - IPython.core.release.keywords
887 - IPython.core.release.keywords
880 - IPython.core.release.long_description
888 - IPython.core.release.long_description
881 - IPython.core.release.name
889 - IPython.core.release.name
882 - IPython.core.release.platforms
890 - IPython.core.release.platforms
883 - IPython.core.release.url
891 - IPython.core.release.url
884 - IPython.core.ultratb.VerboseTB.format_records
892 - IPython.core.ultratb.VerboseTB.format_records
885 - IPython.core.ultratb.find_recursion
893 - IPython.core.ultratb.find_recursion
886 - IPython.core.ultratb.findsource
894 - IPython.core.ultratb.findsource
887 - IPython.core.ultratb.fix_frame_records_filenames
895 - IPython.core.ultratb.fix_frame_records_filenames
888 - IPython.core.ultratb.inspect_error
896 - IPython.core.ultratb.inspect_error
889 - IPython.core.ultratb.is_recursion_error
897 - IPython.core.ultratb.is_recursion_error
890 - IPython.core.ultratb.with_patch_inspect
898 - IPython.core.ultratb.with_patch_inspect
891 - IPython.external.__all__
899 - IPython.external.__all__
892 - IPython.external.__builtins__
900 - IPython.external.__builtins__
893 - IPython.external.__cached__
901 - IPython.external.__cached__
894 - IPython.external.__doc__
902 - IPython.external.__doc__
895 - IPython.external.__file__
903 - IPython.external.__file__
896 - IPython.external.__loader__
904 - IPython.external.__loader__
897 - IPython.external.__name__
905 - IPython.external.__name__
898 - IPython.external.__package__
906 - IPython.external.__package__
899 - IPython.external.__path__
907 - IPython.external.__path__
900 - IPython.external.__spec__
908 - IPython.external.__spec__
901 - IPython.kernel.KernelConnectionInfo
909 - IPython.kernel.KernelConnectionInfo
902 - IPython.kernel.__builtins__
910 - IPython.kernel.__builtins__
903 - IPython.kernel.__cached__
911 - IPython.kernel.__cached__
904 - IPython.kernel.__warningregistry__
912 - IPython.kernel.__warningregistry__
905 - IPython.kernel.pkg
913 - IPython.kernel.pkg
906 - IPython.kernel.protocol_version
914 - IPython.kernel.protocol_version
907 - IPython.kernel.protocol_version_info
915 - IPython.kernel.protocol_version_info
908 - IPython.kernel.src
916 - IPython.kernel.src
909 - IPython.kernel.version_info
917 - IPython.kernel.version_info
910 - IPython.kernel.warn
918 - IPython.kernel.warn
911 - IPython.lib.backgroundjobs
919 - IPython.lib.backgroundjobs
912 - IPython.lib.backgroundjobs.BackgroundJobBase
920 - IPython.lib.backgroundjobs.BackgroundJobBase
913 - IPython.lib.backgroundjobs.BackgroundJobBase.run
921 - IPython.lib.backgroundjobs.BackgroundJobBase.run
914 - IPython.lib.backgroundjobs.BackgroundJobBase.traceback
922 - IPython.lib.backgroundjobs.BackgroundJobBase.traceback
915 - IPython.lib.backgroundjobs.BackgroundJobExpr
923 - IPython.lib.backgroundjobs.BackgroundJobExpr
916 - IPython.lib.backgroundjobs.BackgroundJobExpr.call
924 - IPython.lib.backgroundjobs.BackgroundJobExpr.call
917 - IPython.lib.backgroundjobs.BackgroundJobFunc
925 - IPython.lib.backgroundjobs.BackgroundJobFunc
918 - IPython.lib.backgroundjobs.BackgroundJobFunc.call
926 - IPython.lib.backgroundjobs.BackgroundJobFunc.call
919 - IPython.lib.backgroundjobs.BackgroundJobManager
927 - IPython.lib.backgroundjobs.BackgroundJobManager
920 - IPython.lib.backgroundjobs.BackgroundJobManager.flush
928 - IPython.lib.backgroundjobs.BackgroundJobManager.flush
921 - IPython.lib.backgroundjobs.BackgroundJobManager.new
929 - IPython.lib.backgroundjobs.BackgroundJobManager.new
922 - IPython.lib.backgroundjobs.BackgroundJobManager.remove
930 - IPython.lib.backgroundjobs.BackgroundJobManager.remove
923 - IPython.lib.backgroundjobs.BackgroundJobManager.result
931 - IPython.lib.backgroundjobs.BackgroundJobManager.result
924 - IPython.lib.backgroundjobs.BackgroundJobManager.status
932 - IPython.lib.backgroundjobs.BackgroundJobManager.status
925 - IPython.lib.backgroundjobs.BackgroundJobManager.traceback
933 - IPython.lib.backgroundjobs.BackgroundJobManager.traceback
926 - IPython.lib.backgroundjobs.__builtins__
934 - IPython.lib.backgroundjobs.__builtins__
927 - IPython.lib.backgroundjobs.__cached__
935 - IPython.lib.backgroundjobs.__cached__
928 - IPython.lib.backgroundjobs.__doc__
936 - IPython.lib.backgroundjobs.__doc__
929 - IPython.lib.backgroundjobs.__file__
937 - IPython.lib.backgroundjobs.__file__
930 - IPython.lib.backgroundjobs.__loader__
938 - IPython.lib.backgroundjobs.__loader__
931 - IPython.lib.backgroundjobs.__name__
939 - IPython.lib.backgroundjobs.__name__
932 - IPython.lib.backgroundjobs.__package__
940 - IPython.lib.backgroundjobs.__package__
933 - IPython.lib.backgroundjobs.__spec__
941 - IPython.lib.backgroundjobs.__spec__
934 - IPython.lib.kernel.__builtins__
942 - IPython.lib.kernel.__builtins__
935 - IPython.lib.kernel.__cached__
943 - IPython.lib.kernel.__cached__
936 - IPython.lib.kernel.__doc__
944 - IPython.lib.kernel.__doc__
937 - IPython.lib.kernel.__file__
945 - IPython.lib.kernel.__file__
938 - IPython.lib.kernel.__loader__
946 - IPython.lib.kernel.__loader__
939 - IPython.lib.kernel.__name__
947 - IPython.lib.kernel.__name__
940 - IPython.lib.kernel.__package__
948 - IPython.lib.kernel.__package__
941 - IPython.lib.kernel.__spec__
949 - IPython.lib.kernel.__spec__
942 - IPython.lib.kernel.__warningregistry__
950 - IPython.lib.kernel.__warningregistry__
943 - IPython.paths.fs_encoding
951 - IPython.paths.fs_encoding
944 - IPython.terminal.debugger.DEFAULT_BUFFER
952 - IPython.terminal.debugger.DEFAULT_BUFFER
945 - IPython.terminal.debugger.cursor_in_leading_ws
953 - IPython.terminal.debugger.cursor_in_leading_ws
946 - IPython.terminal.debugger.emacs_insert_mode
954 - IPython.terminal.debugger.emacs_insert_mode
947 - IPython.terminal.debugger.has_selection
955 - IPython.terminal.debugger.has_selection
948 - IPython.terminal.debugger.vi_insert_mode
956 - IPython.terminal.debugger.vi_insert_mode
949 - IPython.terminal.interactiveshell.DISPLAY_BANNER_DEPRECATED
957 - IPython.terminal.interactiveshell.DISPLAY_BANNER_DEPRECATED
950 - IPython.terminal.ipapp.TerminalIPythonApp.parse_command_line
958 - IPython.terminal.ipapp.TerminalIPythonApp.parse_command_line
951 - IPython.testing.test
959 - IPython.testing.test
952 - IPython.utils.contexts.NoOpContext
960 - IPython.utils.contexts.NoOpContext
953 - IPython.utils.io.IOStream
961 - IPython.utils.io.IOStream
954 - IPython.utils.io.IOStream.close
962 - IPython.utils.io.IOStream.close
955 - IPython.utils.io.IOStream.write
963 - IPython.utils.io.IOStream.write
956 - IPython.utils.io.IOStream.writelines
964 - IPython.utils.io.IOStream.writelines
957 - IPython.utils.io.__warningregistry__
965 - IPython.utils.io.__warningregistry__
958 - IPython.utils.io.atomic_writing
966 - IPython.utils.io.atomic_writing
959 - IPython.utils.io.stderr
967 - IPython.utils.io.stderr
960 - IPython.utils.io.stdin
968 - IPython.utils.io.stdin
961 - IPython.utils.io.stdout
969 - IPython.utils.io.stdout
962 - IPython.utils.io.unicode_std_stream
970 - IPython.utils.io.unicode_std_stream
963 - IPython.utils.path.get_ipython_cache_dir
971 - IPython.utils.path.get_ipython_cache_dir
964 - IPython.utils.path.get_ipython_dir
972 - IPython.utils.path.get_ipython_dir
965 - IPython.utils.path.get_ipython_module_path
973 - IPython.utils.path.get_ipython_module_path
966 - IPython.utils.path.get_ipython_package_dir
974 - IPython.utils.path.get_ipython_package_dir
967 - IPython.utils.path.locate_profile
975 - IPython.utils.path.locate_profile
968 - IPython.utils.path.unquote_filename
976 - IPython.utils.path.unquote_filename
969 - IPython.utils.py3compat.PY2
977 - IPython.utils.py3compat.PY2
970 - IPython.utils.py3compat.PY3
978 - IPython.utils.py3compat.PY3
971 - IPython.utils.py3compat.buffer_to_bytes
979 - IPython.utils.py3compat.buffer_to_bytes
972 - IPython.utils.py3compat.builtin_mod_name
980 - IPython.utils.py3compat.builtin_mod_name
973 - IPython.utils.py3compat.cast_bytes
981 - IPython.utils.py3compat.cast_bytes
974 - IPython.utils.py3compat.getcwd
982 - IPython.utils.py3compat.getcwd
975 - IPython.utils.py3compat.isidentifier
983 - IPython.utils.py3compat.isidentifier
976 - IPython.utils.py3compat.u_format
984 - IPython.utils.py3compat.u_format
977
985
978 The following signatures differ between 7.x and 8.0::
986 The following signatures differ between 7.x and 8.0::
979
987
980 - IPython.core.completer.IPCompleter.unicode_name_matches(self, text)
988 - IPython.core.completer.IPCompleter.unicode_name_matches(self, text)
981 + IPython.core.completer.IPCompleter.unicode_name_matches(text)
989 + IPython.core.completer.IPCompleter.unicode_name_matches(text)
982
990
983 - IPython.core.completer.match_dict_keys(keys, prefix, delims)
991 - IPython.core.completer.match_dict_keys(keys, prefix, delims)
984 + IPython.core.completer.match_dict_keys(keys, prefix, delims, extra_prefix='None')
992 + IPython.core.completer.match_dict_keys(keys, prefix, delims, extra_prefix='None')
985
993
986 - IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0)
994 - IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0)
987 + IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0, omit_sections='()')
995 + IPython.core.interactiveshell.InteractiveShell.object_inspect_mime(self, oname, detail_level=0, omit_sections='()')
988
996
989 - IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None', _warn_deprecated=True)
997 - IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None', _warn_deprecated=True)
990 + IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None')
998 + IPython.core.interactiveshell.InteractiveShell.set_hook(self, name, hook, priority=50, str_key='None', re_key='None')
991
999
992 - IPython.core.oinspect.Inspector.info(self, obj, oname='', formatter='None', info='None', detail_level=0)
1000 - IPython.core.oinspect.Inspector.info(self, obj, oname='', formatter='None', info='None', detail_level=0)
993 + IPython.core.oinspect.Inspector.info(self, obj, oname='', info='None', detail_level=0)
1001 + IPython.core.oinspect.Inspector.info(self, obj, oname='', info='None', detail_level=0)
994
1002
995 - IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True)
1003 - IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True)
996 + IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True, omit_sections='()')
1004 + IPython.core.oinspect.Inspector.pinfo(self, obj, oname='', formatter='None', info='None', detail_level=0, enable_html_pager=True, omit_sections='()')
997
1005
998 - IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path='None', overwrite=False)
1006 - IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path='None', overwrite=False)
999 + IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path, overwrite=False)
1007 + IPython.core.profiledir.ProfileDir.copy_config_file(self, config_file, path, overwrite=False)
1000
1008
1001 - IPython.core.ultratb.VerboseTB.format_record(self, frame, file, lnum, func, lines, index)
1009 - IPython.core.ultratb.VerboseTB.format_record(self, frame, file, lnum, func, lines, index)
1002 + IPython.core.ultratb.VerboseTB.format_record(self, frame_info)
1010 + IPython.core.ultratb.VerboseTB.format_record(self, frame_info)
1003
1011
1004 - IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, display_banner='None', global_ns='None', compile_flags='None')
1012 - IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, display_banner='None', global_ns='None', compile_flags='None')
1005 + IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, compile_flags='None')
1013 + IPython.terminal.embed.InteractiveShellEmbed.mainloop(self, local_ns='None', module='None', stack_depth=0, compile_flags='None')
1006
1014
1007 - IPython.terminal.embed.embed(**kwargs)
1015 - IPython.terminal.embed.embed(**kwargs)
1008 + IPython.terminal.embed.embed(*, header='', compile_flags='None', **kwargs)
1016 + IPython.terminal.embed.embed(*, header='', compile_flags='None', **kwargs)
1009
1017
1010 - IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self, display_banner='<object object at 0xffffff>')
1018 - IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self, display_banner='<object object at 0xffffff>')
1011 + IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self)
1019 + IPython.terminal.interactiveshell.TerminalInteractiveShell.interact(self)
1012
1020
1013 - IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self, display_banner='<object object at 0xffffff>')
1021 - IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self, display_banner='<object object at 0xffffff>')
1014 + IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self)
1022 + IPython.terminal.interactiveshell.TerminalInteractiveShell.mainloop(self)
1015
1023
1016 - IPython.utils.path.get_py_filename(name, force_win32='None')
1024 - IPython.utils.path.get_py_filename(name, force_win32='None')
1017 + IPython.utils.path.get_py_filename(name)
1025 + IPython.utils.path.get_py_filename(name)
1018
1026
1019 The following are new attributes (that might be inherited)::
1027 The following are new attributes (that might be inherited)::
1020
1028
1021 + IPython.core.completer.IPCompleter.unicode_names
1029 + IPython.core.completer.IPCompleter.unicode_names
1022 + IPython.core.debugger.InterruptiblePdb.precmd
1030 + IPython.core.debugger.InterruptiblePdb.precmd
1023 + IPython.core.debugger.Pdb.precmd
1031 + IPython.core.debugger.Pdb.precmd
1024 + IPython.core.ultratb.AutoFormattedTB.has_colors
1032 + IPython.core.ultratb.AutoFormattedTB.has_colors
1025 + IPython.core.ultratb.ColorTB.has_colors
1033 + IPython.core.ultratb.ColorTB.has_colors
1026 + IPython.core.ultratb.FormattedTB.has_colors
1034 + IPython.core.ultratb.FormattedTB.has_colors
1027 + IPython.core.ultratb.ListTB.has_colors
1035 + IPython.core.ultratb.ListTB.has_colors
1028 + IPython.core.ultratb.SyntaxTB.has_colors
1036 + IPython.core.ultratb.SyntaxTB.has_colors
1029 + IPython.core.ultratb.TBTools.has_colors
1037 + IPython.core.ultratb.TBTools.has_colors
1030 + IPython.core.ultratb.VerboseTB.has_colors
1038 + IPython.core.ultratb.VerboseTB.has_colors
1031 + IPython.terminal.debugger.TerminalPdb.do_interact
1039 + IPython.terminal.debugger.TerminalPdb.do_interact
1032 + IPython.terminal.debugger.TerminalPdb.precmd
1040 + IPython.terminal.debugger.TerminalPdb.precmd
1033
1041
1034 The following attribute/methods have been removed::
1042 The following attribute/methods have been removed::
1035
1043
1036 - IPython.core.application.BaseIPythonApplication.deprecated_subcommands
1044 - IPython.core.application.BaseIPythonApplication.deprecated_subcommands
1037 - IPython.core.ultratb.AutoFormattedTB.format_records
1045 - IPython.core.ultratb.AutoFormattedTB.format_records
1038 - IPython.core.ultratb.ColorTB.format_records
1046 - IPython.core.ultratb.ColorTB.format_records
1039 - IPython.core.ultratb.FormattedTB.format_records
1047 - IPython.core.ultratb.FormattedTB.format_records
1040 - IPython.terminal.embed.InteractiveShellEmbed.init_deprecation_warnings
1048 - IPython.terminal.embed.InteractiveShellEmbed.init_deprecation_warnings
1041 - IPython.terminal.embed.InteractiveShellEmbed.init_readline
1049 - IPython.terminal.embed.InteractiveShellEmbed.init_readline
1042 - IPython.terminal.embed.InteractiveShellEmbed.write
1050 - IPython.terminal.embed.InteractiveShellEmbed.write
1043 - IPython.terminal.embed.InteractiveShellEmbed.write_err
1051 - IPython.terminal.embed.InteractiveShellEmbed.write_err
1044 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_deprecation_warnings
1052 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_deprecation_warnings
1045 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_readline
1053 - IPython.terminal.interactiveshell.TerminalInteractiveShell.init_readline
1046 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write
1054 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write
1047 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write_err
1055 - IPython.terminal.interactiveshell.TerminalInteractiveShell.write_err
1048 - IPython.terminal.ipapp.LocateIPythonApp.deprecated_subcommands
1056 - IPython.terminal.ipapp.LocateIPythonApp.deprecated_subcommands
1049 - IPython.terminal.ipapp.LocateIPythonApp.initialize_subcommand
1057 - IPython.terminal.ipapp.LocateIPythonApp.initialize_subcommand
1050 - IPython.terminal.ipapp.TerminalIPythonApp.deprecated_subcommands
1058 - IPython.terminal.ipapp.TerminalIPythonApp.deprecated_subcommands
1051 - IPython.terminal.ipapp.TerminalIPythonApp.initialize_subcommand
1059 - IPython.terminal.ipapp.TerminalIPythonApp.initialize_subcommand
General Comments 0
You need to be logged in to leave comments. Login now