##// END OF EJS Templates
Allow to get cellid from ipykernel...
Matthias Bussonnier -
Show More
@@ -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,3766 +1,3794 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13
13
14 import abc
14 import abc
15 import ast
15 import ast
16 import atexit
16 import atexit
17 import builtins as builtin_mod
17 import builtins as builtin_mod
18 import dis
18 import dis
19 import functools
19 import functools
20 import inspect
20 import inspect
21 import os
21 import os
22 import re
22 import re
23 import runpy
23 import runpy
24 import subprocess
24 import subprocess
25 import sys
25 import sys
26 import tempfile
26 import tempfile
27 import traceback
27 import traceback
28 import types
28 import types
29 import warnings
29 import warnings
30 from ast import stmt
30 from ast import stmt
31 from io import open as io_open
31 from io import open as io_open
32 from logging import error
32 from logging import error
33 from pathlib import Path
33 from pathlib import Path
34 from typing import Callable
34 from typing import Callable
35 from typing import List as ListType
35 from typing import List as ListType
36 from typing import Optional, Tuple
36 from typing import Optional, Tuple
37 from warnings import warn
37 from warnings import warn
38
38
39 from pickleshare import PickleShareDB
39 from pickleshare import PickleShareDB
40 from tempfile import TemporaryDirectory
40 from tempfile import TemporaryDirectory
41 from traitlets import (
41 from traitlets import (
42 Any,
42 Any,
43 Bool,
43 Bool,
44 CaselessStrEnum,
44 CaselessStrEnum,
45 Dict,
45 Dict,
46 Enum,
46 Enum,
47 Instance,
47 Instance,
48 Integer,
48 Integer,
49 List,
49 List,
50 Type,
50 Type,
51 Unicode,
51 Unicode,
52 default,
52 default,
53 observe,
53 observe,
54 validate,
54 validate,
55 )
55 )
56 from traitlets.config.configurable import SingletonConfigurable
56 from traitlets.config.configurable import SingletonConfigurable
57 from traitlets.utils.importstring import import_item
57 from traitlets.utils.importstring import import_item
58
58
59 import IPython.core.hooks
59 import IPython.core.hooks
60 from IPython.core import magic, oinspect, page, prefilter, ultratb
60 from IPython.core import magic, oinspect, page, prefilter, ultratb
61 from IPython.core.alias import Alias, AliasManager
61 from IPython.core.alias import Alias, AliasManager
62 from IPython.core.autocall import ExitAutocall
62 from IPython.core.autocall import ExitAutocall
63 from IPython.core.builtin_trap import BuiltinTrap
63 from IPython.core.builtin_trap import BuiltinTrap
64 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
64 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
65 from IPython.core.debugger import InterruptiblePdb
65 from IPython.core.debugger import InterruptiblePdb
66 from IPython.core.display_trap import DisplayTrap
66 from IPython.core.display_trap import DisplayTrap
67 from IPython.core.displayhook import DisplayHook
67 from IPython.core.displayhook import DisplayHook
68 from IPython.core.displaypub import DisplayPublisher
68 from IPython.core.displaypub import DisplayPublisher
69 from IPython.core.error import InputRejected, UsageError
69 from IPython.core.error import InputRejected, UsageError
70 from IPython.core.events import EventManager, available_events
70 from IPython.core.events import EventManager, available_events
71 from IPython.core.extensions import ExtensionManager
71 from IPython.core.extensions import ExtensionManager
72 from IPython.core.formatters import DisplayFormatter
72 from IPython.core.formatters import DisplayFormatter
73 from IPython.core.history import HistoryManager
73 from IPython.core.history import HistoryManager
74 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
74 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
75 from IPython.core.logger import Logger
75 from IPython.core.logger import Logger
76 from IPython.core.macro import Macro
76 from IPython.core.macro import Macro
77 from IPython.core.payload import PayloadManager
77 from IPython.core.payload import PayloadManager
78 from IPython.core.prefilter import PrefilterManager
78 from IPython.core.prefilter import PrefilterManager
79 from IPython.core.profiledir import ProfileDir
79 from IPython.core.profiledir import ProfileDir
80 from IPython.core.usage import default_banner
80 from IPython.core.usage import default_banner
81 from IPython.display import display
81 from IPython.display import display
82 from IPython.paths import get_ipython_dir
82 from IPython.paths import get_ipython_dir
83 from IPython.testing.skipdoctest import skip_doctest
83 from IPython.testing.skipdoctest import skip_doctest
84 from IPython.utils import PyColorize, io, openpy, py3compat
84 from IPython.utils import PyColorize, io, openpy, py3compat
85 from IPython.utils.decorators import undoc
85 from IPython.utils.decorators import undoc
86 from IPython.utils.io import ask_yes_no
86 from IPython.utils.io import ask_yes_no
87 from IPython.utils.ipstruct import Struct
87 from IPython.utils.ipstruct import Struct
88 from IPython.utils.path import ensure_dir_exists, get_home_dir, get_py_filename
88 from IPython.utils.path import ensure_dir_exists, get_home_dir, get_py_filename
89 from IPython.utils.process import getoutput, system
89 from IPython.utils.process import getoutput, system
90 from IPython.utils.strdispatch import StrDispatch
90 from IPython.utils.strdispatch import StrDispatch
91 from IPython.utils.syspathcontext import prepended_to_syspath
91 from IPython.utils.syspathcontext import prepended_to_syspath
92 from IPython.utils.text import DollarFormatter, LSString, SList, format_screen
92 from IPython.utils.text import DollarFormatter, LSString, SList, format_screen
93
93
94 sphinxify: Optional[Callable]
94 sphinxify: Optional[Callable]
95
95
96 try:
96 try:
97 import docrepr.sphinxify as sphx
97 import docrepr.sphinxify as sphx
98
98
99 def sphinxify(oinfo):
99 def sphinxify(oinfo):
100 wrapped_docstring = sphx.wrap_main_docstring(oinfo)
100 wrapped_docstring = sphx.wrap_main_docstring(oinfo)
101
101
102 def sphinxify_docstring(docstring):
102 def sphinxify_docstring(docstring):
103 with TemporaryDirectory() as dirname:
103 with TemporaryDirectory() as dirname:
104 return {
104 return {
105 "text/html": sphx.sphinxify(wrapped_docstring, dirname),
105 "text/html": sphx.sphinxify(wrapped_docstring, dirname),
106 "text/plain": docstring,
106 "text/plain": docstring,
107 }
107 }
108
108
109 return sphinxify_docstring
109 return sphinxify_docstring
110 except ImportError:
110 except ImportError:
111 sphinxify = None
111 sphinxify = None
112
112
113
113
114 class ProvisionalWarning(DeprecationWarning):
114 class ProvisionalWarning(DeprecationWarning):
115 """
115 """
116 Warning class for unstable features
116 Warning class for unstable features
117 """
117 """
118 pass
118 pass
119
119
120 from ast import Module
120 from ast import Module
121
121
122 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
122 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
123 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
123 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
124
124
125 #-----------------------------------------------------------------------------
125 #-----------------------------------------------------------------------------
126 # Await Helpers
126 # Await Helpers
127 #-----------------------------------------------------------------------------
127 #-----------------------------------------------------------------------------
128
128
129 # we still need to run things using the asyncio eventloop, but there is no
129 # we still need to run things using the asyncio eventloop, but there is no
130 # async integration
130 # async integration
131 from .async_helpers import (
131 from .async_helpers import (
132 _asyncio_runner,
132 _asyncio_runner,
133 _curio_runner,
133 _curio_runner,
134 _pseudo_sync_runner,
134 _pseudo_sync_runner,
135 _should_be_async,
135 _should_be_async,
136 _trio_runner,
136 _trio_runner,
137 )
137 )
138
138
139 #-----------------------------------------------------------------------------
139 #-----------------------------------------------------------------------------
140 # Globals
140 # Globals
141 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
142
142
143 # compiled regexps for autoindent management
143 # compiled regexps for autoindent management
144 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
144 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
145
145
146 #-----------------------------------------------------------------------------
146 #-----------------------------------------------------------------------------
147 # Utilities
147 # Utilities
148 #-----------------------------------------------------------------------------
148 #-----------------------------------------------------------------------------
149
149
150 @undoc
150 @undoc
151 def softspace(file, newvalue):
151 def softspace(file, newvalue):
152 """Copied from code.py, to remove the dependency"""
152 """Copied from code.py, to remove the dependency"""
153
153
154 oldvalue = 0
154 oldvalue = 0
155 try:
155 try:
156 oldvalue = file.softspace
156 oldvalue = file.softspace
157 except AttributeError:
157 except AttributeError:
158 pass
158 pass
159 try:
159 try:
160 file.softspace = newvalue
160 file.softspace = newvalue
161 except (AttributeError, TypeError):
161 except (AttributeError, TypeError):
162 # "attribute-less object" or "read-only attributes"
162 # "attribute-less object" or "read-only attributes"
163 pass
163 pass
164 return oldvalue
164 return oldvalue
165
165
166 @undoc
166 @undoc
167 def no_op(*a, **kw):
167 def no_op(*a, **kw):
168 pass
168 pass
169
169
170
170
171 class SpaceInInput(Exception): pass
171 class SpaceInInput(Exception): pass
172
172
173
173
174 class SeparateUnicode(Unicode):
174 class SeparateUnicode(Unicode):
175 r"""A Unicode subclass to validate separate_in, separate_out, etc.
175 r"""A Unicode subclass to validate separate_in, separate_out, etc.
176
176
177 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
177 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
178 """
178 """
179
179
180 def validate(self, obj, value):
180 def validate(self, obj, value):
181 if value == '0': value = ''
181 if value == '0': value = ''
182 value = value.replace('\\n','\n')
182 value = value.replace('\\n','\n')
183 return super(SeparateUnicode, self).validate(obj, value)
183 return super(SeparateUnicode, self).validate(obj, value)
184
184
185
185
186 @undoc
186 @undoc
187 class DummyMod(object):
187 class DummyMod(object):
188 """A dummy module used for IPython's interactive module when
188 """A dummy module used for IPython's interactive module when
189 a namespace must be assigned to the module's __dict__."""
189 a namespace must be assigned to the module's __dict__."""
190 __spec__ = None
190 __spec__ = None
191
191
192
192
193 class ExecutionInfo(object):
193 class ExecutionInfo(object):
194 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
194 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
195
195
196 Stores information about what is going to happen.
196 Stores information about what is going to happen.
197 """
197 """
198 raw_cell = None
198 raw_cell = None
199 store_history = False
199 store_history = False
200 silent = False
200 silent = False
201 shell_futures = True
201 shell_futures = True
202 cell_id = None
202
203
203 def __init__(self, raw_cell, store_history, silent, shell_futures):
204 def __init__(self, raw_cell, store_history, silent, shell_futures, cell_id):
204 self.raw_cell = raw_cell
205 self.raw_cell = raw_cell
205 self.store_history = store_history
206 self.store_history = store_history
206 self.silent = silent
207 self.silent = silent
207 self.shell_futures = shell_futures
208 self.shell_futures = shell_futures
209 self.cell_id = cell_id
208
210
209 def __repr__(self):
211 def __repr__(self):
210 name = self.__class__.__qualname__
212 name = self.__class__.__qualname__
211 raw_cell = ((self.raw_cell[:50] + '..')
213 raw_cell = (
212 if len(self.raw_cell) > 50 else self.raw_cell)
214 (self.raw_cell[:50] + "..") if len(self.raw_cell) > 50 else self.raw_cell
213 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
215 )
214 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
216 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s cell_id=%s>' % (
217 name,
218 id(self),
219 raw_cell,
220 self.store_history,
221 self.silent,
222 self.shell_futures,
223 self.cell_id,
224 )
215
225
216
226
217 class ExecutionResult(object):
227 class ExecutionResult(object):
218 """The result of a call to :meth:`InteractiveShell.run_cell`
228 """The result of a call to :meth:`InteractiveShell.run_cell`
219
229
220 Stores information about what took place.
230 Stores information about what took place.
221 """
231 """
222 execution_count = None
232 execution_count = None
223 error_before_exec = None
233 error_before_exec = None
224 error_in_exec: Optional[BaseException] = None
234 error_in_exec: Optional[BaseException] = None
225 info = None
235 info = None
226 result = None
236 result = None
227
237
228 def __init__(self, info):
238 def __init__(self, info):
229 self.info = info
239 self.info = info
230
240
231 @property
241 @property
232 def success(self):
242 def success(self):
233 return (self.error_before_exec is None) and (self.error_in_exec is None)
243 return (self.error_before_exec is None) and (self.error_in_exec is None)
234
244
235 def raise_error(self):
245 def raise_error(self):
236 """Reraises error if `success` is `False`, otherwise does nothing"""
246 """Reraises error if `success` is `False`, otherwise does nothing"""
237 if self.error_before_exec is not None:
247 if self.error_before_exec is not None:
238 raise self.error_before_exec
248 raise self.error_before_exec
239 if self.error_in_exec is not None:
249 if self.error_in_exec is not None:
240 raise self.error_in_exec
250 raise self.error_in_exec
241
251
242 def __repr__(self):
252 def __repr__(self):
243 name = self.__class__.__qualname__
253 name = self.__class__.__qualname__
244 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
254 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
245 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
255 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
246
256
247
257
248 class InteractiveShell(SingletonConfigurable):
258 class InteractiveShell(SingletonConfigurable):
249 """An enhanced, interactive shell for Python."""
259 """An enhanced, interactive shell for Python."""
250
260
251 _instance = None
261 _instance = None
252
262
253 ast_transformers = List([], help=
263 ast_transformers = List([], help=
254 """
264 """
255 A list of ast.NodeTransformer subclass instances, which will be applied
265 A list of ast.NodeTransformer subclass instances, which will be applied
256 to user input before code is run.
266 to user input before code is run.
257 """
267 """
258 ).tag(config=True)
268 ).tag(config=True)
259
269
260 autocall = Enum((0,1,2), default_value=0, help=
270 autocall = Enum((0,1,2), default_value=0, help=
261 """
271 """
262 Make IPython automatically call any callable object even if you didn't
272 Make IPython automatically call any callable object even if you didn't
263 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
273 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
264 automatically. The value can be '0' to disable the feature, '1' for
274 automatically. The value can be '0' to disable the feature, '1' for
265 'smart' autocall, where it is not applied if there are no more
275 'smart' autocall, where it is not applied if there are no more
266 arguments on the line, and '2' for 'full' autocall, where all callable
276 arguments on the line, and '2' for 'full' autocall, where all callable
267 objects are automatically called (even if no arguments are present).
277 objects are automatically called (even if no arguments are present).
268 """
278 """
269 ).tag(config=True)
279 ).tag(config=True)
270
280
271 autoindent = Bool(True, help=
281 autoindent = Bool(True, help=
272 """
282 """
273 Autoindent IPython code entered interactively.
283 Autoindent IPython code entered interactively.
274 """
284 """
275 ).tag(config=True)
285 ).tag(config=True)
276
286
277 autoawait = Bool(True, help=
287 autoawait = Bool(True, help=
278 """
288 """
279 Automatically run await statement in the top level repl.
289 Automatically run await statement in the top level repl.
280 """
290 """
281 ).tag(config=True)
291 ).tag(config=True)
282
292
283 loop_runner_map ={
293 loop_runner_map ={
284 'asyncio':(_asyncio_runner, True),
294 'asyncio':(_asyncio_runner, True),
285 'curio':(_curio_runner, True),
295 'curio':(_curio_runner, True),
286 'trio':(_trio_runner, True),
296 'trio':(_trio_runner, True),
287 'sync': (_pseudo_sync_runner, False)
297 'sync': (_pseudo_sync_runner, False)
288 }
298 }
289
299
290 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
300 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
291 allow_none=True,
301 allow_none=True,
292 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
302 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
293 ).tag(config=True)
303 ).tag(config=True)
294
304
295 @default('loop_runner')
305 @default('loop_runner')
296 def _default_loop_runner(self):
306 def _default_loop_runner(self):
297 return import_item("IPython.core.interactiveshell._asyncio_runner")
307 return import_item("IPython.core.interactiveshell._asyncio_runner")
298
308
299 @validate('loop_runner')
309 @validate('loop_runner')
300 def _import_runner(self, proposal):
310 def _import_runner(self, proposal):
301 if isinstance(proposal.value, str):
311 if isinstance(proposal.value, str):
302 if proposal.value in self.loop_runner_map:
312 if proposal.value in self.loop_runner_map:
303 runner, autoawait = self.loop_runner_map[proposal.value]
313 runner, autoawait = self.loop_runner_map[proposal.value]
304 self.autoawait = autoawait
314 self.autoawait = autoawait
305 return runner
315 return runner
306 runner = import_item(proposal.value)
316 runner = import_item(proposal.value)
307 if not callable(runner):
317 if not callable(runner):
308 raise ValueError('loop_runner must be callable')
318 raise ValueError('loop_runner must be callable')
309 return runner
319 return runner
310 if not callable(proposal.value):
320 if not callable(proposal.value):
311 raise ValueError('loop_runner must be callable')
321 raise ValueError('loop_runner must be callable')
312 return proposal.value
322 return proposal.value
313
323
314 automagic = Bool(True, help=
324 automagic = Bool(True, help=
315 """
325 """
316 Enable magic commands to be called without the leading %.
326 Enable magic commands to be called without the leading %.
317 """
327 """
318 ).tag(config=True)
328 ).tag(config=True)
319
329
320 banner1 = Unicode(default_banner,
330 banner1 = Unicode(default_banner,
321 help="""The part of the banner to be printed before the profile"""
331 help="""The part of the banner to be printed before the profile"""
322 ).tag(config=True)
332 ).tag(config=True)
323 banner2 = Unicode('',
333 banner2 = Unicode('',
324 help="""The part of the banner to be printed after the profile"""
334 help="""The part of the banner to be printed after the profile"""
325 ).tag(config=True)
335 ).tag(config=True)
326
336
327 cache_size = Integer(1000, help=
337 cache_size = Integer(1000, help=
328 """
338 """
329 Set the size of the output cache. The default is 1000, you can
339 Set the size of the output cache. The default is 1000, you can
330 change it permanently in your config file. Setting it to 0 completely
340 change it permanently in your config file. Setting it to 0 completely
331 disables the caching system, and the minimum value accepted is 3 (if
341 disables the caching system, and the minimum value accepted is 3 (if
332 you provide a value less than 3, it is reset to 0 and a warning is
342 you provide a value less than 3, it is reset to 0 and a warning is
333 issued). This limit is defined because otherwise you'll spend more
343 issued). This limit is defined because otherwise you'll spend more
334 time re-flushing a too small cache than working
344 time re-flushing a too small cache than working
335 """
345 """
336 ).tag(config=True)
346 ).tag(config=True)
337 color_info = Bool(True, help=
347 color_info = Bool(True, help=
338 """
348 """
339 Use colors for displaying information about objects. Because this
349 Use colors for displaying information about objects. Because this
340 information is passed through a pager (like 'less'), and some pagers
350 information is passed through a pager (like 'less'), and some pagers
341 get confused with color codes, this capability can be turned off.
351 get confused with color codes, this capability can be turned off.
342 """
352 """
343 ).tag(config=True)
353 ).tag(config=True)
344 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
354 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
345 default_value='Neutral',
355 default_value='Neutral',
346 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
356 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
347 ).tag(config=True)
357 ).tag(config=True)
348 debug = Bool(False).tag(config=True)
358 debug = Bool(False).tag(config=True)
349 disable_failing_post_execute = Bool(False,
359 disable_failing_post_execute = Bool(False,
350 help="Don't call post-execute functions that have failed in the past."
360 help="Don't call post-execute functions that have failed in the past."
351 ).tag(config=True)
361 ).tag(config=True)
352 display_formatter = Instance(DisplayFormatter, allow_none=True)
362 display_formatter = Instance(DisplayFormatter, allow_none=True)
353 displayhook_class = Type(DisplayHook)
363 displayhook_class = Type(DisplayHook)
354 display_pub_class = Type(DisplayPublisher)
364 display_pub_class = Type(DisplayPublisher)
355 compiler_class = Type(CachingCompiler)
365 compiler_class = Type(CachingCompiler)
356
366
357 sphinxify_docstring = Bool(False, help=
367 sphinxify_docstring = Bool(False, help=
358 """
368 """
359 Enables rich html representation of docstrings. (This requires the
369 Enables rich html representation of docstrings. (This requires the
360 docrepr module).
370 docrepr module).
361 """).tag(config=True)
371 """).tag(config=True)
362
372
363 @observe("sphinxify_docstring")
373 @observe("sphinxify_docstring")
364 def _sphinxify_docstring_changed(self, change):
374 def _sphinxify_docstring_changed(self, change):
365 if change['new']:
375 if change['new']:
366 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
376 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
367
377
368 enable_html_pager = Bool(False, help=
378 enable_html_pager = Bool(False, help=
369 """
379 """
370 (Provisional API) enables html representation in mime bundles sent
380 (Provisional API) enables html representation in mime bundles sent
371 to pagers.
381 to pagers.
372 """).tag(config=True)
382 """).tag(config=True)
373
383
374 @observe("enable_html_pager")
384 @observe("enable_html_pager")
375 def _enable_html_pager_changed(self, change):
385 def _enable_html_pager_changed(self, change):
376 if change['new']:
386 if change['new']:
377 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
387 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
378
388
379 data_pub_class = None
389 data_pub_class = None
380
390
381 exit_now = Bool(False)
391 exit_now = Bool(False)
382 exiter = Instance(ExitAutocall)
392 exiter = Instance(ExitAutocall)
383 @default('exiter')
393 @default('exiter')
384 def _exiter_default(self):
394 def _exiter_default(self):
385 return ExitAutocall(self)
395 return ExitAutocall(self)
386 # Monotonically increasing execution counter
396 # Monotonically increasing execution counter
387 execution_count = Integer(1)
397 execution_count = Integer(1)
388 filename = Unicode("<ipython console>")
398 filename = Unicode("<ipython console>")
389 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
399 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
390
400
391 # Used to transform cells before running them, and check whether code is complete
401 # Used to transform cells before running them, and check whether code is complete
392 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
402 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
393 ())
403 ())
394
404
395 @property
405 @property
396 def input_transformers_cleanup(self):
406 def input_transformers_cleanup(self):
397 return self.input_transformer_manager.cleanup_transforms
407 return self.input_transformer_manager.cleanup_transforms
398
408
399 input_transformers_post = List([],
409 input_transformers_post = List([],
400 help="A list of string input transformers, to be applied after IPython's "
410 help="A list of string input transformers, to be applied after IPython's "
401 "own input transformations."
411 "own input transformations."
402 )
412 )
403
413
404 @property
414 @property
405 def input_splitter(self):
415 def input_splitter(self):
406 """Make this available for backward compatibility (pre-7.0 release) with existing code.
416 """Make this available for backward compatibility (pre-7.0 release) with existing code.
407
417
408 For example, ipykernel ipykernel currently uses
418 For example, ipykernel ipykernel currently uses
409 `shell.input_splitter.check_complete`
419 `shell.input_splitter.check_complete`
410 """
420 """
411 from warnings import warn
421 from warnings import warn
412 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
422 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
413 DeprecationWarning, stacklevel=2
423 DeprecationWarning, stacklevel=2
414 )
424 )
415 return self.input_transformer_manager
425 return self.input_transformer_manager
416
426
417 logstart = Bool(False, help=
427 logstart = Bool(False, help=
418 """
428 """
419 Start logging to the default log file in overwrite mode.
429 Start logging to the default log file in overwrite mode.
420 Use `logappend` to specify a log file to **append** logs to.
430 Use `logappend` to specify a log file to **append** logs to.
421 """
431 """
422 ).tag(config=True)
432 ).tag(config=True)
423 logfile = Unicode('', help=
433 logfile = Unicode('', help=
424 """
434 """
425 The name of the logfile to use.
435 The name of the logfile to use.
426 """
436 """
427 ).tag(config=True)
437 ).tag(config=True)
428 logappend = Unicode('', help=
438 logappend = Unicode('', help=
429 """
439 """
430 Start logging to the given file in append mode.
440 Start logging to the given file in append mode.
431 Use `logfile` to specify a log file to **overwrite** logs to.
441 Use `logfile` to specify a log file to **overwrite** logs to.
432 """
442 """
433 ).tag(config=True)
443 ).tag(config=True)
434 object_info_string_level = Enum((0,1,2), default_value=0,
444 object_info_string_level = Enum((0,1,2), default_value=0,
435 ).tag(config=True)
445 ).tag(config=True)
436 pdb = Bool(False, help=
446 pdb = Bool(False, help=
437 """
447 """
438 Automatically call the pdb debugger after every exception.
448 Automatically call the pdb debugger after every exception.
439 """
449 """
440 ).tag(config=True)
450 ).tag(config=True)
441 display_page = Bool(False,
451 display_page = Bool(False,
442 help="""If True, anything that would be passed to the pager
452 help="""If True, anything that would be passed to the pager
443 will be displayed as regular output instead."""
453 will be displayed as regular output instead."""
444 ).tag(config=True)
454 ).tag(config=True)
445
455
446
456
447 show_rewritten_input = Bool(True,
457 show_rewritten_input = Bool(True,
448 help="Show rewritten input, e.g. for autocall."
458 help="Show rewritten input, e.g. for autocall."
449 ).tag(config=True)
459 ).tag(config=True)
450
460
451 quiet = Bool(False).tag(config=True)
461 quiet = Bool(False).tag(config=True)
452
462
453 history_length = Integer(10000,
463 history_length = Integer(10000,
454 help='Total length of command history'
464 help='Total length of command history'
455 ).tag(config=True)
465 ).tag(config=True)
456
466
457 history_load_length = Integer(1000, help=
467 history_load_length = Integer(1000, help=
458 """
468 """
459 The number of saved history entries to be loaded
469 The number of saved history entries to be loaded
460 into the history buffer at startup.
470 into the history buffer at startup.
461 """
471 """
462 ).tag(config=True)
472 ).tag(config=True)
463
473
464 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
474 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
465 default_value='last_expr',
475 default_value='last_expr',
466 help="""
476 help="""
467 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
477 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
468 which nodes should be run interactively (displaying output from expressions).
478 which nodes should be run interactively (displaying output from expressions).
469 """
479 """
470 ).tag(config=True)
480 ).tag(config=True)
471
481
472 # TODO: this part of prompt management should be moved to the frontends.
482 # TODO: this part of prompt management should be moved to the frontends.
473 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
483 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
474 separate_in = SeparateUnicode('\n').tag(config=True)
484 separate_in = SeparateUnicode('\n').tag(config=True)
475 separate_out = SeparateUnicode('').tag(config=True)
485 separate_out = SeparateUnicode('').tag(config=True)
476 separate_out2 = SeparateUnicode('').tag(config=True)
486 separate_out2 = SeparateUnicode('').tag(config=True)
477 wildcards_case_sensitive = Bool(True).tag(config=True)
487 wildcards_case_sensitive = Bool(True).tag(config=True)
478 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
488 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
479 default_value='Context',
489 default_value='Context',
480 help="Switch modes for the IPython exception handlers."
490 help="Switch modes for the IPython exception handlers."
481 ).tag(config=True)
491 ).tag(config=True)
482
492
483 # Subcomponents of InteractiveShell
493 # Subcomponents of InteractiveShell
484 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
494 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
485 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
495 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
486 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
496 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
487 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
497 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
488 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
498 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
489 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
499 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
490 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
500 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
491 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
501 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
492
502
493 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
503 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
494 @property
504 @property
495 def profile(self):
505 def profile(self):
496 if self.profile_dir is not None:
506 if self.profile_dir is not None:
497 name = os.path.basename(self.profile_dir.location)
507 name = os.path.basename(self.profile_dir.location)
498 return name.replace('profile_','')
508 return name.replace('profile_','')
499
509
500
510
501 # Private interface
511 # Private interface
502 _post_execute = Dict()
512 _post_execute = Dict()
503
513
504 # Tracks any GUI loop loaded for pylab
514 # Tracks any GUI loop loaded for pylab
505 pylab_gui_select = None
515 pylab_gui_select = None
506
516
507 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
517 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
508
518
509 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
519 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
510
520
511 def __init__(self, ipython_dir=None, profile_dir=None,
521 def __init__(self, ipython_dir=None, profile_dir=None,
512 user_module=None, user_ns=None,
522 user_module=None, user_ns=None,
513 custom_exceptions=((), None), **kwargs):
523 custom_exceptions=((), None), **kwargs):
514 # This is where traits with a config_key argument are updated
524 # This is where traits with a config_key argument are updated
515 # from the values on config.
525 # from the values on config.
516 super(InteractiveShell, self).__init__(**kwargs)
526 super(InteractiveShell, self).__init__(**kwargs)
517 if 'PromptManager' in self.config:
527 if 'PromptManager' in self.config:
518 warn('As of IPython 5.0 `PromptManager` config will have no effect'
528 warn('As of IPython 5.0 `PromptManager` config will have no effect'
519 ' and has been replaced by TerminalInteractiveShell.prompts_class')
529 ' and has been replaced by TerminalInteractiveShell.prompts_class')
520 self.configurables = [self]
530 self.configurables = [self]
521
531
522 # These are relatively independent and stateless
532 # These are relatively independent and stateless
523 self.init_ipython_dir(ipython_dir)
533 self.init_ipython_dir(ipython_dir)
524 self.init_profile_dir(profile_dir)
534 self.init_profile_dir(profile_dir)
525 self.init_instance_attrs()
535 self.init_instance_attrs()
526 self.init_environment()
536 self.init_environment()
527
537
528 # Check if we're in a virtualenv, and set up sys.path.
538 # Check if we're in a virtualenv, and set up sys.path.
529 self.init_virtualenv()
539 self.init_virtualenv()
530
540
531 # Create namespaces (user_ns, user_global_ns, etc.)
541 # Create namespaces (user_ns, user_global_ns, etc.)
532 self.init_create_namespaces(user_module, user_ns)
542 self.init_create_namespaces(user_module, user_ns)
533 # This has to be done after init_create_namespaces because it uses
543 # This has to be done after init_create_namespaces because it uses
534 # something in self.user_ns, but before init_sys_modules, which
544 # something in self.user_ns, but before init_sys_modules, which
535 # is the first thing to modify sys.
545 # is the first thing to modify sys.
536 # TODO: When we override sys.stdout and sys.stderr before this class
546 # TODO: When we override sys.stdout and sys.stderr before this class
537 # is created, we are saving the overridden ones here. Not sure if this
547 # is created, we are saving the overridden ones here. Not sure if this
538 # is what we want to do.
548 # is what we want to do.
539 self.save_sys_module_state()
549 self.save_sys_module_state()
540 self.init_sys_modules()
550 self.init_sys_modules()
541
551
542 # While we're trying to have each part of the code directly access what
552 # While we're trying to have each part of the code directly access what
543 # it needs without keeping redundant references to objects, we have too
553 # it needs without keeping redundant references to objects, we have too
544 # much legacy code that expects ip.db to exist.
554 # much legacy code that expects ip.db to exist.
545 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
555 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
546
556
547 self.init_history()
557 self.init_history()
548 self.init_encoding()
558 self.init_encoding()
549 self.init_prefilter()
559 self.init_prefilter()
550
560
551 self.init_syntax_highlighting()
561 self.init_syntax_highlighting()
552 self.init_hooks()
562 self.init_hooks()
553 self.init_events()
563 self.init_events()
554 self.init_pushd_popd_magic()
564 self.init_pushd_popd_magic()
555 self.init_user_ns()
565 self.init_user_ns()
556 self.init_logger()
566 self.init_logger()
557 self.init_builtins()
567 self.init_builtins()
558
568
559 # The following was in post_config_initialization
569 # The following was in post_config_initialization
560 self.init_inspector()
570 self.init_inspector()
561 self.raw_input_original = input
571 self.raw_input_original = input
562 self.init_completer()
572 self.init_completer()
563 # TODO: init_io() needs to happen before init_traceback handlers
573 # TODO: init_io() needs to happen before init_traceback handlers
564 # because the traceback handlers hardcode the stdout/stderr streams.
574 # because the traceback handlers hardcode the stdout/stderr streams.
565 # This logic in in debugger.Pdb and should eventually be changed.
575 # This logic in in debugger.Pdb and should eventually be changed.
566 self.init_io()
576 self.init_io()
567 self.init_traceback_handlers(custom_exceptions)
577 self.init_traceback_handlers(custom_exceptions)
568 self.init_prompts()
578 self.init_prompts()
569 self.init_display_formatter()
579 self.init_display_formatter()
570 self.init_display_pub()
580 self.init_display_pub()
571 self.init_data_pub()
581 self.init_data_pub()
572 self.init_displayhook()
582 self.init_displayhook()
573 self.init_magics()
583 self.init_magics()
574 self.init_alias()
584 self.init_alias()
575 self.init_logstart()
585 self.init_logstart()
576 self.init_pdb()
586 self.init_pdb()
577 self.init_extension_manager()
587 self.init_extension_manager()
578 self.init_payload()
588 self.init_payload()
579 self.events.trigger('shell_initialized', self)
589 self.events.trigger('shell_initialized', self)
580 atexit.register(self.atexit_operations)
590 atexit.register(self.atexit_operations)
581
591
582 # The trio runner is used for running Trio in the foreground thread. It
592 # The trio runner is used for running Trio in the foreground thread. It
583 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
593 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
584 # which calls `trio.run()` for every cell. This runner runs all cells
594 # which calls `trio.run()` for every cell. This runner runs all cells
585 # inside a single Trio event loop. If used, it is set from
595 # inside a single Trio event loop. If used, it is set from
586 # `ipykernel.kernelapp`.
596 # `ipykernel.kernelapp`.
587 self.trio_runner = None
597 self.trio_runner = None
588
598
589 def get_ipython(self):
599 def get_ipython(self):
590 """Return the currently running IPython instance."""
600 """Return the currently running IPython instance."""
591 return self
601 return self
592
602
593 #-------------------------------------------------------------------------
603 #-------------------------------------------------------------------------
594 # Trait changed handlers
604 # Trait changed handlers
595 #-------------------------------------------------------------------------
605 #-------------------------------------------------------------------------
596 @observe('ipython_dir')
606 @observe('ipython_dir')
597 def _ipython_dir_changed(self, change):
607 def _ipython_dir_changed(self, change):
598 ensure_dir_exists(change['new'])
608 ensure_dir_exists(change['new'])
599
609
600 def set_autoindent(self,value=None):
610 def set_autoindent(self,value=None):
601 """Set the autoindent flag.
611 """Set the autoindent flag.
602
612
603 If called with no arguments, it acts as a toggle."""
613 If called with no arguments, it acts as a toggle."""
604 if value is None:
614 if value is None:
605 self.autoindent = not self.autoindent
615 self.autoindent = not self.autoindent
606 else:
616 else:
607 self.autoindent = value
617 self.autoindent = value
608
618
609 def set_trio_runner(self, tr):
619 def set_trio_runner(self, tr):
610 self.trio_runner = tr
620 self.trio_runner = tr
611
621
612 #-------------------------------------------------------------------------
622 #-------------------------------------------------------------------------
613 # init_* methods called by __init__
623 # init_* methods called by __init__
614 #-------------------------------------------------------------------------
624 #-------------------------------------------------------------------------
615
625
616 def init_ipython_dir(self, ipython_dir):
626 def init_ipython_dir(self, ipython_dir):
617 if ipython_dir is not None:
627 if ipython_dir is not None:
618 self.ipython_dir = ipython_dir
628 self.ipython_dir = ipython_dir
619 return
629 return
620
630
621 self.ipython_dir = get_ipython_dir()
631 self.ipython_dir = get_ipython_dir()
622
632
623 def init_profile_dir(self, profile_dir):
633 def init_profile_dir(self, profile_dir):
624 if profile_dir is not None:
634 if profile_dir is not None:
625 self.profile_dir = profile_dir
635 self.profile_dir = profile_dir
626 return
636 return
627 self.profile_dir = ProfileDir.create_profile_dir_by_name(
637 self.profile_dir = ProfileDir.create_profile_dir_by_name(
628 self.ipython_dir, "default"
638 self.ipython_dir, "default"
629 )
639 )
630
640
631 def init_instance_attrs(self):
641 def init_instance_attrs(self):
632 self.more = False
642 self.more = False
633
643
634 # command compiler
644 # command compiler
635 self.compile = self.compiler_class()
645 self.compile = self.compiler_class()
636
646
637 # Make an empty namespace, which extension writers can rely on both
647 # Make an empty namespace, which extension writers can rely on both
638 # existing and NEVER being used by ipython itself. This gives them a
648 # existing and NEVER being used by ipython itself. This gives them a
639 # convenient location for storing additional information and state
649 # convenient location for storing additional information and state
640 # their extensions may require, without fear of collisions with other
650 # their extensions may require, without fear of collisions with other
641 # ipython names that may develop later.
651 # ipython names that may develop later.
642 self.meta = Struct()
652 self.meta = Struct()
643
653
644 # Temporary files used for various purposes. Deleted at exit.
654 # Temporary files used for various purposes. Deleted at exit.
645 # The files here are stored with Path from Pathlib
655 # The files here are stored with Path from Pathlib
646 self.tempfiles = []
656 self.tempfiles = []
647 self.tempdirs = []
657 self.tempdirs = []
648
658
649 # keep track of where we started running (mainly for crash post-mortem)
659 # keep track of where we started running (mainly for crash post-mortem)
650 # This is not being used anywhere currently.
660 # This is not being used anywhere currently.
651 self.starting_dir = os.getcwd()
661 self.starting_dir = os.getcwd()
652
662
653 # Indentation management
663 # Indentation management
654 self.indent_current_nsp = 0
664 self.indent_current_nsp = 0
655
665
656 # Dict to track post-execution functions that have been registered
666 # Dict to track post-execution functions that have been registered
657 self._post_execute = {}
667 self._post_execute = {}
658
668
659 def init_environment(self):
669 def init_environment(self):
660 """Any changes we need to make to the user's environment."""
670 """Any changes we need to make to the user's environment."""
661 pass
671 pass
662
672
663 def init_encoding(self):
673 def init_encoding(self):
664 # Get system encoding at startup time. Certain terminals (like Emacs
674 # Get system encoding at startup time. Certain terminals (like Emacs
665 # under Win32 have it set to None, and we need to have a known valid
675 # under Win32 have it set to None, and we need to have a known valid
666 # encoding to use in the raw_input() method
676 # encoding to use in the raw_input() method
667 try:
677 try:
668 self.stdin_encoding = sys.stdin.encoding or 'ascii'
678 self.stdin_encoding = sys.stdin.encoding or 'ascii'
669 except AttributeError:
679 except AttributeError:
670 self.stdin_encoding = 'ascii'
680 self.stdin_encoding = 'ascii'
671
681
672
682
673 @observe('colors')
683 @observe('colors')
674 def init_syntax_highlighting(self, changes=None):
684 def init_syntax_highlighting(self, changes=None):
675 # Python source parser/formatter for syntax highlighting
685 # Python source parser/formatter for syntax highlighting
676 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
686 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
677 self.pycolorize = lambda src: pyformat(src,'str')
687 self.pycolorize = lambda src: pyformat(src,'str')
678
688
679 def refresh_style(self):
689 def refresh_style(self):
680 # No-op here, used in subclass
690 # No-op here, used in subclass
681 pass
691 pass
682
692
683 def init_pushd_popd_magic(self):
693 def init_pushd_popd_magic(self):
684 # for pushd/popd management
694 # for pushd/popd management
685 self.home_dir = get_home_dir()
695 self.home_dir = get_home_dir()
686
696
687 self.dir_stack = []
697 self.dir_stack = []
688
698
689 def init_logger(self):
699 def init_logger(self):
690 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
700 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
691 logmode='rotate')
701 logmode='rotate')
692
702
693 def init_logstart(self):
703 def init_logstart(self):
694 """Initialize logging in case it was requested at the command line.
704 """Initialize logging in case it was requested at the command line.
695 """
705 """
696 if self.logappend:
706 if self.logappend:
697 self.magic('logstart %s append' % self.logappend)
707 self.magic('logstart %s append' % self.logappend)
698 elif self.logfile:
708 elif self.logfile:
699 self.magic('logstart %s' % self.logfile)
709 self.magic('logstart %s' % self.logfile)
700 elif self.logstart:
710 elif self.logstart:
701 self.magic('logstart')
711 self.magic('logstart')
702
712
703
713
704 def init_builtins(self):
714 def init_builtins(self):
705 # A single, static flag that we set to True. Its presence indicates
715 # A single, static flag that we set to True. Its presence indicates
706 # that an IPython shell has been created, and we make no attempts at
716 # that an IPython shell has been created, and we make no attempts at
707 # removing on exit or representing the existence of more than one
717 # removing on exit or representing the existence of more than one
708 # IPython at a time.
718 # IPython at a time.
709 builtin_mod.__dict__['__IPYTHON__'] = True
719 builtin_mod.__dict__['__IPYTHON__'] = True
710 builtin_mod.__dict__['display'] = display
720 builtin_mod.__dict__['display'] = display
711
721
712 self.builtin_trap = BuiltinTrap(shell=self)
722 self.builtin_trap = BuiltinTrap(shell=self)
713
723
714 @observe('colors')
724 @observe('colors')
715 def init_inspector(self, changes=None):
725 def init_inspector(self, changes=None):
716 # Object inspector
726 # Object inspector
717 self.inspector = oinspect.Inspector(oinspect.InspectColors,
727 self.inspector = oinspect.Inspector(oinspect.InspectColors,
718 PyColorize.ANSICodeColors,
728 PyColorize.ANSICodeColors,
719 self.colors,
729 self.colors,
720 self.object_info_string_level)
730 self.object_info_string_level)
721
731
722 def init_io(self):
732 def init_io(self):
723 # implemented in subclasses, TerminalInteractiveShell does call
733 # implemented in subclasses, TerminalInteractiveShell does call
724 # colorama.init().
734 # colorama.init().
725 pass
735 pass
726
736
727 def init_prompts(self):
737 def init_prompts(self):
728 # Set system prompts, so that scripts can decide if they are running
738 # Set system prompts, so that scripts can decide if they are running
729 # interactively.
739 # interactively.
730 sys.ps1 = 'In : '
740 sys.ps1 = 'In : '
731 sys.ps2 = '...: '
741 sys.ps2 = '...: '
732 sys.ps3 = 'Out: '
742 sys.ps3 = 'Out: '
733
743
734 def init_display_formatter(self):
744 def init_display_formatter(self):
735 self.display_formatter = DisplayFormatter(parent=self)
745 self.display_formatter = DisplayFormatter(parent=self)
736 self.configurables.append(self.display_formatter)
746 self.configurables.append(self.display_formatter)
737
747
738 def init_display_pub(self):
748 def init_display_pub(self):
739 self.display_pub = self.display_pub_class(parent=self, shell=self)
749 self.display_pub = self.display_pub_class(parent=self, shell=self)
740 self.configurables.append(self.display_pub)
750 self.configurables.append(self.display_pub)
741
751
742 def init_data_pub(self):
752 def init_data_pub(self):
743 if not self.data_pub_class:
753 if not self.data_pub_class:
744 self.data_pub = None
754 self.data_pub = None
745 return
755 return
746 self.data_pub = self.data_pub_class(parent=self)
756 self.data_pub = self.data_pub_class(parent=self)
747 self.configurables.append(self.data_pub)
757 self.configurables.append(self.data_pub)
748
758
749 def init_displayhook(self):
759 def init_displayhook(self):
750 # Initialize displayhook, set in/out prompts and printing system
760 # Initialize displayhook, set in/out prompts and printing system
751 self.displayhook = self.displayhook_class(
761 self.displayhook = self.displayhook_class(
752 parent=self,
762 parent=self,
753 shell=self,
763 shell=self,
754 cache_size=self.cache_size,
764 cache_size=self.cache_size,
755 )
765 )
756 self.configurables.append(self.displayhook)
766 self.configurables.append(self.displayhook)
757 # This is a context manager that installs/revmoes the displayhook at
767 # This is a context manager that installs/revmoes the displayhook at
758 # the appropriate time.
768 # the appropriate time.
759 self.display_trap = DisplayTrap(hook=self.displayhook)
769 self.display_trap = DisplayTrap(hook=self.displayhook)
760
770
761 @staticmethod
771 @staticmethod
762 def get_path_links(p: Path):
772 def get_path_links(p: Path):
763 """Gets path links including all symlinks
773 """Gets path links including all symlinks
764
774
765 Examples
775 Examples
766 --------
776 --------
767 In [1]: from IPython.core.interactiveshell import InteractiveShell
777 In [1]: from IPython.core.interactiveshell import InteractiveShell
768
778
769 In [2]: import sys, pathlib
779 In [2]: import sys, pathlib
770
780
771 In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable))
781 In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable))
772
782
773 In [4]: len(paths) == len(set(paths))
783 In [4]: len(paths) == len(set(paths))
774 Out[4]: True
784 Out[4]: True
775
785
776 In [5]: bool(paths)
786 In [5]: bool(paths)
777 Out[5]: True
787 Out[5]: True
778 """
788 """
779 paths = [p]
789 paths = [p]
780 while p.is_symlink():
790 while p.is_symlink():
781 new_path = Path(os.readlink(p))
791 new_path = Path(os.readlink(p))
782 if not new_path.is_absolute():
792 if not new_path.is_absolute():
783 new_path = p.parent / new_path
793 new_path = p.parent / new_path
784 p = new_path
794 p = new_path
785 paths.append(p)
795 paths.append(p)
786 return paths
796 return paths
787
797
788 def init_virtualenv(self):
798 def init_virtualenv(self):
789 """Add the current virtualenv to sys.path so the user can import modules from it.
799 """Add the current virtualenv to sys.path so the user can import modules from it.
790 This isn't perfect: it doesn't use the Python interpreter with which the
800 This isn't perfect: it doesn't use the Python interpreter with which the
791 virtualenv was built, and it ignores the --no-site-packages option. A
801 virtualenv was built, and it ignores the --no-site-packages option. A
792 warning will appear suggesting the user installs IPython in the
802 warning will appear suggesting the user installs IPython in the
793 virtualenv, but for many cases, it probably works well enough.
803 virtualenv, but for many cases, it probably works well enough.
794
804
795 Adapted from code snippets online.
805 Adapted from code snippets online.
796
806
797 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
807 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
798 """
808 """
799 if 'VIRTUAL_ENV' not in os.environ:
809 if 'VIRTUAL_ENV' not in os.environ:
800 # Not in a virtualenv
810 # Not in a virtualenv
801 return
811 return
802 elif os.environ["VIRTUAL_ENV"] == "":
812 elif os.environ["VIRTUAL_ENV"] == "":
803 warn("Virtual env path set to '', please check if this is intended.")
813 warn("Virtual env path set to '', please check if this is intended.")
804 return
814 return
805
815
806 p = Path(sys.executable)
816 p = Path(sys.executable)
807 p_venv = Path(os.environ["VIRTUAL_ENV"])
817 p_venv = Path(os.environ["VIRTUAL_ENV"])
808
818
809 # fallback venv detection:
819 # fallback venv detection:
810 # stdlib venv may symlink sys.executable, so we can't use realpath.
820 # stdlib venv may symlink sys.executable, so we can't use realpath.
811 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
821 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
812 # So we just check every item in the symlink tree (generally <= 3)
822 # So we just check every item in the symlink tree (generally <= 3)
813 paths = self.get_path_links(p)
823 paths = self.get_path_links(p)
814
824
815 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
825 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
816 if p_venv.parts[1] == "cygdrive":
826 if p_venv.parts[1] == "cygdrive":
817 drive_name = p_venv.parts[2]
827 drive_name = p_venv.parts[2]
818 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
828 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
819
829
820 if any(p_venv == p.parents[1] for p in paths):
830 if any(p_venv == p.parents[1] for p in paths):
821 # Our exe is inside or has access to the virtualenv, don't need to do anything.
831 # Our exe is inside or has access to the virtualenv, don't need to do anything.
822 return
832 return
823
833
824 if sys.platform == "win32":
834 if sys.platform == "win32":
825 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
835 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
826 else:
836 else:
827 virtual_env_path = Path(
837 virtual_env_path = Path(
828 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
838 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
829 )
839 )
830 p_ver = sys.version_info[:2]
840 p_ver = sys.version_info[:2]
831
841
832 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
842 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
833 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
843 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
834 if re_m:
844 if re_m:
835 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
845 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
836 if predicted_path.exists():
846 if predicted_path.exists():
837 p_ver = re_m.groups()
847 p_ver = re_m.groups()
838
848
839 virtual_env = str(virtual_env_path).format(*p_ver)
849 virtual_env = str(virtual_env_path).format(*p_ver)
840
850
841 warn(
851 warn(
842 "Attempting to work in a virtualenv. If you encounter problems, "
852 "Attempting to work in a virtualenv. If you encounter problems, "
843 "please install IPython inside the virtualenv."
853 "please install IPython inside the virtualenv."
844 )
854 )
845 import site
855 import site
846 sys.path.insert(0, virtual_env)
856 sys.path.insert(0, virtual_env)
847 site.addsitedir(virtual_env)
857 site.addsitedir(virtual_env)
848
858
849 #-------------------------------------------------------------------------
859 #-------------------------------------------------------------------------
850 # Things related to injections into the sys module
860 # Things related to injections into the sys module
851 #-------------------------------------------------------------------------
861 #-------------------------------------------------------------------------
852
862
853 def save_sys_module_state(self):
863 def save_sys_module_state(self):
854 """Save the state of hooks in the sys module.
864 """Save the state of hooks in the sys module.
855
865
856 This has to be called after self.user_module is created.
866 This has to be called after self.user_module is created.
857 """
867 """
858 self._orig_sys_module_state = {'stdin': sys.stdin,
868 self._orig_sys_module_state = {'stdin': sys.stdin,
859 'stdout': sys.stdout,
869 'stdout': sys.stdout,
860 'stderr': sys.stderr,
870 'stderr': sys.stderr,
861 'excepthook': sys.excepthook}
871 'excepthook': sys.excepthook}
862 self._orig_sys_modules_main_name = self.user_module.__name__
872 self._orig_sys_modules_main_name = self.user_module.__name__
863 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
873 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
864
874
865 def restore_sys_module_state(self):
875 def restore_sys_module_state(self):
866 """Restore the state of the sys module."""
876 """Restore the state of the sys module."""
867 try:
877 try:
868 for k, v in self._orig_sys_module_state.items():
878 for k, v in self._orig_sys_module_state.items():
869 setattr(sys, k, v)
879 setattr(sys, k, v)
870 except AttributeError:
880 except AttributeError:
871 pass
881 pass
872 # Reset what what done in self.init_sys_modules
882 # Reset what what done in self.init_sys_modules
873 if self._orig_sys_modules_main_mod is not None:
883 if self._orig_sys_modules_main_mod is not None:
874 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
884 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
875
885
876 #-------------------------------------------------------------------------
886 #-------------------------------------------------------------------------
877 # Things related to the banner
887 # Things related to the banner
878 #-------------------------------------------------------------------------
888 #-------------------------------------------------------------------------
879
889
880 @property
890 @property
881 def banner(self):
891 def banner(self):
882 banner = self.banner1
892 banner = self.banner1
883 if self.profile and self.profile != 'default':
893 if self.profile and self.profile != 'default':
884 banner += '\nIPython profile: %s\n' % self.profile
894 banner += '\nIPython profile: %s\n' % self.profile
885 if self.banner2:
895 if self.banner2:
886 banner += '\n' + self.banner2
896 banner += '\n' + self.banner2
887 return banner
897 return banner
888
898
889 def show_banner(self, banner=None):
899 def show_banner(self, banner=None):
890 if banner is None:
900 if banner is None:
891 banner = self.banner
901 banner = self.banner
892 sys.stdout.write(banner)
902 sys.stdout.write(banner)
893
903
894 #-------------------------------------------------------------------------
904 #-------------------------------------------------------------------------
895 # Things related to hooks
905 # Things related to hooks
896 #-------------------------------------------------------------------------
906 #-------------------------------------------------------------------------
897
907
898 def init_hooks(self):
908 def init_hooks(self):
899 # hooks holds pointers used for user-side customizations
909 # hooks holds pointers used for user-side customizations
900 self.hooks = Struct()
910 self.hooks = Struct()
901
911
902 self.strdispatchers = {}
912 self.strdispatchers = {}
903
913
904 # Set all default hooks, defined in the IPython.hooks module.
914 # Set all default hooks, defined in the IPython.hooks module.
905 hooks = IPython.core.hooks
915 hooks = IPython.core.hooks
906 for hook_name in hooks.__all__:
916 for hook_name in hooks.__all__:
907 # default hooks have priority 100, i.e. low; user hooks should have
917 # default hooks have priority 100, i.e. low; user hooks should have
908 # 0-100 priority
918 # 0-100 priority
909 self.set_hook(hook_name, getattr(hooks, hook_name), 100)
919 self.set_hook(hook_name, getattr(hooks, hook_name), 100)
910
920
911 if self.display_page:
921 if self.display_page:
912 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
922 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
913
923
914 def set_hook(self, name, hook, priority=50, str_key=None, re_key=None):
924 def set_hook(self, name, hook, priority=50, str_key=None, re_key=None):
915 """set_hook(name,hook) -> sets an internal IPython hook.
925 """set_hook(name,hook) -> sets an internal IPython hook.
916
926
917 IPython exposes some of its internal API as user-modifiable hooks. By
927 IPython exposes some of its internal API as user-modifiable hooks. By
918 adding your function to one of these hooks, you can modify IPython's
928 adding your function to one of these hooks, you can modify IPython's
919 behavior to call at runtime your own routines."""
929 behavior to call at runtime your own routines."""
920
930
921 # At some point in the future, this should validate the hook before it
931 # At some point in the future, this should validate the hook before it
922 # accepts it. Probably at least check that the hook takes the number
932 # accepts it. Probably at least check that the hook takes the number
923 # of args it's supposed to.
933 # of args it's supposed to.
924
934
925 f = types.MethodType(hook,self)
935 f = types.MethodType(hook,self)
926
936
927 # check if the hook is for strdispatcher first
937 # check if the hook is for strdispatcher first
928 if str_key is not None:
938 if str_key is not None:
929 sdp = self.strdispatchers.get(name, StrDispatch())
939 sdp = self.strdispatchers.get(name, StrDispatch())
930 sdp.add_s(str_key, f, priority )
940 sdp.add_s(str_key, f, priority )
931 self.strdispatchers[name] = sdp
941 self.strdispatchers[name] = sdp
932 return
942 return
933 if re_key is not None:
943 if re_key is not None:
934 sdp = self.strdispatchers.get(name, StrDispatch())
944 sdp = self.strdispatchers.get(name, StrDispatch())
935 sdp.add_re(re.compile(re_key), f, priority )
945 sdp.add_re(re.compile(re_key), f, priority )
936 self.strdispatchers[name] = sdp
946 self.strdispatchers[name] = sdp
937 return
947 return
938
948
939 dp = getattr(self.hooks, name, None)
949 dp = getattr(self.hooks, name, None)
940 if name not in IPython.core.hooks.__all__:
950 if name not in IPython.core.hooks.__all__:
941 print("Warning! Hook '%s' is not one of %s" % \
951 print("Warning! Hook '%s' is not one of %s" % \
942 (name, IPython.core.hooks.__all__ ))
952 (name, IPython.core.hooks.__all__ ))
943
953
944 if name in IPython.core.hooks.deprecated:
954 if name in IPython.core.hooks.deprecated:
945 alternative = IPython.core.hooks.deprecated[name]
955 alternative = IPython.core.hooks.deprecated[name]
946 raise ValueError(
956 raise ValueError(
947 "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format(
957 "Hook {} has been deprecated since IPython 5.0. Use {} instead.".format(
948 name, alternative
958 name, alternative
949 )
959 )
950 )
960 )
951
961
952 if not dp:
962 if not dp:
953 dp = IPython.core.hooks.CommandChainDispatcher()
963 dp = IPython.core.hooks.CommandChainDispatcher()
954
964
955 try:
965 try:
956 dp.add(f,priority)
966 dp.add(f,priority)
957 except AttributeError:
967 except AttributeError:
958 # it was not commandchain, plain old func - replace
968 # it was not commandchain, plain old func - replace
959 dp = f
969 dp = f
960
970
961 setattr(self.hooks,name, dp)
971 setattr(self.hooks,name, dp)
962
972
963 #-------------------------------------------------------------------------
973 #-------------------------------------------------------------------------
964 # Things related to events
974 # Things related to events
965 #-------------------------------------------------------------------------
975 #-------------------------------------------------------------------------
966
976
967 def init_events(self):
977 def init_events(self):
968 self.events = EventManager(self, available_events)
978 self.events = EventManager(self, available_events)
969
979
970 self.events.register("pre_execute", self._clear_warning_registry)
980 self.events.register("pre_execute", self._clear_warning_registry)
971
981
972 def register_post_execute(self, func):
982 def register_post_execute(self, func):
973 """DEPRECATED: Use ip.events.register('post_run_cell', func)
983 """DEPRECATED: Use ip.events.register('post_run_cell', func)
974
984
975 Register a function for calling after code execution.
985 Register a function for calling after code execution.
976 """
986 """
977 raise ValueError(
987 raise ValueError(
978 "ip.register_post_execute is deprecated since IPython 1.0, use "
988 "ip.register_post_execute is deprecated since IPython 1.0, use "
979 "ip.events.register('post_run_cell', func) instead."
989 "ip.events.register('post_run_cell', func) instead."
980 )
990 )
981
991
982 def _clear_warning_registry(self):
992 def _clear_warning_registry(self):
983 # clear the warning registry, so that different code blocks with
993 # clear the warning registry, so that different code blocks with
984 # overlapping line number ranges don't cause spurious suppression of
994 # overlapping line number ranges don't cause spurious suppression of
985 # warnings (see gh-6611 for details)
995 # warnings (see gh-6611 for details)
986 if "__warningregistry__" in self.user_global_ns:
996 if "__warningregistry__" in self.user_global_ns:
987 del self.user_global_ns["__warningregistry__"]
997 del self.user_global_ns["__warningregistry__"]
988
998
989 #-------------------------------------------------------------------------
999 #-------------------------------------------------------------------------
990 # Things related to the "main" module
1000 # Things related to the "main" module
991 #-------------------------------------------------------------------------
1001 #-------------------------------------------------------------------------
992
1002
993 def new_main_mod(self, filename, modname):
1003 def new_main_mod(self, filename, modname):
994 """Return a new 'main' module object for user code execution.
1004 """Return a new 'main' module object for user code execution.
995
1005
996 ``filename`` should be the path of the script which will be run in the
1006 ``filename`` should be the path of the script which will be run in the
997 module. Requests with the same filename will get the same module, with
1007 module. Requests with the same filename will get the same module, with
998 its namespace cleared.
1008 its namespace cleared.
999
1009
1000 ``modname`` should be the module name - normally either '__main__' or
1010 ``modname`` should be the module name - normally either '__main__' or
1001 the basename of the file without the extension.
1011 the basename of the file without the extension.
1002
1012
1003 When scripts are executed via %run, we must keep a reference to their
1013 When scripts are executed via %run, we must keep a reference to their
1004 __main__ module around so that Python doesn't
1014 __main__ module around so that Python doesn't
1005 clear it, rendering references to module globals useless.
1015 clear it, rendering references to module globals useless.
1006
1016
1007 This method keeps said reference in a private dict, keyed by the
1017 This method keeps said reference in a private dict, keyed by the
1008 absolute path of the script. This way, for multiple executions of the
1018 absolute path of the script. This way, for multiple executions of the
1009 same script we only keep one copy of the namespace (the last one),
1019 same script we only keep one copy of the namespace (the last one),
1010 thus preventing memory leaks from old references while allowing the
1020 thus preventing memory leaks from old references while allowing the
1011 objects from the last execution to be accessible.
1021 objects from the last execution to be accessible.
1012 """
1022 """
1013 filename = os.path.abspath(filename)
1023 filename = os.path.abspath(filename)
1014 try:
1024 try:
1015 main_mod = self._main_mod_cache[filename]
1025 main_mod = self._main_mod_cache[filename]
1016 except KeyError:
1026 except KeyError:
1017 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1027 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1018 modname,
1028 modname,
1019 doc="Module created for script run in IPython")
1029 doc="Module created for script run in IPython")
1020 else:
1030 else:
1021 main_mod.__dict__.clear()
1031 main_mod.__dict__.clear()
1022 main_mod.__name__ = modname
1032 main_mod.__name__ = modname
1023
1033
1024 main_mod.__file__ = filename
1034 main_mod.__file__ = filename
1025 # It seems pydoc (and perhaps others) needs any module instance to
1035 # It seems pydoc (and perhaps others) needs any module instance to
1026 # implement a __nonzero__ method
1036 # implement a __nonzero__ method
1027 main_mod.__nonzero__ = lambda : True
1037 main_mod.__nonzero__ = lambda : True
1028
1038
1029 return main_mod
1039 return main_mod
1030
1040
1031 def clear_main_mod_cache(self):
1041 def clear_main_mod_cache(self):
1032 """Clear the cache of main modules.
1042 """Clear the cache of main modules.
1033
1043
1034 Mainly for use by utilities like %reset.
1044 Mainly for use by utilities like %reset.
1035
1045
1036 Examples
1046 Examples
1037 --------
1047 --------
1038 In [15]: import IPython
1048 In [15]: import IPython
1039
1049
1040 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1050 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1041
1051
1042 In [17]: len(_ip._main_mod_cache) > 0
1052 In [17]: len(_ip._main_mod_cache) > 0
1043 Out[17]: True
1053 Out[17]: True
1044
1054
1045 In [18]: _ip.clear_main_mod_cache()
1055 In [18]: _ip.clear_main_mod_cache()
1046
1056
1047 In [19]: len(_ip._main_mod_cache) == 0
1057 In [19]: len(_ip._main_mod_cache) == 0
1048 Out[19]: True
1058 Out[19]: True
1049 """
1059 """
1050 self._main_mod_cache.clear()
1060 self._main_mod_cache.clear()
1051
1061
1052 #-------------------------------------------------------------------------
1062 #-------------------------------------------------------------------------
1053 # Things related to debugging
1063 # Things related to debugging
1054 #-------------------------------------------------------------------------
1064 #-------------------------------------------------------------------------
1055
1065
1056 def init_pdb(self):
1066 def init_pdb(self):
1057 # Set calling of pdb on exceptions
1067 # Set calling of pdb on exceptions
1058 # self.call_pdb is a property
1068 # self.call_pdb is a property
1059 self.call_pdb = self.pdb
1069 self.call_pdb = self.pdb
1060
1070
1061 def _get_call_pdb(self):
1071 def _get_call_pdb(self):
1062 return self._call_pdb
1072 return self._call_pdb
1063
1073
1064 def _set_call_pdb(self,val):
1074 def _set_call_pdb(self,val):
1065
1075
1066 if val not in (0,1,False,True):
1076 if val not in (0,1,False,True):
1067 raise ValueError('new call_pdb value must be boolean')
1077 raise ValueError('new call_pdb value must be boolean')
1068
1078
1069 # store value in instance
1079 # store value in instance
1070 self._call_pdb = val
1080 self._call_pdb = val
1071
1081
1072 # notify the actual exception handlers
1082 # notify the actual exception handlers
1073 self.InteractiveTB.call_pdb = val
1083 self.InteractiveTB.call_pdb = val
1074
1084
1075 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1085 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1076 'Control auto-activation of pdb at exceptions')
1086 'Control auto-activation of pdb at exceptions')
1077
1087
1078 def debugger(self,force=False):
1088 def debugger(self,force=False):
1079 """Call the pdb debugger.
1089 """Call the pdb debugger.
1080
1090
1081 Keywords:
1091 Keywords:
1082
1092
1083 - force(False): by default, this routine checks the instance call_pdb
1093 - force(False): by default, this routine checks the instance call_pdb
1084 flag and does not actually invoke the debugger if the flag is false.
1094 flag and does not actually invoke the debugger if the flag is false.
1085 The 'force' option forces the debugger to activate even if the flag
1095 The 'force' option forces the debugger to activate even if the flag
1086 is false.
1096 is false.
1087 """
1097 """
1088
1098
1089 if not (force or self.call_pdb):
1099 if not (force or self.call_pdb):
1090 return
1100 return
1091
1101
1092 if not hasattr(sys,'last_traceback'):
1102 if not hasattr(sys,'last_traceback'):
1093 error('No traceback has been produced, nothing to debug.')
1103 error('No traceback has been produced, nothing to debug.')
1094 return
1104 return
1095
1105
1096 self.InteractiveTB.debugger(force=True)
1106 self.InteractiveTB.debugger(force=True)
1097
1107
1098 #-------------------------------------------------------------------------
1108 #-------------------------------------------------------------------------
1099 # Things related to IPython's various namespaces
1109 # Things related to IPython's various namespaces
1100 #-------------------------------------------------------------------------
1110 #-------------------------------------------------------------------------
1101 default_user_namespaces = True
1111 default_user_namespaces = True
1102
1112
1103 def init_create_namespaces(self, user_module=None, user_ns=None):
1113 def init_create_namespaces(self, user_module=None, user_ns=None):
1104 # Create the namespace where the user will operate. user_ns is
1114 # Create the namespace where the user will operate. user_ns is
1105 # normally the only one used, and it is passed to the exec calls as
1115 # normally the only one used, and it is passed to the exec calls as
1106 # the locals argument. But we do carry a user_global_ns namespace
1116 # the locals argument. But we do carry a user_global_ns namespace
1107 # given as the exec 'globals' argument, This is useful in embedding
1117 # given as the exec 'globals' argument, This is useful in embedding
1108 # situations where the ipython shell opens in a context where the
1118 # situations where the ipython shell opens in a context where the
1109 # distinction between locals and globals is meaningful. For
1119 # distinction between locals and globals is meaningful. For
1110 # non-embedded contexts, it is just the same object as the user_ns dict.
1120 # non-embedded contexts, it is just the same object as the user_ns dict.
1111
1121
1112 # FIXME. For some strange reason, __builtins__ is showing up at user
1122 # FIXME. For some strange reason, __builtins__ is showing up at user
1113 # level as a dict instead of a module. This is a manual fix, but I
1123 # level as a dict instead of a module. This is a manual fix, but I
1114 # should really track down where the problem is coming from. Alex
1124 # should really track down where the problem is coming from. Alex
1115 # Schmolck reported this problem first.
1125 # Schmolck reported this problem first.
1116
1126
1117 # A useful post by Alex Martelli on this topic:
1127 # A useful post by Alex Martelli on this topic:
1118 # Re: inconsistent value from __builtins__
1128 # Re: inconsistent value from __builtins__
1119 # Von: Alex Martelli <aleaxit@yahoo.com>
1129 # Von: Alex Martelli <aleaxit@yahoo.com>
1120 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1130 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1121 # Gruppen: comp.lang.python
1131 # Gruppen: comp.lang.python
1122
1132
1123 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1133 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1124 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1134 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1125 # > <type 'dict'>
1135 # > <type 'dict'>
1126 # > >>> print type(__builtins__)
1136 # > >>> print type(__builtins__)
1127 # > <type 'module'>
1137 # > <type 'module'>
1128 # > Is this difference in return value intentional?
1138 # > Is this difference in return value intentional?
1129
1139
1130 # Well, it's documented that '__builtins__' can be either a dictionary
1140 # Well, it's documented that '__builtins__' can be either a dictionary
1131 # or a module, and it's been that way for a long time. Whether it's
1141 # or a module, and it's been that way for a long time. Whether it's
1132 # intentional (or sensible), I don't know. In any case, the idea is
1142 # intentional (or sensible), I don't know. In any case, the idea is
1133 # that if you need to access the built-in namespace directly, you
1143 # that if you need to access the built-in namespace directly, you
1134 # should start with "import __builtin__" (note, no 's') which will
1144 # should start with "import __builtin__" (note, no 's') which will
1135 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1145 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1136
1146
1137 # These routines return a properly built module and dict as needed by
1147 # These routines return a properly built module and dict as needed by
1138 # the rest of the code, and can also be used by extension writers to
1148 # the rest of the code, and can also be used by extension writers to
1139 # generate properly initialized namespaces.
1149 # generate properly initialized namespaces.
1140 if (user_ns is not None) or (user_module is not None):
1150 if (user_ns is not None) or (user_module is not None):
1141 self.default_user_namespaces = False
1151 self.default_user_namespaces = False
1142 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1152 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1143
1153
1144 # A record of hidden variables we have added to the user namespace, so
1154 # A record of hidden variables we have added to the user namespace, so
1145 # we can list later only variables defined in actual interactive use.
1155 # we can list later only variables defined in actual interactive use.
1146 self.user_ns_hidden = {}
1156 self.user_ns_hidden = {}
1147
1157
1148 # Now that FakeModule produces a real module, we've run into a nasty
1158 # Now that FakeModule produces a real module, we've run into a nasty
1149 # problem: after script execution (via %run), the module where the user
1159 # problem: after script execution (via %run), the module where the user
1150 # code ran is deleted. Now that this object is a true module (needed
1160 # code ran is deleted. Now that this object is a true module (needed
1151 # so doctest and other tools work correctly), the Python module
1161 # so doctest and other tools work correctly), the Python module
1152 # teardown mechanism runs over it, and sets to None every variable
1162 # teardown mechanism runs over it, and sets to None every variable
1153 # present in that module. Top-level references to objects from the
1163 # present in that module. Top-level references to objects from the
1154 # script survive, because the user_ns is updated with them. However,
1164 # script survive, because the user_ns is updated with them. However,
1155 # calling functions defined in the script that use other things from
1165 # calling functions defined in the script that use other things from
1156 # the script will fail, because the function's closure had references
1166 # the script will fail, because the function's closure had references
1157 # to the original objects, which are now all None. So we must protect
1167 # to the original objects, which are now all None. So we must protect
1158 # these modules from deletion by keeping a cache.
1168 # these modules from deletion by keeping a cache.
1159 #
1169 #
1160 # To avoid keeping stale modules around (we only need the one from the
1170 # To avoid keeping stale modules around (we only need the one from the
1161 # last run), we use a dict keyed with the full path to the script, so
1171 # last run), we use a dict keyed with the full path to the script, so
1162 # only the last version of the module is held in the cache. Note,
1172 # only the last version of the module is held in the cache. Note,
1163 # however, that we must cache the module *namespace contents* (their
1173 # however, that we must cache the module *namespace contents* (their
1164 # __dict__). Because if we try to cache the actual modules, old ones
1174 # __dict__). Because if we try to cache the actual modules, old ones
1165 # (uncached) could be destroyed while still holding references (such as
1175 # (uncached) could be destroyed while still holding references (such as
1166 # those held by GUI objects that tend to be long-lived)>
1176 # those held by GUI objects that tend to be long-lived)>
1167 #
1177 #
1168 # The %reset command will flush this cache. See the cache_main_mod()
1178 # The %reset command will flush this cache. See the cache_main_mod()
1169 # and clear_main_mod_cache() methods for details on use.
1179 # and clear_main_mod_cache() methods for details on use.
1170
1180
1171 # This is the cache used for 'main' namespaces
1181 # This is the cache used for 'main' namespaces
1172 self._main_mod_cache = {}
1182 self._main_mod_cache = {}
1173
1183
1174 # A table holding all the namespaces IPython deals with, so that
1184 # A table holding all the namespaces IPython deals with, so that
1175 # introspection facilities can search easily.
1185 # introspection facilities can search easily.
1176 self.ns_table = {'user_global':self.user_module.__dict__,
1186 self.ns_table = {'user_global':self.user_module.__dict__,
1177 'user_local':self.user_ns,
1187 'user_local':self.user_ns,
1178 'builtin':builtin_mod.__dict__
1188 'builtin':builtin_mod.__dict__
1179 }
1189 }
1180
1190
1181 @property
1191 @property
1182 def user_global_ns(self):
1192 def user_global_ns(self):
1183 return self.user_module.__dict__
1193 return self.user_module.__dict__
1184
1194
1185 def prepare_user_module(self, user_module=None, user_ns=None):
1195 def prepare_user_module(self, user_module=None, user_ns=None):
1186 """Prepare the module and namespace in which user code will be run.
1196 """Prepare the module and namespace in which user code will be run.
1187
1197
1188 When IPython is started normally, both parameters are None: a new module
1198 When IPython is started normally, both parameters are None: a new module
1189 is created automatically, and its __dict__ used as the namespace.
1199 is created automatically, and its __dict__ used as the namespace.
1190
1200
1191 If only user_module is provided, its __dict__ is used as the namespace.
1201 If only user_module is provided, its __dict__ is used as the namespace.
1192 If only user_ns is provided, a dummy module is created, and user_ns
1202 If only user_ns is provided, a dummy module is created, and user_ns
1193 becomes the global namespace. If both are provided (as they may be
1203 becomes the global namespace. If both are provided (as they may be
1194 when embedding), user_ns is the local namespace, and user_module
1204 when embedding), user_ns is the local namespace, and user_module
1195 provides the global namespace.
1205 provides the global namespace.
1196
1206
1197 Parameters
1207 Parameters
1198 ----------
1208 ----------
1199 user_module : module, optional
1209 user_module : module, optional
1200 The current user module in which IPython is being run. If None,
1210 The current user module in which IPython is being run. If None,
1201 a clean module will be created.
1211 a clean module will be created.
1202 user_ns : dict, optional
1212 user_ns : dict, optional
1203 A namespace in which to run interactive commands.
1213 A namespace in which to run interactive commands.
1204
1214
1205 Returns
1215 Returns
1206 -------
1216 -------
1207 A tuple of user_module and user_ns, each properly initialised.
1217 A tuple of user_module and user_ns, each properly initialised.
1208 """
1218 """
1209 if user_module is None and user_ns is not None:
1219 if user_module is None and user_ns is not None:
1210 user_ns.setdefault("__name__", "__main__")
1220 user_ns.setdefault("__name__", "__main__")
1211 user_module = DummyMod()
1221 user_module = DummyMod()
1212 user_module.__dict__ = user_ns
1222 user_module.__dict__ = user_ns
1213
1223
1214 if user_module is None:
1224 if user_module is None:
1215 user_module = types.ModuleType("__main__",
1225 user_module = types.ModuleType("__main__",
1216 doc="Automatically created module for IPython interactive environment")
1226 doc="Automatically created module for IPython interactive environment")
1217
1227
1218 # We must ensure that __builtin__ (without the final 's') is always
1228 # We must ensure that __builtin__ (without the final 's') is always
1219 # available and pointing to the __builtin__ *module*. For more details:
1229 # available and pointing to the __builtin__ *module*. For more details:
1220 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1230 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1221 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1231 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1222 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1232 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1223
1233
1224 if user_ns is None:
1234 if user_ns is None:
1225 user_ns = user_module.__dict__
1235 user_ns = user_module.__dict__
1226
1236
1227 return user_module, user_ns
1237 return user_module, user_ns
1228
1238
1229 def init_sys_modules(self):
1239 def init_sys_modules(self):
1230 # We need to insert into sys.modules something that looks like a
1240 # We need to insert into sys.modules something that looks like a
1231 # module but which accesses the IPython namespace, for shelve and
1241 # module but which accesses the IPython namespace, for shelve and
1232 # pickle to work interactively. Normally they rely on getting
1242 # pickle to work interactively. Normally they rely on getting
1233 # everything out of __main__, but for embedding purposes each IPython
1243 # everything out of __main__, but for embedding purposes each IPython
1234 # instance has its own private namespace, so we can't go shoving
1244 # instance has its own private namespace, so we can't go shoving
1235 # everything into __main__.
1245 # everything into __main__.
1236
1246
1237 # note, however, that we should only do this for non-embedded
1247 # note, however, that we should only do this for non-embedded
1238 # ipythons, which really mimic the __main__.__dict__ with their own
1248 # ipythons, which really mimic the __main__.__dict__ with their own
1239 # namespace. Embedded instances, on the other hand, should not do
1249 # namespace. Embedded instances, on the other hand, should not do
1240 # this because they need to manage the user local/global namespaces
1250 # this because they need to manage the user local/global namespaces
1241 # only, but they live within a 'normal' __main__ (meaning, they
1251 # only, but they live within a 'normal' __main__ (meaning, they
1242 # shouldn't overtake the execution environment of the script they're
1252 # shouldn't overtake the execution environment of the script they're
1243 # embedded in).
1253 # embedded in).
1244
1254
1245 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1255 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1246 main_name = self.user_module.__name__
1256 main_name = self.user_module.__name__
1247 sys.modules[main_name] = self.user_module
1257 sys.modules[main_name] = self.user_module
1248
1258
1249 def init_user_ns(self):
1259 def init_user_ns(self):
1250 """Initialize all user-visible namespaces to their minimum defaults.
1260 """Initialize all user-visible namespaces to their minimum defaults.
1251
1261
1252 Certain history lists are also initialized here, as they effectively
1262 Certain history lists are also initialized here, as they effectively
1253 act as user namespaces.
1263 act as user namespaces.
1254
1264
1255 Notes
1265 Notes
1256 -----
1266 -----
1257 All data structures here are only filled in, they are NOT reset by this
1267 All data structures here are only filled in, they are NOT reset by this
1258 method. If they were not empty before, data will simply be added to
1268 method. If they were not empty before, data will simply be added to
1259 them.
1269 them.
1260 """
1270 """
1261 # This function works in two parts: first we put a few things in
1271 # This function works in two parts: first we put a few things in
1262 # user_ns, and we sync that contents into user_ns_hidden so that these
1272 # user_ns, and we sync that contents into user_ns_hidden so that these
1263 # initial variables aren't shown by %who. After the sync, we add the
1273 # initial variables aren't shown by %who. After the sync, we add the
1264 # rest of what we *do* want the user to see with %who even on a new
1274 # rest of what we *do* want the user to see with %who even on a new
1265 # session (probably nothing, so they really only see their own stuff)
1275 # session (probably nothing, so they really only see their own stuff)
1266
1276
1267 # The user dict must *always* have a __builtin__ reference to the
1277 # The user dict must *always* have a __builtin__ reference to the
1268 # Python standard __builtin__ namespace, which must be imported.
1278 # Python standard __builtin__ namespace, which must be imported.
1269 # This is so that certain operations in prompt evaluation can be
1279 # This is so that certain operations in prompt evaluation can be
1270 # reliably executed with builtins. Note that we can NOT use
1280 # reliably executed with builtins. Note that we can NOT use
1271 # __builtins__ (note the 's'), because that can either be a dict or a
1281 # __builtins__ (note the 's'), because that can either be a dict or a
1272 # module, and can even mutate at runtime, depending on the context
1282 # module, and can even mutate at runtime, depending on the context
1273 # (Python makes no guarantees on it). In contrast, __builtin__ is
1283 # (Python makes no guarantees on it). In contrast, __builtin__ is
1274 # always a module object, though it must be explicitly imported.
1284 # always a module object, though it must be explicitly imported.
1275
1285
1276 # For more details:
1286 # For more details:
1277 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1287 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1278 ns = {}
1288 ns = {}
1279
1289
1280 # make global variables for user access to the histories
1290 # make global variables for user access to the histories
1281 ns['_ih'] = self.history_manager.input_hist_parsed
1291 ns['_ih'] = self.history_manager.input_hist_parsed
1282 ns['_oh'] = self.history_manager.output_hist
1292 ns['_oh'] = self.history_manager.output_hist
1283 ns['_dh'] = self.history_manager.dir_hist
1293 ns['_dh'] = self.history_manager.dir_hist
1284
1294
1285 # user aliases to input and output histories. These shouldn't show up
1295 # user aliases to input and output histories. These shouldn't show up
1286 # in %who, as they can have very large reprs.
1296 # in %who, as they can have very large reprs.
1287 ns['In'] = self.history_manager.input_hist_parsed
1297 ns['In'] = self.history_manager.input_hist_parsed
1288 ns['Out'] = self.history_manager.output_hist
1298 ns['Out'] = self.history_manager.output_hist
1289
1299
1290 # Store myself as the public api!!!
1300 # Store myself as the public api!!!
1291 ns['get_ipython'] = self.get_ipython
1301 ns['get_ipython'] = self.get_ipython
1292
1302
1293 ns['exit'] = self.exiter
1303 ns['exit'] = self.exiter
1294 ns['quit'] = self.exiter
1304 ns['quit'] = self.exiter
1295
1305
1296 # Sync what we've added so far to user_ns_hidden so these aren't seen
1306 # Sync what we've added so far to user_ns_hidden so these aren't seen
1297 # by %who
1307 # by %who
1298 self.user_ns_hidden.update(ns)
1308 self.user_ns_hidden.update(ns)
1299
1309
1300 # Anything put into ns now would show up in %who. Think twice before
1310 # Anything put into ns now would show up in %who. Think twice before
1301 # putting anything here, as we really want %who to show the user their
1311 # putting anything here, as we really want %who to show the user their
1302 # stuff, not our variables.
1312 # stuff, not our variables.
1303
1313
1304 # Finally, update the real user's namespace
1314 # Finally, update the real user's namespace
1305 self.user_ns.update(ns)
1315 self.user_ns.update(ns)
1306
1316
1307 @property
1317 @property
1308 def all_ns_refs(self):
1318 def all_ns_refs(self):
1309 """Get a list of references to all the namespace dictionaries in which
1319 """Get a list of references to all the namespace dictionaries in which
1310 IPython might store a user-created object.
1320 IPython might store a user-created object.
1311
1321
1312 Note that this does not include the displayhook, which also caches
1322 Note that this does not include the displayhook, which also caches
1313 objects from the output."""
1323 objects from the output."""
1314 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1324 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1315 [m.__dict__ for m in self._main_mod_cache.values()]
1325 [m.__dict__ for m in self._main_mod_cache.values()]
1316
1326
1317 def reset(self, new_session=True, aggressive=False):
1327 def reset(self, new_session=True, aggressive=False):
1318 """Clear all internal namespaces, and attempt to release references to
1328 """Clear all internal namespaces, and attempt to release references to
1319 user objects.
1329 user objects.
1320
1330
1321 If new_session is True, a new history session will be opened.
1331 If new_session is True, a new history session will be opened.
1322 """
1332 """
1323 # Clear histories
1333 # Clear histories
1324 self.history_manager.reset(new_session)
1334 self.history_manager.reset(new_session)
1325 # Reset counter used to index all histories
1335 # Reset counter used to index all histories
1326 if new_session:
1336 if new_session:
1327 self.execution_count = 1
1337 self.execution_count = 1
1328
1338
1329 # Reset last execution result
1339 # Reset last execution result
1330 self.last_execution_succeeded = True
1340 self.last_execution_succeeded = True
1331 self.last_execution_result = None
1341 self.last_execution_result = None
1332
1342
1333 # Flush cached output items
1343 # Flush cached output items
1334 if self.displayhook.do_full_cache:
1344 if self.displayhook.do_full_cache:
1335 self.displayhook.flush()
1345 self.displayhook.flush()
1336
1346
1337 # The main execution namespaces must be cleared very carefully,
1347 # The main execution namespaces must be cleared very carefully,
1338 # skipping the deletion of the builtin-related keys, because doing so
1348 # skipping the deletion of the builtin-related keys, because doing so
1339 # would cause errors in many object's __del__ methods.
1349 # would cause errors in many object's __del__ methods.
1340 if self.user_ns is not self.user_global_ns:
1350 if self.user_ns is not self.user_global_ns:
1341 self.user_ns.clear()
1351 self.user_ns.clear()
1342 ns = self.user_global_ns
1352 ns = self.user_global_ns
1343 drop_keys = set(ns.keys())
1353 drop_keys = set(ns.keys())
1344 drop_keys.discard('__builtin__')
1354 drop_keys.discard('__builtin__')
1345 drop_keys.discard('__builtins__')
1355 drop_keys.discard('__builtins__')
1346 drop_keys.discard('__name__')
1356 drop_keys.discard('__name__')
1347 for k in drop_keys:
1357 for k in drop_keys:
1348 del ns[k]
1358 del ns[k]
1349
1359
1350 self.user_ns_hidden.clear()
1360 self.user_ns_hidden.clear()
1351
1361
1352 # Restore the user namespaces to minimal usability
1362 # Restore the user namespaces to minimal usability
1353 self.init_user_ns()
1363 self.init_user_ns()
1354 if aggressive and not hasattr(self, "_sys_modules_keys"):
1364 if aggressive and not hasattr(self, "_sys_modules_keys"):
1355 print("Cannot restore sys.module, no snapshot")
1365 print("Cannot restore sys.module, no snapshot")
1356 elif aggressive:
1366 elif aggressive:
1357 print("culling sys module...")
1367 print("culling sys module...")
1358 current_keys = set(sys.modules.keys())
1368 current_keys = set(sys.modules.keys())
1359 for k in current_keys - self._sys_modules_keys:
1369 for k in current_keys - self._sys_modules_keys:
1360 if k.startswith("multiprocessing"):
1370 if k.startswith("multiprocessing"):
1361 continue
1371 continue
1362 del sys.modules[k]
1372 del sys.modules[k]
1363
1373
1364 # Restore the default and user aliases
1374 # Restore the default and user aliases
1365 self.alias_manager.clear_aliases()
1375 self.alias_manager.clear_aliases()
1366 self.alias_manager.init_aliases()
1376 self.alias_manager.init_aliases()
1367
1377
1368 # Now define aliases that only make sense on the terminal, because they
1378 # Now define aliases that only make sense on the terminal, because they
1369 # need direct access to the console in a way that we can't emulate in
1379 # need direct access to the console in a way that we can't emulate in
1370 # GUI or web frontend
1380 # GUI or web frontend
1371 if os.name == 'posix':
1381 if os.name == 'posix':
1372 for cmd in ('clear', 'more', 'less', 'man'):
1382 for cmd in ('clear', 'more', 'less', 'man'):
1373 if cmd not in self.magics_manager.magics['line']:
1383 if cmd not in self.magics_manager.magics['line']:
1374 self.alias_manager.soft_define_alias(cmd, cmd)
1384 self.alias_manager.soft_define_alias(cmd, cmd)
1375
1385
1376 # Flush the private list of module references kept for script
1386 # Flush the private list of module references kept for script
1377 # execution protection
1387 # execution protection
1378 self.clear_main_mod_cache()
1388 self.clear_main_mod_cache()
1379
1389
1380 def del_var(self, varname, by_name=False):
1390 def del_var(self, varname, by_name=False):
1381 """Delete a variable from the various namespaces, so that, as
1391 """Delete a variable from the various namespaces, so that, as
1382 far as possible, we're not keeping any hidden references to it.
1392 far as possible, we're not keeping any hidden references to it.
1383
1393
1384 Parameters
1394 Parameters
1385 ----------
1395 ----------
1386 varname : str
1396 varname : str
1387 The name of the variable to delete.
1397 The name of the variable to delete.
1388 by_name : bool
1398 by_name : bool
1389 If True, delete variables with the given name in each
1399 If True, delete variables with the given name in each
1390 namespace. If False (default), find the variable in the user
1400 namespace. If False (default), find the variable in the user
1391 namespace, and delete references to it.
1401 namespace, and delete references to it.
1392 """
1402 """
1393 if varname in ('__builtin__', '__builtins__'):
1403 if varname in ('__builtin__', '__builtins__'):
1394 raise ValueError("Refusing to delete %s" % varname)
1404 raise ValueError("Refusing to delete %s" % varname)
1395
1405
1396 ns_refs = self.all_ns_refs
1406 ns_refs = self.all_ns_refs
1397
1407
1398 if by_name: # Delete by name
1408 if by_name: # Delete by name
1399 for ns in ns_refs:
1409 for ns in ns_refs:
1400 try:
1410 try:
1401 del ns[varname]
1411 del ns[varname]
1402 except KeyError:
1412 except KeyError:
1403 pass
1413 pass
1404 else: # Delete by object
1414 else: # Delete by object
1405 try:
1415 try:
1406 obj = self.user_ns[varname]
1416 obj = self.user_ns[varname]
1407 except KeyError as e:
1417 except KeyError as e:
1408 raise NameError("name '%s' is not defined" % varname) from e
1418 raise NameError("name '%s' is not defined" % varname) from e
1409 # Also check in output history
1419 # Also check in output history
1410 ns_refs.append(self.history_manager.output_hist)
1420 ns_refs.append(self.history_manager.output_hist)
1411 for ns in ns_refs:
1421 for ns in ns_refs:
1412 to_delete = [n for n, o in ns.items() if o is obj]
1422 to_delete = [n for n, o in ns.items() if o is obj]
1413 for name in to_delete:
1423 for name in to_delete:
1414 del ns[name]
1424 del ns[name]
1415
1425
1416 # Ensure it is removed from the last execution result
1426 # Ensure it is removed from the last execution result
1417 if self.last_execution_result.result is obj:
1427 if self.last_execution_result.result is obj:
1418 self.last_execution_result = None
1428 self.last_execution_result = None
1419
1429
1420 # displayhook keeps extra references, but not in a dictionary
1430 # displayhook keeps extra references, but not in a dictionary
1421 for name in ('_', '__', '___'):
1431 for name in ('_', '__', '___'):
1422 if getattr(self.displayhook, name) is obj:
1432 if getattr(self.displayhook, name) is obj:
1423 setattr(self.displayhook, name, None)
1433 setattr(self.displayhook, name, None)
1424
1434
1425 def reset_selective(self, regex=None):
1435 def reset_selective(self, regex=None):
1426 """Clear selective variables from internal namespaces based on a
1436 """Clear selective variables from internal namespaces based on a
1427 specified regular expression.
1437 specified regular expression.
1428
1438
1429 Parameters
1439 Parameters
1430 ----------
1440 ----------
1431 regex : string or compiled pattern, optional
1441 regex : string or compiled pattern, optional
1432 A regular expression pattern that will be used in searching
1442 A regular expression pattern that will be used in searching
1433 variable names in the users namespaces.
1443 variable names in the users namespaces.
1434 """
1444 """
1435 if regex is not None:
1445 if regex is not None:
1436 try:
1446 try:
1437 m = re.compile(regex)
1447 m = re.compile(regex)
1438 except TypeError as e:
1448 except TypeError as e:
1439 raise TypeError('regex must be a string or compiled pattern') from e
1449 raise TypeError('regex must be a string or compiled pattern') from e
1440 # Search for keys in each namespace that match the given regex
1450 # Search for keys in each namespace that match the given regex
1441 # If a match is found, delete the key/value pair.
1451 # If a match is found, delete the key/value pair.
1442 for ns in self.all_ns_refs:
1452 for ns in self.all_ns_refs:
1443 for var in ns:
1453 for var in ns:
1444 if m.search(var):
1454 if m.search(var):
1445 del ns[var]
1455 del ns[var]
1446
1456
1447 def push(self, variables, interactive=True):
1457 def push(self, variables, interactive=True):
1448 """Inject a group of variables into the IPython user namespace.
1458 """Inject a group of variables into the IPython user namespace.
1449
1459
1450 Parameters
1460 Parameters
1451 ----------
1461 ----------
1452 variables : dict, str or list/tuple of str
1462 variables : dict, str or list/tuple of str
1453 The variables to inject into the user's namespace. If a dict, a
1463 The variables to inject into the user's namespace. If a dict, a
1454 simple update is done. If a str, the string is assumed to have
1464 simple update is done. If a str, the string is assumed to have
1455 variable names separated by spaces. A list/tuple of str can also
1465 variable names separated by spaces. A list/tuple of str can also
1456 be used to give the variable names. If just the variable names are
1466 be used to give the variable names. If just the variable names are
1457 give (list/tuple/str) then the variable values looked up in the
1467 give (list/tuple/str) then the variable values looked up in the
1458 callers frame.
1468 callers frame.
1459 interactive : bool
1469 interactive : bool
1460 If True (default), the variables will be listed with the ``who``
1470 If True (default), the variables will be listed with the ``who``
1461 magic.
1471 magic.
1462 """
1472 """
1463 vdict = None
1473 vdict = None
1464
1474
1465 # We need a dict of name/value pairs to do namespace updates.
1475 # We need a dict of name/value pairs to do namespace updates.
1466 if isinstance(variables, dict):
1476 if isinstance(variables, dict):
1467 vdict = variables
1477 vdict = variables
1468 elif isinstance(variables, (str, list, tuple)):
1478 elif isinstance(variables, (str, list, tuple)):
1469 if isinstance(variables, str):
1479 if isinstance(variables, str):
1470 vlist = variables.split()
1480 vlist = variables.split()
1471 else:
1481 else:
1472 vlist = variables
1482 vlist = variables
1473 vdict = {}
1483 vdict = {}
1474 cf = sys._getframe(1)
1484 cf = sys._getframe(1)
1475 for name in vlist:
1485 for name in vlist:
1476 try:
1486 try:
1477 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1487 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1478 except:
1488 except:
1479 print('Could not get variable %s from %s' %
1489 print('Could not get variable %s from %s' %
1480 (name,cf.f_code.co_name))
1490 (name,cf.f_code.co_name))
1481 else:
1491 else:
1482 raise ValueError('variables must be a dict/str/list/tuple')
1492 raise ValueError('variables must be a dict/str/list/tuple')
1483
1493
1484 # Propagate variables to user namespace
1494 # Propagate variables to user namespace
1485 self.user_ns.update(vdict)
1495 self.user_ns.update(vdict)
1486
1496
1487 # And configure interactive visibility
1497 # And configure interactive visibility
1488 user_ns_hidden = self.user_ns_hidden
1498 user_ns_hidden = self.user_ns_hidden
1489 if interactive:
1499 if interactive:
1490 for name in vdict:
1500 for name in vdict:
1491 user_ns_hidden.pop(name, None)
1501 user_ns_hidden.pop(name, None)
1492 else:
1502 else:
1493 user_ns_hidden.update(vdict)
1503 user_ns_hidden.update(vdict)
1494
1504
1495 def drop_by_id(self, variables):
1505 def drop_by_id(self, variables):
1496 """Remove a dict of variables from the user namespace, if they are the
1506 """Remove a dict of variables from the user namespace, if they are the
1497 same as the values in the dictionary.
1507 same as the values in the dictionary.
1498
1508
1499 This is intended for use by extensions: variables that they've added can
1509 This is intended for use by extensions: variables that they've added can
1500 be taken back out if they are unloaded, without removing any that the
1510 be taken back out if they are unloaded, without removing any that the
1501 user has overwritten.
1511 user has overwritten.
1502
1512
1503 Parameters
1513 Parameters
1504 ----------
1514 ----------
1505 variables : dict
1515 variables : dict
1506 A dictionary mapping object names (as strings) to the objects.
1516 A dictionary mapping object names (as strings) to the objects.
1507 """
1517 """
1508 for name, obj in variables.items():
1518 for name, obj in variables.items():
1509 if name in self.user_ns and self.user_ns[name] is obj:
1519 if name in self.user_ns and self.user_ns[name] is obj:
1510 del self.user_ns[name]
1520 del self.user_ns[name]
1511 self.user_ns_hidden.pop(name, None)
1521 self.user_ns_hidden.pop(name, None)
1512
1522
1513 #-------------------------------------------------------------------------
1523 #-------------------------------------------------------------------------
1514 # Things related to object introspection
1524 # Things related to object introspection
1515 #-------------------------------------------------------------------------
1525 #-------------------------------------------------------------------------
1516
1526
1517 def _ofind(self, oname, namespaces=None):
1527 def _ofind(self, oname, namespaces=None):
1518 """Find an object in the available namespaces.
1528 """Find an object in the available namespaces.
1519
1529
1520 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1530 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1521
1531
1522 Has special code to detect magic functions.
1532 Has special code to detect magic functions.
1523 """
1533 """
1524 oname = oname.strip()
1534 oname = oname.strip()
1525 if not oname.startswith(ESC_MAGIC) and \
1535 if not oname.startswith(ESC_MAGIC) and \
1526 not oname.startswith(ESC_MAGIC2) and \
1536 not oname.startswith(ESC_MAGIC2) and \
1527 not all(a.isidentifier() for a in oname.split(".")):
1537 not all(a.isidentifier() for a in oname.split(".")):
1528 return {'found': False}
1538 return {'found': False}
1529
1539
1530 if namespaces is None:
1540 if namespaces is None:
1531 # Namespaces to search in:
1541 # Namespaces to search in:
1532 # Put them in a list. The order is important so that we
1542 # Put them in a list. The order is important so that we
1533 # find things in the same order that Python finds them.
1543 # find things in the same order that Python finds them.
1534 namespaces = [ ('Interactive', self.user_ns),
1544 namespaces = [ ('Interactive', self.user_ns),
1535 ('Interactive (global)', self.user_global_ns),
1545 ('Interactive (global)', self.user_global_ns),
1536 ('Python builtin', builtin_mod.__dict__),
1546 ('Python builtin', builtin_mod.__dict__),
1537 ]
1547 ]
1538
1548
1539 ismagic = False
1549 ismagic = False
1540 isalias = False
1550 isalias = False
1541 found = False
1551 found = False
1542 ospace = None
1552 ospace = None
1543 parent = None
1553 parent = None
1544 obj = None
1554 obj = None
1545
1555
1546
1556
1547 # Look for the given name by splitting it in parts. If the head is
1557 # Look for the given name by splitting it in parts. If the head is
1548 # found, then we look for all the remaining parts as members, and only
1558 # found, then we look for all the remaining parts as members, and only
1549 # declare success if we can find them all.
1559 # declare success if we can find them all.
1550 oname_parts = oname.split('.')
1560 oname_parts = oname.split('.')
1551 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1561 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1552 for nsname,ns in namespaces:
1562 for nsname,ns in namespaces:
1553 try:
1563 try:
1554 obj = ns[oname_head]
1564 obj = ns[oname_head]
1555 except KeyError:
1565 except KeyError:
1556 continue
1566 continue
1557 else:
1567 else:
1558 for idx, part in enumerate(oname_rest):
1568 for idx, part in enumerate(oname_rest):
1559 try:
1569 try:
1560 parent = obj
1570 parent = obj
1561 # The last part is looked up in a special way to avoid
1571 # The last part is looked up in a special way to avoid
1562 # descriptor invocation as it may raise or have side
1572 # descriptor invocation as it may raise or have side
1563 # effects.
1573 # effects.
1564 if idx == len(oname_rest) - 1:
1574 if idx == len(oname_rest) - 1:
1565 obj = self._getattr_property(obj, part)
1575 obj = self._getattr_property(obj, part)
1566 else:
1576 else:
1567 obj = getattr(obj, part)
1577 obj = getattr(obj, part)
1568 except:
1578 except:
1569 # Blanket except b/c some badly implemented objects
1579 # Blanket except b/c some badly implemented objects
1570 # allow __getattr__ to raise exceptions other than
1580 # allow __getattr__ to raise exceptions other than
1571 # AttributeError, which then crashes IPython.
1581 # AttributeError, which then crashes IPython.
1572 break
1582 break
1573 else:
1583 else:
1574 # If we finish the for loop (no break), we got all members
1584 # If we finish the for loop (no break), we got all members
1575 found = True
1585 found = True
1576 ospace = nsname
1586 ospace = nsname
1577 break # namespace loop
1587 break # namespace loop
1578
1588
1579 # Try to see if it's magic
1589 # Try to see if it's magic
1580 if not found:
1590 if not found:
1581 obj = None
1591 obj = None
1582 if oname.startswith(ESC_MAGIC2):
1592 if oname.startswith(ESC_MAGIC2):
1583 oname = oname.lstrip(ESC_MAGIC2)
1593 oname = oname.lstrip(ESC_MAGIC2)
1584 obj = self.find_cell_magic(oname)
1594 obj = self.find_cell_magic(oname)
1585 elif oname.startswith(ESC_MAGIC):
1595 elif oname.startswith(ESC_MAGIC):
1586 oname = oname.lstrip(ESC_MAGIC)
1596 oname = oname.lstrip(ESC_MAGIC)
1587 obj = self.find_line_magic(oname)
1597 obj = self.find_line_magic(oname)
1588 else:
1598 else:
1589 # search without prefix, so run? will find %run?
1599 # search without prefix, so run? will find %run?
1590 obj = self.find_line_magic(oname)
1600 obj = self.find_line_magic(oname)
1591 if obj is None:
1601 if obj is None:
1592 obj = self.find_cell_magic(oname)
1602 obj = self.find_cell_magic(oname)
1593 if obj is not None:
1603 if obj is not None:
1594 found = True
1604 found = True
1595 ospace = 'IPython internal'
1605 ospace = 'IPython internal'
1596 ismagic = True
1606 ismagic = True
1597 isalias = isinstance(obj, Alias)
1607 isalias = isinstance(obj, Alias)
1598
1608
1599 # Last try: special-case some literals like '', [], {}, etc:
1609 # Last try: special-case some literals like '', [], {}, etc:
1600 if not found and oname_head in ["''",'""','[]','{}','()']:
1610 if not found and oname_head in ["''",'""','[]','{}','()']:
1601 obj = eval(oname_head)
1611 obj = eval(oname_head)
1602 found = True
1612 found = True
1603 ospace = 'Interactive'
1613 ospace = 'Interactive'
1604
1614
1605 return {
1615 return {
1606 'obj':obj,
1616 'obj':obj,
1607 'found':found,
1617 'found':found,
1608 'parent':parent,
1618 'parent':parent,
1609 'ismagic':ismagic,
1619 'ismagic':ismagic,
1610 'isalias':isalias,
1620 'isalias':isalias,
1611 'namespace':ospace
1621 'namespace':ospace
1612 }
1622 }
1613
1623
1614 @staticmethod
1624 @staticmethod
1615 def _getattr_property(obj, attrname):
1625 def _getattr_property(obj, attrname):
1616 """Property-aware getattr to use in object finding.
1626 """Property-aware getattr to use in object finding.
1617
1627
1618 If attrname represents a property, return it unevaluated (in case it has
1628 If attrname represents a property, return it unevaluated (in case it has
1619 side effects or raises an error.
1629 side effects or raises an error.
1620
1630
1621 """
1631 """
1622 if not isinstance(obj, type):
1632 if not isinstance(obj, type):
1623 try:
1633 try:
1624 # `getattr(type(obj), attrname)` is not guaranteed to return
1634 # `getattr(type(obj), attrname)` is not guaranteed to return
1625 # `obj`, but does so for property:
1635 # `obj`, but does so for property:
1626 #
1636 #
1627 # property.__get__(self, None, cls) -> self
1637 # property.__get__(self, None, cls) -> self
1628 #
1638 #
1629 # The universal alternative is to traverse the mro manually
1639 # The universal alternative is to traverse the mro manually
1630 # searching for attrname in class dicts.
1640 # searching for attrname in class dicts.
1631 attr = getattr(type(obj), attrname)
1641 attr = getattr(type(obj), attrname)
1632 except AttributeError:
1642 except AttributeError:
1633 pass
1643 pass
1634 else:
1644 else:
1635 # This relies on the fact that data descriptors (with both
1645 # This relies on the fact that data descriptors (with both
1636 # __get__ & __set__ magic methods) take precedence over
1646 # __get__ & __set__ magic methods) take precedence over
1637 # instance-level attributes:
1647 # instance-level attributes:
1638 #
1648 #
1639 # class A(object):
1649 # class A(object):
1640 # @property
1650 # @property
1641 # def foobar(self): return 123
1651 # def foobar(self): return 123
1642 # a = A()
1652 # a = A()
1643 # a.__dict__['foobar'] = 345
1653 # a.__dict__['foobar'] = 345
1644 # a.foobar # == 123
1654 # a.foobar # == 123
1645 #
1655 #
1646 # So, a property may be returned right away.
1656 # So, a property may be returned right away.
1647 if isinstance(attr, property):
1657 if isinstance(attr, property):
1648 return attr
1658 return attr
1649
1659
1650 # Nothing helped, fall back.
1660 # Nothing helped, fall back.
1651 return getattr(obj, attrname)
1661 return getattr(obj, attrname)
1652
1662
1653 def _object_find(self, oname, namespaces=None):
1663 def _object_find(self, oname, namespaces=None):
1654 """Find an object and return a struct with info about it."""
1664 """Find an object and return a struct with info about it."""
1655 return Struct(self._ofind(oname, namespaces))
1665 return Struct(self._ofind(oname, namespaces))
1656
1666
1657 def _inspect(self, meth, oname, namespaces=None, **kw):
1667 def _inspect(self, meth, oname, namespaces=None, **kw):
1658 """Generic interface to the inspector system.
1668 """Generic interface to the inspector system.
1659
1669
1660 This function is meant to be called by pdef, pdoc & friends.
1670 This function is meant to be called by pdef, pdoc & friends.
1661 """
1671 """
1662 info = self._object_find(oname, namespaces)
1672 info = self._object_find(oname, namespaces)
1663 docformat = (
1673 docformat = (
1664 sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None
1674 sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None
1665 )
1675 )
1666 if info.found:
1676 if info.found:
1667 pmethod = getattr(self.inspector, meth)
1677 pmethod = getattr(self.inspector, meth)
1668 # TODO: only apply format_screen to the plain/text repr of the mime
1678 # TODO: only apply format_screen to the plain/text repr of the mime
1669 # bundle.
1679 # bundle.
1670 formatter = format_screen if info.ismagic else docformat
1680 formatter = format_screen if info.ismagic else docformat
1671 if meth == 'pdoc':
1681 if meth == 'pdoc':
1672 pmethod(info.obj, oname, formatter)
1682 pmethod(info.obj, oname, formatter)
1673 elif meth == 'pinfo':
1683 elif meth == 'pinfo':
1674 pmethod(
1684 pmethod(
1675 info.obj,
1685 info.obj,
1676 oname,
1686 oname,
1677 formatter,
1687 formatter,
1678 info,
1688 info,
1679 enable_html_pager=self.enable_html_pager,
1689 enable_html_pager=self.enable_html_pager,
1680 **kw,
1690 **kw,
1681 )
1691 )
1682 else:
1692 else:
1683 pmethod(info.obj, oname)
1693 pmethod(info.obj, oname)
1684 else:
1694 else:
1685 print('Object `%s` not found.' % oname)
1695 print('Object `%s` not found.' % oname)
1686 return 'not found' # so callers can take other action
1696 return 'not found' # so callers can take other action
1687
1697
1688 def object_inspect(self, oname, detail_level=0):
1698 def object_inspect(self, oname, detail_level=0):
1689 """Get object info about oname"""
1699 """Get object info about oname"""
1690 with self.builtin_trap:
1700 with self.builtin_trap:
1691 info = self._object_find(oname)
1701 info = self._object_find(oname)
1692 if info.found:
1702 if info.found:
1693 return self.inspector.info(info.obj, oname, info=info,
1703 return self.inspector.info(info.obj, oname, info=info,
1694 detail_level=detail_level
1704 detail_level=detail_level
1695 )
1705 )
1696 else:
1706 else:
1697 return oinspect.object_info(name=oname, found=False)
1707 return oinspect.object_info(name=oname, found=False)
1698
1708
1699 def object_inspect_text(self, oname, detail_level=0):
1709 def object_inspect_text(self, oname, detail_level=0):
1700 """Get object info as formatted text"""
1710 """Get object info as formatted text"""
1701 return self.object_inspect_mime(oname, detail_level)['text/plain']
1711 return self.object_inspect_mime(oname, detail_level)['text/plain']
1702
1712
1703 def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
1713 def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
1704 """Get object info as a mimebundle of formatted representations.
1714 """Get object info as a mimebundle of formatted representations.
1705
1715
1706 A mimebundle is a dictionary, keyed by mime-type.
1716 A mimebundle is a dictionary, keyed by mime-type.
1707 It must always have the key `'text/plain'`.
1717 It must always have the key `'text/plain'`.
1708 """
1718 """
1709 with self.builtin_trap:
1719 with self.builtin_trap:
1710 info = self._object_find(oname)
1720 info = self._object_find(oname)
1711 if info.found:
1721 if info.found:
1712 docformat = (
1722 docformat = (
1713 sphinxify(self.object_inspect(oname))
1723 sphinxify(self.object_inspect(oname))
1714 if self.sphinxify_docstring
1724 if self.sphinxify_docstring
1715 else None
1725 else None
1716 )
1726 )
1717 return self.inspector._get_info(
1727 return self.inspector._get_info(
1718 info.obj,
1728 info.obj,
1719 oname,
1729 oname,
1720 info=info,
1730 info=info,
1721 detail_level=detail_level,
1731 detail_level=detail_level,
1722 formatter=docformat,
1732 formatter=docformat,
1723 omit_sections=omit_sections,
1733 omit_sections=omit_sections,
1724 )
1734 )
1725 else:
1735 else:
1726 raise KeyError(oname)
1736 raise KeyError(oname)
1727
1737
1728 #-------------------------------------------------------------------------
1738 #-------------------------------------------------------------------------
1729 # Things related to history management
1739 # Things related to history management
1730 #-------------------------------------------------------------------------
1740 #-------------------------------------------------------------------------
1731
1741
1732 def init_history(self):
1742 def init_history(self):
1733 """Sets up the command history, and starts regular autosaves."""
1743 """Sets up the command history, and starts regular autosaves."""
1734 self.history_manager = HistoryManager(shell=self, parent=self)
1744 self.history_manager = HistoryManager(shell=self, parent=self)
1735 self.configurables.append(self.history_manager)
1745 self.configurables.append(self.history_manager)
1736
1746
1737 #-------------------------------------------------------------------------
1747 #-------------------------------------------------------------------------
1738 # Things related to exception handling and tracebacks (not debugging)
1748 # Things related to exception handling and tracebacks (not debugging)
1739 #-------------------------------------------------------------------------
1749 #-------------------------------------------------------------------------
1740
1750
1741 debugger_cls = InterruptiblePdb
1751 debugger_cls = InterruptiblePdb
1742
1752
1743 def init_traceback_handlers(self, custom_exceptions):
1753 def init_traceback_handlers(self, custom_exceptions):
1744 # Syntax error handler.
1754 # Syntax error handler.
1745 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1755 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1746
1756
1747 # The interactive one is initialized with an offset, meaning we always
1757 # The interactive one is initialized with an offset, meaning we always
1748 # want to remove the topmost item in the traceback, which is our own
1758 # want to remove the topmost item in the traceback, which is our own
1749 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1759 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1750 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1760 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1751 color_scheme='NoColor',
1761 color_scheme='NoColor',
1752 tb_offset = 1,
1762 tb_offset = 1,
1753 check_cache=check_linecache_ipython,
1763 check_cache=check_linecache_ipython,
1754 debugger_cls=self.debugger_cls, parent=self)
1764 debugger_cls=self.debugger_cls, parent=self)
1755
1765
1756 # The instance will store a pointer to the system-wide exception hook,
1766 # The instance will store a pointer to the system-wide exception hook,
1757 # so that runtime code (such as magics) can access it. This is because
1767 # so that runtime code (such as magics) can access it. This is because
1758 # during the read-eval loop, it may get temporarily overwritten.
1768 # during the read-eval loop, it may get temporarily overwritten.
1759 self.sys_excepthook = sys.excepthook
1769 self.sys_excepthook = sys.excepthook
1760
1770
1761 # and add any custom exception handlers the user may have specified
1771 # and add any custom exception handlers the user may have specified
1762 self.set_custom_exc(*custom_exceptions)
1772 self.set_custom_exc(*custom_exceptions)
1763
1773
1764 # Set the exception mode
1774 # Set the exception mode
1765 self.InteractiveTB.set_mode(mode=self.xmode)
1775 self.InteractiveTB.set_mode(mode=self.xmode)
1766
1776
1767 def set_custom_exc(self, exc_tuple, handler):
1777 def set_custom_exc(self, exc_tuple, handler):
1768 """set_custom_exc(exc_tuple, handler)
1778 """set_custom_exc(exc_tuple, handler)
1769
1779
1770 Set a custom exception handler, which will be called if any of the
1780 Set a custom exception handler, which will be called if any of the
1771 exceptions in exc_tuple occur in the mainloop (specifically, in the
1781 exceptions in exc_tuple occur in the mainloop (specifically, in the
1772 run_code() method).
1782 run_code() method).
1773
1783
1774 Parameters
1784 Parameters
1775 ----------
1785 ----------
1776 exc_tuple : tuple of exception classes
1786 exc_tuple : tuple of exception classes
1777 A *tuple* of exception classes, for which to call the defined
1787 A *tuple* of exception classes, for which to call the defined
1778 handler. It is very important that you use a tuple, and NOT A
1788 handler. It is very important that you use a tuple, and NOT A
1779 LIST here, because of the way Python's except statement works. If
1789 LIST here, because of the way Python's except statement works. If
1780 you only want to trap a single exception, use a singleton tuple::
1790 you only want to trap a single exception, use a singleton tuple::
1781
1791
1782 exc_tuple == (MyCustomException,)
1792 exc_tuple == (MyCustomException,)
1783
1793
1784 handler : callable
1794 handler : callable
1785 handler must have the following signature::
1795 handler must have the following signature::
1786
1796
1787 def my_handler(self, etype, value, tb, tb_offset=None):
1797 def my_handler(self, etype, value, tb, tb_offset=None):
1788 ...
1798 ...
1789 return structured_traceback
1799 return structured_traceback
1790
1800
1791 Your handler must return a structured traceback (a list of strings),
1801 Your handler must return a structured traceback (a list of strings),
1792 or None.
1802 or None.
1793
1803
1794 This will be made into an instance method (via types.MethodType)
1804 This will be made into an instance method (via types.MethodType)
1795 of IPython itself, and it will be called if any of the exceptions
1805 of IPython itself, and it will be called if any of the exceptions
1796 listed in the exc_tuple are caught. If the handler is None, an
1806 listed in the exc_tuple are caught. If the handler is None, an
1797 internal basic one is used, which just prints basic info.
1807 internal basic one is used, which just prints basic info.
1798
1808
1799 To protect IPython from crashes, if your handler ever raises an
1809 To protect IPython from crashes, if your handler ever raises an
1800 exception or returns an invalid result, it will be immediately
1810 exception or returns an invalid result, it will be immediately
1801 disabled.
1811 disabled.
1802
1812
1803 Notes
1813 Notes
1804 -----
1814 -----
1805 WARNING: by putting in your own exception handler into IPython's main
1815 WARNING: by putting in your own exception handler into IPython's main
1806 execution loop, you run a very good chance of nasty crashes. This
1816 execution loop, you run a very good chance of nasty crashes. This
1807 facility should only be used if you really know what you are doing.
1817 facility should only be used if you really know what you are doing.
1808 """
1818 """
1809
1819
1810 if not isinstance(exc_tuple, tuple):
1820 if not isinstance(exc_tuple, tuple):
1811 raise TypeError("The custom exceptions must be given as a tuple.")
1821 raise TypeError("The custom exceptions must be given as a tuple.")
1812
1822
1813 def dummy_handler(self, etype, value, tb, tb_offset=None):
1823 def dummy_handler(self, etype, value, tb, tb_offset=None):
1814 print('*** Simple custom exception handler ***')
1824 print('*** Simple custom exception handler ***')
1815 print('Exception type :', etype)
1825 print('Exception type :', etype)
1816 print('Exception value:', value)
1826 print('Exception value:', value)
1817 print('Traceback :', tb)
1827 print('Traceback :', tb)
1818
1828
1819 def validate_stb(stb):
1829 def validate_stb(stb):
1820 """validate structured traceback return type
1830 """validate structured traceback return type
1821
1831
1822 return type of CustomTB *should* be a list of strings, but allow
1832 return type of CustomTB *should* be a list of strings, but allow
1823 single strings or None, which are harmless.
1833 single strings or None, which are harmless.
1824
1834
1825 This function will *always* return a list of strings,
1835 This function will *always* return a list of strings,
1826 and will raise a TypeError if stb is inappropriate.
1836 and will raise a TypeError if stb is inappropriate.
1827 """
1837 """
1828 msg = "CustomTB must return list of strings, not %r" % stb
1838 msg = "CustomTB must return list of strings, not %r" % stb
1829 if stb is None:
1839 if stb is None:
1830 return []
1840 return []
1831 elif isinstance(stb, str):
1841 elif isinstance(stb, str):
1832 return [stb]
1842 return [stb]
1833 elif not isinstance(stb, list):
1843 elif not isinstance(stb, list):
1834 raise TypeError(msg)
1844 raise TypeError(msg)
1835 # it's a list
1845 # it's a list
1836 for line in stb:
1846 for line in stb:
1837 # check every element
1847 # check every element
1838 if not isinstance(line, str):
1848 if not isinstance(line, str):
1839 raise TypeError(msg)
1849 raise TypeError(msg)
1840 return stb
1850 return stb
1841
1851
1842 if handler is None:
1852 if handler is None:
1843 wrapped = dummy_handler
1853 wrapped = dummy_handler
1844 else:
1854 else:
1845 def wrapped(self,etype,value,tb,tb_offset=None):
1855 def wrapped(self,etype,value,tb,tb_offset=None):
1846 """wrap CustomTB handler, to protect IPython from user code
1856 """wrap CustomTB handler, to protect IPython from user code
1847
1857
1848 This makes it harder (but not impossible) for custom exception
1858 This makes it harder (but not impossible) for custom exception
1849 handlers to crash IPython.
1859 handlers to crash IPython.
1850 """
1860 """
1851 try:
1861 try:
1852 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1862 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1853 return validate_stb(stb)
1863 return validate_stb(stb)
1854 except:
1864 except:
1855 # clear custom handler immediately
1865 # clear custom handler immediately
1856 self.set_custom_exc((), None)
1866 self.set_custom_exc((), None)
1857 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1867 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1858 # show the exception in handler first
1868 # show the exception in handler first
1859 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1869 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1860 print(self.InteractiveTB.stb2text(stb))
1870 print(self.InteractiveTB.stb2text(stb))
1861 print("The original exception:")
1871 print("The original exception:")
1862 stb = self.InteractiveTB.structured_traceback(
1872 stb = self.InteractiveTB.structured_traceback(
1863 (etype,value,tb), tb_offset=tb_offset
1873 (etype,value,tb), tb_offset=tb_offset
1864 )
1874 )
1865 return stb
1875 return stb
1866
1876
1867 self.CustomTB = types.MethodType(wrapped,self)
1877 self.CustomTB = types.MethodType(wrapped,self)
1868 self.custom_exceptions = exc_tuple
1878 self.custom_exceptions = exc_tuple
1869
1879
1870 def excepthook(self, etype, value, tb):
1880 def excepthook(self, etype, value, tb):
1871 """One more defense for GUI apps that call sys.excepthook.
1881 """One more defense for GUI apps that call sys.excepthook.
1872
1882
1873 GUI frameworks like wxPython trap exceptions and call
1883 GUI frameworks like wxPython trap exceptions and call
1874 sys.excepthook themselves. I guess this is a feature that
1884 sys.excepthook themselves. I guess this is a feature that
1875 enables them to keep running after exceptions that would
1885 enables them to keep running after exceptions that would
1876 otherwise kill their mainloop. This is a bother for IPython
1886 otherwise kill their mainloop. This is a bother for IPython
1877 which expects to catch all of the program exceptions with a try:
1887 which expects to catch all of the program exceptions with a try:
1878 except: statement.
1888 except: statement.
1879
1889
1880 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1890 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1881 any app directly invokes sys.excepthook, it will look to the user like
1891 any app directly invokes sys.excepthook, it will look to the user like
1882 IPython crashed. In order to work around this, we can disable the
1892 IPython crashed. In order to work around this, we can disable the
1883 CrashHandler and replace it with this excepthook instead, which prints a
1893 CrashHandler and replace it with this excepthook instead, which prints a
1884 regular traceback using our InteractiveTB. In this fashion, apps which
1894 regular traceback using our InteractiveTB. In this fashion, apps which
1885 call sys.excepthook will generate a regular-looking exception from
1895 call sys.excepthook will generate a regular-looking exception from
1886 IPython, and the CrashHandler will only be triggered by real IPython
1896 IPython, and the CrashHandler will only be triggered by real IPython
1887 crashes.
1897 crashes.
1888
1898
1889 This hook should be used sparingly, only in places which are not likely
1899 This hook should be used sparingly, only in places which are not likely
1890 to be true IPython errors.
1900 to be true IPython errors.
1891 """
1901 """
1892 self.showtraceback((etype, value, tb), tb_offset=0)
1902 self.showtraceback((etype, value, tb), tb_offset=0)
1893
1903
1894 def _get_exc_info(self, exc_tuple=None):
1904 def _get_exc_info(self, exc_tuple=None):
1895 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1905 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1896
1906
1897 Ensures sys.last_type,value,traceback hold the exc_info we found,
1907 Ensures sys.last_type,value,traceback hold the exc_info we found,
1898 from whichever source.
1908 from whichever source.
1899
1909
1900 raises ValueError if none of these contain any information
1910 raises ValueError if none of these contain any information
1901 """
1911 """
1902 if exc_tuple is None:
1912 if exc_tuple is None:
1903 etype, value, tb = sys.exc_info()
1913 etype, value, tb = sys.exc_info()
1904 else:
1914 else:
1905 etype, value, tb = exc_tuple
1915 etype, value, tb = exc_tuple
1906
1916
1907 if etype is None:
1917 if etype is None:
1908 if hasattr(sys, 'last_type'):
1918 if hasattr(sys, 'last_type'):
1909 etype, value, tb = sys.last_type, sys.last_value, \
1919 etype, value, tb = sys.last_type, sys.last_value, \
1910 sys.last_traceback
1920 sys.last_traceback
1911
1921
1912 if etype is None:
1922 if etype is None:
1913 raise ValueError("No exception to find")
1923 raise ValueError("No exception to find")
1914
1924
1915 # Now store the exception info in sys.last_type etc.
1925 # Now store the exception info in sys.last_type etc.
1916 # WARNING: these variables are somewhat deprecated and not
1926 # WARNING: these variables are somewhat deprecated and not
1917 # necessarily safe to use in a threaded environment, but tools
1927 # necessarily safe to use in a threaded environment, but tools
1918 # like pdb depend on their existence, so let's set them. If we
1928 # like pdb depend on their existence, so let's set them. If we
1919 # find problems in the field, we'll need to revisit their use.
1929 # find problems in the field, we'll need to revisit their use.
1920 sys.last_type = etype
1930 sys.last_type = etype
1921 sys.last_value = value
1931 sys.last_value = value
1922 sys.last_traceback = tb
1932 sys.last_traceback = tb
1923
1933
1924 return etype, value, tb
1934 return etype, value, tb
1925
1935
1926 def show_usage_error(self, exc):
1936 def show_usage_error(self, exc):
1927 """Show a short message for UsageErrors
1937 """Show a short message for UsageErrors
1928
1938
1929 These are special exceptions that shouldn't show a traceback.
1939 These are special exceptions that shouldn't show a traceback.
1930 """
1940 """
1931 print("UsageError: %s" % exc, file=sys.stderr)
1941 print("UsageError: %s" % exc, file=sys.stderr)
1932
1942
1933 def get_exception_only(self, exc_tuple=None):
1943 def get_exception_only(self, exc_tuple=None):
1934 """
1944 """
1935 Return as a string (ending with a newline) the exception that
1945 Return as a string (ending with a newline) the exception that
1936 just occurred, without any traceback.
1946 just occurred, without any traceback.
1937 """
1947 """
1938 etype, value, tb = self._get_exc_info(exc_tuple)
1948 etype, value, tb = self._get_exc_info(exc_tuple)
1939 msg = traceback.format_exception_only(etype, value)
1949 msg = traceback.format_exception_only(etype, value)
1940 return ''.join(msg)
1950 return ''.join(msg)
1941
1951
1942 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1952 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1943 exception_only=False, running_compiled_code=False):
1953 exception_only=False, running_compiled_code=False):
1944 """Display the exception that just occurred.
1954 """Display the exception that just occurred.
1945
1955
1946 If nothing is known about the exception, this is the method which
1956 If nothing is known about the exception, this is the method which
1947 should be used throughout the code for presenting user tracebacks,
1957 should be used throughout the code for presenting user tracebacks,
1948 rather than directly invoking the InteractiveTB object.
1958 rather than directly invoking the InteractiveTB object.
1949
1959
1950 A specific showsyntaxerror() also exists, but this method can take
1960 A specific showsyntaxerror() also exists, but this method can take
1951 care of calling it if needed, so unless you are explicitly catching a
1961 care of calling it if needed, so unless you are explicitly catching a
1952 SyntaxError exception, don't try to analyze the stack manually and
1962 SyntaxError exception, don't try to analyze the stack manually and
1953 simply call this method."""
1963 simply call this method."""
1954
1964
1955 try:
1965 try:
1956 try:
1966 try:
1957 etype, value, tb = self._get_exc_info(exc_tuple)
1967 etype, value, tb = self._get_exc_info(exc_tuple)
1958 except ValueError:
1968 except ValueError:
1959 print('No traceback available to show.', file=sys.stderr)
1969 print('No traceback available to show.', file=sys.stderr)
1960 return
1970 return
1961
1971
1962 if issubclass(etype, SyntaxError):
1972 if issubclass(etype, SyntaxError):
1963 # Though this won't be called by syntax errors in the input
1973 # Though this won't be called by syntax errors in the input
1964 # line, there may be SyntaxError cases with imported code.
1974 # line, there may be SyntaxError cases with imported code.
1965 self.showsyntaxerror(filename, running_compiled_code)
1975 self.showsyntaxerror(filename, running_compiled_code)
1966 elif etype is UsageError:
1976 elif etype is UsageError:
1967 self.show_usage_error(value)
1977 self.show_usage_error(value)
1968 else:
1978 else:
1969 if exception_only:
1979 if exception_only:
1970 stb = ['An exception has occurred, use %tb to see '
1980 stb = ['An exception has occurred, use %tb to see '
1971 'the full traceback.\n']
1981 'the full traceback.\n']
1972 stb.extend(self.InteractiveTB.get_exception_only(etype,
1982 stb.extend(self.InteractiveTB.get_exception_only(etype,
1973 value))
1983 value))
1974 else:
1984 else:
1975 try:
1985 try:
1976 # Exception classes can customise their traceback - we
1986 # Exception classes can customise their traceback - we
1977 # use this in IPython.parallel for exceptions occurring
1987 # use this in IPython.parallel for exceptions occurring
1978 # in the engines. This should return a list of strings.
1988 # in the engines. This should return a list of strings.
1979 if hasattr(value, "_render_traceback_"):
1989 if hasattr(value, "_render_traceback_"):
1980 stb = value._render_traceback_()
1990 stb = value._render_traceback_()
1981 else:
1991 else:
1982 stb = self.InteractiveTB.structured_traceback(
1992 stb = self.InteractiveTB.structured_traceback(
1983 etype, value, tb, tb_offset=tb_offset
1993 etype, value, tb, tb_offset=tb_offset
1984 )
1994 )
1985
1995
1986 except Exception:
1996 except Exception:
1987 print(
1997 print(
1988 "Unexpected exception formatting exception. Falling back to standard exception"
1998 "Unexpected exception formatting exception. Falling back to standard exception"
1989 )
1999 )
1990 traceback.print_exc()
2000 traceback.print_exc()
1991 return None
2001 return None
1992
2002
1993 self._showtraceback(etype, value, stb)
2003 self._showtraceback(etype, value, stb)
1994 if self.call_pdb:
2004 if self.call_pdb:
1995 # drop into debugger
2005 # drop into debugger
1996 self.debugger(force=True)
2006 self.debugger(force=True)
1997 return
2007 return
1998
2008
1999 # Actually show the traceback
2009 # Actually show the traceback
2000 self._showtraceback(etype, value, stb)
2010 self._showtraceback(etype, value, stb)
2001
2011
2002 except KeyboardInterrupt:
2012 except KeyboardInterrupt:
2003 print('\n' + self.get_exception_only(), file=sys.stderr)
2013 print('\n' + self.get_exception_only(), file=sys.stderr)
2004
2014
2005 def _showtraceback(self, etype, evalue, stb: str):
2015 def _showtraceback(self, etype, evalue, stb: str):
2006 """Actually show a traceback.
2016 """Actually show a traceback.
2007
2017
2008 Subclasses may override this method to put the traceback on a different
2018 Subclasses may override this method to put the traceback on a different
2009 place, like a side channel.
2019 place, like a side channel.
2010 """
2020 """
2011 val = self.InteractiveTB.stb2text(stb)
2021 val = self.InteractiveTB.stb2text(stb)
2012 try:
2022 try:
2013 print(val)
2023 print(val)
2014 except UnicodeEncodeError:
2024 except UnicodeEncodeError:
2015 print(val.encode("utf-8", "backslashreplace").decode())
2025 print(val.encode("utf-8", "backslashreplace").decode())
2016
2026
2017 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2027 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2018 """Display the syntax error that just occurred.
2028 """Display the syntax error that just occurred.
2019
2029
2020 This doesn't display a stack trace because there isn't one.
2030 This doesn't display a stack trace because there isn't one.
2021
2031
2022 If a filename is given, it is stuffed in the exception instead
2032 If a filename is given, it is stuffed in the exception instead
2023 of what was there before (because Python's parser always uses
2033 of what was there before (because Python's parser always uses
2024 "<string>" when reading from a string).
2034 "<string>" when reading from a string).
2025
2035
2026 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2036 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2027 longer stack trace will be displayed.
2037 longer stack trace will be displayed.
2028 """
2038 """
2029 etype, value, last_traceback = self._get_exc_info()
2039 etype, value, last_traceback = self._get_exc_info()
2030
2040
2031 if filename and issubclass(etype, SyntaxError):
2041 if filename and issubclass(etype, SyntaxError):
2032 try:
2042 try:
2033 value.filename = filename
2043 value.filename = filename
2034 except:
2044 except:
2035 # Not the format we expect; leave it alone
2045 # Not the format we expect; leave it alone
2036 pass
2046 pass
2037
2047
2038 # If the error occurred when executing compiled code, we should provide full stacktrace.
2048 # If the error occurred when executing compiled code, we should provide full stacktrace.
2039 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2049 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2040 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2050 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2041 self._showtraceback(etype, value, stb)
2051 self._showtraceback(etype, value, stb)
2042
2052
2043 # This is overridden in TerminalInteractiveShell to show a message about
2053 # This is overridden in TerminalInteractiveShell to show a message about
2044 # the %paste magic.
2054 # the %paste magic.
2045 def showindentationerror(self):
2055 def showindentationerror(self):
2046 """Called by _run_cell when there's an IndentationError in code entered
2056 """Called by _run_cell when there's an IndentationError in code entered
2047 at the prompt.
2057 at the prompt.
2048
2058
2049 This is overridden in TerminalInteractiveShell to show a message about
2059 This is overridden in TerminalInteractiveShell to show a message about
2050 the %paste magic."""
2060 the %paste magic."""
2051 self.showsyntaxerror()
2061 self.showsyntaxerror()
2052
2062
2053 @skip_doctest
2063 @skip_doctest
2054 def set_next_input(self, s, replace=False):
2064 def set_next_input(self, s, replace=False):
2055 """ Sets the 'default' input string for the next command line.
2065 """ Sets the 'default' input string for the next command line.
2056
2066
2057 Example::
2067 Example::
2058
2068
2059 In [1]: _ip.set_next_input("Hello Word")
2069 In [1]: _ip.set_next_input("Hello Word")
2060 In [2]: Hello Word_ # cursor is here
2070 In [2]: Hello Word_ # cursor is here
2061 """
2071 """
2062 self.rl_next_input = s
2072 self.rl_next_input = s
2063
2073
2064 def _indent_current_str(self):
2074 def _indent_current_str(self):
2065 """return the current level of indentation as a string"""
2075 """return the current level of indentation as a string"""
2066 return self.input_splitter.get_indent_spaces() * ' '
2076 return self.input_splitter.get_indent_spaces() * ' '
2067
2077
2068 #-------------------------------------------------------------------------
2078 #-------------------------------------------------------------------------
2069 # Things related to text completion
2079 # Things related to text completion
2070 #-------------------------------------------------------------------------
2080 #-------------------------------------------------------------------------
2071
2081
2072 def init_completer(self):
2082 def init_completer(self):
2073 """Initialize the completion machinery.
2083 """Initialize the completion machinery.
2074
2084
2075 This creates completion machinery that can be used by client code,
2085 This creates completion machinery that can be used by client code,
2076 either interactively in-process (typically triggered by the readline
2086 either interactively in-process (typically triggered by the readline
2077 library), programmatically (such as in test suites) or out-of-process
2087 library), programmatically (such as in test suites) or out-of-process
2078 (typically over the network by remote frontends).
2088 (typically over the network by remote frontends).
2079 """
2089 """
2080 from IPython.core.completer import IPCompleter
2090 from IPython.core.completer import IPCompleter
2081 from IPython.core.completerlib import (
2091 from IPython.core.completerlib import (
2082 cd_completer,
2092 cd_completer,
2083 magic_run_completer,
2093 magic_run_completer,
2084 module_completer,
2094 module_completer,
2085 reset_completer,
2095 reset_completer,
2086 )
2096 )
2087
2097
2088 self.Completer = IPCompleter(shell=self,
2098 self.Completer = IPCompleter(shell=self,
2089 namespace=self.user_ns,
2099 namespace=self.user_ns,
2090 global_namespace=self.user_global_ns,
2100 global_namespace=self.user_global_ns,
2091 parent=self,
2101 parent=self,
2092 )
2102 )
2093 self.configurables.append(self.Completer)
2103 self.configurables.append(self.Completer)
2094
2104
2095 # Add custom completers to the basic ones built into IPCompleter
2105 # Add custom completers to the basic ones built into IPCompleter
2096 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2106 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2097 self.strdispatchers['complete_command'] = sdisp
2107 self.strdispatchers['complete_command'] = sdisp
2098 self.Completer.custom_completers = sdisp
2108 self.Completer.custom_completers = sdisp
2099
2109
2100 self.set_hook('complete_command', module_completer, str_key = 'import')
2110 self.set_hook('complete_command', module_completer, str_key = 'import')
2101 self.set_hook('complete_command', module_completer, str_key = 'from')
2111 self.set_hook('complete_command', module_completer, str_key = 'from')
2102 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2112 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2103 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2113 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2104 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2114 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2105 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2115 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2106
2116
2107 @skip_doctest
2117 @skip_doctest
2108 def complete(self, text, line=None, cursor_pos=None):
2118 def complete(self, text, line=None, cursor_pos=None):
2109 """Return the completed text and a list of completions.
2119 """Return the completed text and a list of completions.
2110
2120
2111 Parameters
2121 Parameters
2112 ----------
2122 ----------
2113 text : string
2123 text : string
2114 A string of text to be completed on. It can be given as empty and
2124 A string of text to be completed on. It can be given as empty and
2115 instead a line/position pair are given. In this case, the
2125 instead a line/position pair are given. In this case, the
2116 completer itself will split the line like readline does.
2126 completer itself will split the line like readline does.
2117 line : string, optional
2127 line : string, optional
2118 The complete line that text is part of.
2128 The complete line that text is part of.
2119 cursor_pos : int, optional
2129 cursor_pos : int, optional
2120 The position of the cursor on the input line.
2130 The position of the cursor on the input line.
2121
2131
2122 Returns
2132 Returns
2123 -------
2133 -------
2124 text : string
2134 text : string
2125 The actual text that was completed.
2135 The actual text that was completed.
2126 matches : list
2136 matches : list
2127 A sorted list with all possible completions.
2137 A sorted list with all possible completions.
2128
2138
2129 Notes
2139 Notes
2130 -----
2140 -----
2131 The optional arguments allow the completion to take more context into
2141 The optional arguments allow the completion to take more context into
2132 account, and are part of the low-level completion API.
2142 account, and are part of the low-level completion API.
2133
2143
2134 This is a wrapper around the completion mechanism, similar to what
2144 This is a wrapper around the completion mechanism, similar to what
2135 readline does at the command line when the TAB key is hit. By
2145 readline does at the command line when the TAB key is hit. By
2136 exposing it as a method, it can be used by other non-readline
2146 exposing it as a method, it can be used by other non-readline
2137 environments (such as GUIs) for text completion.
2147 environments (such as GUIs) for text completion.
2138
2148
2139 Examples
2149 Examples
2140 --------
2150 --------
2141 In [1]: x = 'hello'
2151 In [1]: x = 'hello'
2142
2152
2143 In [2]: _ip.complete('x.l')
2153 In [2]: _ip.complete('x.l')
2144 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2154 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2145 """
2155 """
2146
2156
2147 # Inject names into __builtin__ so we can complete on the added names.
2157 # Inject names into __builtin__ so we can complete on the added names.
2148 with self.builtin_trap:
2158 with self.builtin_trap:
2149 return self.Completer.complete(text, line, cursor_pos)
2159 return self.Completer.complete(text, line, cursor_pos)
2150
2160
2151 def set_custom_completer(self, completer, pos=0) -> None:
2161 def set_custom_completer(self, completer, pos=0) -> None:
2152 """Adds a new custom completer function.
2162 """Adds a new custom completer function.
2153
2163
2154 The position argument (defaults to 0) is the index in the completers
2164 The position argument (defaults to 0) is the index in the completers
2155 list where you want the completer to be inserted.
2165 list where you want the completer to be inserted.
2156
2166
2157 `completer` should have the following signature::
2167 `completer` should have the following signature::
2158
2168
2159 def completion(self: Completer, text: string) -> List[str]:
2169 def completion(self: Completer, text: string) -> List[str]:
2160 raise NotImplementedError
2170 raise NotImplementedError
2161
2171
2162 It will be bound to the current Completer instance and pass some text
2172 It will be bound to the current Completer instance and pass some text
2163 and return a list with current completions to suggest to the user.
2173 and return a list with current completions to suggest to the user.
2164 """
2174 """
2165
2175
2166 newcomp = types.MethodType(completer, self.Completer)
2176 newcomp = types.MethodType(completer, self.Completer)
2167 self.Completer.custom_matchers.insert(pos,newcomp)
2177 self.Completer.custom_matchers.insert(pos,newcomp)
2168
2178
2169 def set_completer_frame(self, frame=None):
2179 def set_completer_frame(self, frame=None):
2170 """Set the frame of the completer."""
2180 """Set the frame of the completer."""
2171 if frame:
2181 if frame:
2172 self.Completer.namespace = frame.f_locals
2182 self.Completer.namespace = frame.f_locals
2173 self.Completer.global_namespace = frame.f_globals
2183 self.Completer.global_namespace = frame.f_globals
2174 else:
2184 else:
2175 self.Completer.namespace = self.user_ns
2185 self.Completer.namespace = self.user_ns
2176 self.Completer.global_namespace = self.user_global_ns
2186 self.Completer.global_namespace = self.user_global_ns
2177
2187
2178 #-------------------------------------------------------------------------
2188 #-------------------------------------------------------------------------
2179 # Things related to magics
2189 # Things related to magics
2180 #-------------------------------------------------------------------------
2190 #-------------------------------------------------------------------------
2181
2191
2182 def init_magics(self):
2192 def init_magics(self):
2183 from IPython.core import magics as m
2193 from IPython.core import magics as m
2184 self.magics_manager = magic.MagicsManager(shell=self,
2194 self.magics_manager = magic.MagicsManager(shell=self,
2185 parent=self,
2195 parent=self,
2186 user_magics=m.UserMagics(self))
2196 user_magics=m.UserMagics(self))
2187 self.configurables.append(self.magics_manager)
2197 self.configurables.append(self.magics_manager)
2188
2198
2189 # Expose as public API from the magics manager
2199 # Expose as public API from the magics manager
2190 self.register_magics = self.magics_manager.register
2200 self.register_magics = self.magics_manager.register
2191
2201
2192 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2202 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2193 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2203 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2194 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2204 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2195 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2205 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2196 m.PylabMagics, m.ScriptMagics,
2206 m.PylabMagics, m.ScriptMagics,
2197 )
2207 )
2198 self.register_magics(m.AsyncMagics)
2208 self.register_magics(m.AsyncMagics)
2199
2209
2200 # Register Magic Aliases
2210 # Register Magic Aliases
2201 mman = self.magics_manager
2211 mman = self.magics_manager
2202 # FIXME: magic aliases should be defined by the Magics classes
2212 # FIXME: magic aliases should be defined by the Magics classes
2203 # or in MagicsManager, not here
2213 # or in MagicsManager, not here
2204 mman.register_alias('ed', 'edit')
2214 mman.register_alias('ed', 'edit')
2205 mman.register_alias('hist', 'history')
2215 mman.register_alias('hist', 'history')
2206 mman.register_alias('rep', 'recall')
2216 mman.register_alias('rep', 'recall')
2207 mman.register_alias('SVG', 'svg', 'cell')
2217 mman.register_alias('SVG', 'svg', 'cell')
2208 mman.register_alias('HTML', 'html', 'cell')
2218 mman.register_alias('HTML', 'html', 'cell')
2209 mman.register_alias('file', 'writefile', 'cell')
2219 mman.register_alias('file', 'writefile', 'cell')
2210
2220
2211 # FIXME: Move the color initialization to the DisplayHook, which
2221 # FIXME: Move the color initialization to the DisplayHook, which
2212 # should be split into a prompt manager and displayhook. We probably
2222 # should be split into a prompt manager and displayhook. We probably
2213 # even need a centralize colors management object.
2223 # even need a centralize colors management object.
2214 self.run_line_magic('colors', self.colors)
2224 self.run_line_magic('colors', self.colors)
2215
2225
2216 # Defined here so that it's included in the documentation
2226 # Defined here so that it's included in the documentation
2217 @functools.wraps(magic.MagicsManager.register_function)
2227 @functools.wraps(magic.MagicsManager.register_function)
2218 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2228 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2219 self.magics_manager.register_function(
2229 self.magics_manager.register_function(
2220 func, magic_kind=magic_kind, magic_name=magic_name
2230 func, magic_kind=magic_kind, magic_name=magic_name
2221 )
2231 )
2222
2232
2223 def _find_with_lazy_load(self, /, type_, magic_name: str):
2233 def _find_with_lazy_load(self, /, type_, magic_name: str):
2224 """
2234 """
2225 Try to find a magic potentially lazy-loading it.
2235 Try to find a magic potentially lazy-loading it.
2226
2236
2227 Parameters
2237 Parameters
2228 ----------
2238 ----------
2229
2239
2230 type_: "line"|"cell"
2240 type_: "line"|"cell"
2231 the type of magics we are trying to find/lazy load.
2241 the type of magics we are trying to find/lazy load.
2232 magic_name: str
2242 magic_name: str
2233 The name of the magic we are trying to find/lazy load
2243 The name of the magic we are trying to find/lazy load
2234
2244
2235
2245
2236 Note that this may have any side effects
2246 Note that this may have any side effects
2237 """
2247 """
2238 finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_]
2248 finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_]
2239 fn = finder(magic_name)
2249 fn = finder(magic_name)
2240 if fn is not None:
2250 if fn is not None:
2241 return fn
2251 return fn
2242 lazy = self.magics_manager.lazy_magics.get(magic_name)
2252 lazy = self.magics_manager.lazy_magics.get(magic_name)
2243 if lazy is None:
2253 if lazy is None:
2244 return None
2254 return None
2245
2255
2246 self.run_line_magic("load_ext", lazy)
2256 self.run_line_magic("load_ext", lazy)
2247 res = finder(magic_name)
2257 res = finder(magic_name)
2248 return res
2258 return res
2249
2259
2250 def run_line_magic(self, magic_name: str, line, _stack_depth=1):
2260 def run_line_magic(self, magic_name: str, line, _stack_depth=1):
2251 """Execute the given line magic.
2261 """Execute the given line magic.
2252
2262
2253 Parameters
2263 Parameters
2254 ----------
2264 ----------
2255 magic_name : str
2265 magic_name : str
2256 Name of the desired magic function, without '%' prefix.
2266 Name of the desired magic function, without '%' prefix.
2257 line : str
2267 line : str
2258 The rest of the input line as a single string.
2268 The rest of the input line as a single string.
2259 _stack_depth : int
2269 _stack_depth : int
2260 If run_line_magic() is called from magic() then _stack_depth=2.
2270 If run_line_magic() is called from magic() then _stack_depth=2.
2261 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2271 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2262 """
2272 """
2263 fn = self._find_with_lazy_load("line", magic_name)
2273 fn = self._find_with_lazy_load("line", magic_name)
2264 if fn is None:
2274 if fn is None:
2265 lazy = self.magics_manager.lazy_magics.get(magic_name)
2275 lazy = self.magics_manager.lazy_magics.get(magic_name)
2266 if lazy:
2276 if lazy:
2267 self.run_line_magic("load_ext", lazy)
2277 self.run_line_magic("load_ext", lazy)
2268 fn = self.find_line_magic(magic_name)
2278 fn = self.find_line_magic(magic_name)
2269 if fn is None:
2279 if fn is None:
2270 cm = self.find_cell_magic(magic_name)
2280 cm = self.find_cell_magic(magic_name)
2271 etpl = "Line magic function `%%%s` not found%s."
2281 etpl = "Line magic function `%%%s` not found%s."
2272 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2282 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2273 'did you mean that instead?)' % magic_name )
2283 'did you mean that instead?)' % magic_name )
2274 raise UsageError(etpl % (magic_name, extra))
2284 raise UsageError(etpl % (magic_name, extra))
2275 else:
2285 else:
2276 # Note: this is the distance in the stack to the user's frame.
2286 # Note: this is the distance in the stack to the user's frame.
2277 # This will need to be updated if the internal calling logic gets
2287 # This will need to be updated if the internal calling logic gets
2278 # refactored, or else we'll be expanding the wrong variables.
2288 # refactored, or else we'll be expanding the wrong variables.
2279
2289
2280 # Determine stack_depth depending on where run_line_magic() has been called
2290 # Determine stack_depth depending on where run_line_magic() has been called
2281 stack_depth = _stack_depth
2291 stack_depth = _stack_depth
2282 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2292 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2283 # magic has opted out of var_expand
2293 # magic has opted out of var_expand
2284 magic_arg_s = line
2294 magic_arg_s = line
2285 else:
2295 else:
2286 magic_arg_s = self.var_expand(line, stack_depth)
2296 magic_arg_s = self.var_expand(line, stack_depth)
2287 # Put magic args in a list so we can call with f(*a) syntax
2297 # Put magic args in a list so we can call with f(*a) syntax
2288 args = [magic_arg_s]
2298 args = [magic_arg_s]
2289 kwargs = {}
2299 kwargs = {}
2290 # Grab local namespace if we need it:
2300 # Grab local namespace if we need it:
2291 if getattr(fn, "needs_local_scope", False):
2301 if getattr(fn, "needs_local_scope", False):
2292 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2302 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2293 with self.builtin_trap:
2303 with self.builtin_trap:
2294 result = fn(*args, **kwargs)
2304 result = fn(*args, **kwargs)
2295 return result
2305 return result
2296
2306
2297 def get_local_scope(self, stack_depth):
2307 def get_local_scope(self, stack_depth):
2298 """Get local scope at given stack depth.
2308 """Get local scope at given stack depth.
2299
2309
2300 Parameters
2310 Parameters
2301 ----------
2311 ----------
2302 stack_depth : int
2312 stack_depth : int
2303 Depth relative to calling frame
2313 Depth relative to calling frame
2304 """
2314 """
2305 return sys._getframe(stack_depth + 1).f_locals
2315 return sys._getframe(stack_depth + 1).f_locals
2306
2316
2307 def run_cell_magic(self, magic_name, line, cell):
2317 def run_cell_magic(self, magic_name, line, cell):
2308 """Execute the given cell magic.
2318 """Execute the given cell magic.
2309
2319
2310 Parameters
2320 Parameters
2311 ----------
2321 ----------
2312 magic_name : str
2322 magic_name : str
2313 Name of the desired magic function, without '%' prefix.
2323 Name of the desired magic function, without '%' prefix.
2314 line : str
2324 line : str
2315 The rest of the first input line as a single string.
2325 The rest of the first input line as a single string.
2316 cell : str
2326 cell : str
2317 The body of the cell as a (possibly multiline) string.
2327 The body of the cell as a (possibly multiline) string.
2318 """
2328 """
2319 fn = self._find_with_lazy_load("cell", magic_name)
2329 fn = self._find_with_lazy_load("cell", magic_name)
2320 if fn is None:
2330 if fn is None:
2321 lm = self.find_line_magic(magic_name)
2331 lm = self.find_line_magic(magic_name)
2322 etpl = "Cell magic `%%{0}` not found{1}."
2332 etpl = "Cell magic `%%{0}` not found{1}."
2323 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2333 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2324 'did you mean that instead?)'.format(magic_name))
2334 'did you mean that instead?)'.format(magic_name))
2325 raise UsageError(etpl.format(magic_name, extra))
2335 raise UsageError(etpl.format(magic_name, extra))
2326 elif cell == '':
2336 elif cell == '':
2327 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2337 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2328 if self.find_line_magic(magic_name) is not None:
2338 if self.find_line_magic(magic_name) is not None:
2329 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2339 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2330 raise UsageError(message)
2340 raise UsageError(message)
2331 else:
2341 else:
2332 # Note: this is the distance in the stack to the user's frame.
2342 # Note: this is the distance in the stack to the user's frame.
2333 # This will need to be updated if the internal calling logic gets
2343 # This will need to be updated if the internal calling logic gets
2334 # refactored, or else we'll be expanding the wrong variables.
2344 # refactored, or else we'll be expanding the wrong variables.
2335 stack_depth = 2
2345 stack_depth = 2
2336 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2346 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2337 # magic has opted out of var_expand
2347 # magic has opted out of var_expand
2338 magic_arg_s = line
2348 magic_arg_s = line
2339 else:
2349 else:
2340 magic_arg_s = self.var_expand(line, stack_depth)
2350 magic_arg_s = self.var_expand(line, stack_depth)
2341 kwargs = {}
2351 kwargs = {}
2342 if getattr(fn, "needs_local_scope", False):
2352 if getattr(fn, "needs_local_scope", False):
2343 kwargs['local_ns'] = self.user_ns
2353 kwargs['local_ns'] = self.user_ns
2344
2354
2345 with self.builtin_trap:
2355 with self.builtin_trap:
2346 args = (magic_arg_s, cell)
2356 args = (magic_arg_s, cell)
2347 result = fn(*args, **kwargs)
2357 result = fn(*args, **kwargs)
2348 return result
2358 return result
2349
2359
2350 def find_line_magic(self, magic_name):
2360 def find_line_magic(self, magic_name):
2351 """Find and return a line magic by name.
2361 """Find and return a line magic by name.
2352
2362
2353 Returns None if the magic isn't found."""
2363 Returns None if the magic isn't found."""
2354 return self.magics_manager.magics['line'].get(magic_name)
2364 return self.magics_manager.magics['line'].get(magic_name)
2355
2365
2356 def find_cell_magic(self, magic_name):
2366 def find_cell_magic(self, magic_name):
2357 """Find and return a cell magic by name.
2367 """Find and return a cell magic by name.
2358
2368
2359 Returns None if the magic isn't found."""
2369 Returns None if the magic isn't found."""
2360 return self.magics_manager.magics['cell'].get(magic_name)
2370 return self.magics_manager.magics['cell'].get(magic_name)
2361
2371
2362 def find_magic(self, magic_name, magic_kind='line'):
2372 def find_magic(self, magic_name, magic_kind='line'):
2363 """Find and return a magic of the given type by name.
2373 """Find and return a magic of the given type by name.
2364
2374
2365 Returns None if the magic isn't found."""
2375 Returns None if the magic isn't found."""
2366 return self.magics_manager.magics[magic_kind].get(magic_name)
2376 return self.magics_manager.magics[magic_kind].get(magic_name)
2367
2377
2368 def magic(self, arg_s):
2378 def magic(self, arg_s):
2369 """
2379 """
2370 DEPRECATED
2380 DEPRECATED
2371
2381
2372 Deprecated since IPython 0.13 (warning added in
2382 Deprecated since IPython 0.13 (warning added in
2373 8.1), use run_line_magic(magic_name, parameter_s).
2383 8.1), use run_line_magic(magic_name, parameter_s).
2374
2384
2375 Call a magic function by name.
2385 Call a magic function by name.
2376
2386
2377 Input: a string containing the name of the magic function to call and
2387 Input: a string containing the name of the magic function to call and
2378 any additional arguments to be passed to the magic.
2388 any additional arguments to be passed to the magic.
2379
2389
2380 magic('name -opt foo bar') is equivalent to typing at the ipython
2390 magic('name -opt foo bar') is equivalent to typing at the ipython
2381 prompt:
2391 prompt:
2382
2392
2383 In[1]: %name -opt foo bar
2393 In[1]: %name -opt foo bar
2384
2394
2385 To call a magic without arguments, simply use magic('name').
2395 To call a magic without arguments, simply use magic('name').
2386
2396
2387 This provides a proper Python function to call IPython's magics in any
2397 This provides a proper Python function to call IPython's magics in any
2388 valid Python code you can type at the interpreter, including loops and
2398 valid Python code you can type at the interpreter, including loops and
2389 compound statements.
2399 compound statements.
2390 """
2400 """
2391 warnings.warn(
2401 warnings.warn(
2392 "`magic(...)` is deprecated since IPython 0.13 (warning added in "
2402 "`magic(...)` is deprecated since IPython 0.13 (warning added in "
2393 "8.1), use run_line_magic(magic_name, parameter_s).",
2403 "8.1), use run_line_magic(magic_name, parameter_s).",
2394 DeprecationWarning,
2404 DeprecationWarning,
2395 stacklevel=2,
2405 stacklevel=2,
2396 )
2406 )
2397 # TODO: should we issue a loud deprecation warning here?
2407 # TODO: should we issue a loud deprecation warning here?
2398 magic_name, _, magic_arg_s = arg_s.partition(' ')
2408 magic_name, _, magic_arg_s = arg_s.partition(' ')
2399 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2409 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2400 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2410 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2401
2411
2402 #-------------------------------------------------------------------------
2412 #-------------------------------------------------------------------------
2403 # Things related to macros
2413 # Things related to macros
2404 #-------------------------------------------------------------------------
2414 #-------------------------------------------------------------------------
2405
2415
2406 def define_macro(self, name, themacro):
2416 def define_macro(self, name, themacro):
2407 """Define a new macro
2417 """Define a new macro
2408
2418
2409 Parameters
2419 Parameters
2410 ----------
2420 ----------
2411 name : str
2421 name : str
2412 The name of the macro.
2422 The name of the macro.
2413 themacro : str or Macro
2423 themacro : str or Macro
2414 The action to do upon invoking the macro. If a string, a new
2424 The action to do upon invoking the macro. If a string, a new
2415 Macro object is created by passing the string to it.
2425 Macro object is created by passing the string to it.
2416 """
2426 """
2417
2427
2418 from IPython.core import macro
2428 from IPython.core import macro
2419
2429
2420 if isinstance(themacro, str):
2430 if isinstance(themacro, str):
2421 themacro = macro.Macro(themacro)
2431 themacro = macro.Macro(themacro)
2422 if not isinstance(themacro, macro.Macro):
2432 if not isinstance(themacro, macro.Macro):
2423 raise ValueError('A macro must be a string or a Macro instance.')
2433 raise ValueError('A macro must be a string or a Macro instance.')
2424 self.user_ns[name] = themacro
2434 self.user_ns[name] = themacro
2425
2435
2426 #-------------------------------------------------------------------------
2436 #-------------------------------------------------------------------------
2427 # Things related to the running of system commands
2437 # Things related to the running of system commands
2428 #-------------------------------------------------------------------------
2438 #-------------------------------------------------------------------------
2429
2439
2430 def system_piped(self, cmd):
2440 def system_piped(self, cmd):
2431 """Call the given cmd in a subprocess, piping stdout/err
2441 """Call the given cmd in a subprocess, piping stdout/err
2432
2442
2433 Parameters
2443 Parameters
2434 ----------
2444 ----------
2435 cmd : str
2445 cmd : str
2436 Command to execute (can not end in '&', as background processes are
2446 Command to execute (can not end in '&', as background processes are
2437 not supported. Should not be a command that expects input
2447 not supported. Should not be a command that expects input
2438 other than simple text.
2448 other than simple text.
2439 """
2449 """
2440 if cmd.rstrip().endswith('&'):
2450 if cmd.rstrip().endswith('&'):
2441 # this is *far* from a rigorous test
2451 # this is *far* from a rigorous test
2442 # We do not support backgrounding processes because we either use
2452 # We do not support backgrounding processes because we either use
2443 # pexpect or pipes to read from. Users can always just call
2453 # pexpect or pipes to read from. Users can always just call
2444 # os.system() or use ip.system=ip.system_raw
2454 # os.system() or use ip.system=ip.system_raw
2445 # if they really want a background process.
2455 # if they really want a background process.
2446 raise OSError("Background processes not supported.")
2456 raise OSError("Background processes not supported.")
2447
2457
2448 # we explicitly do NOT return the subprocess status code, because
2458 # we explicitly do NOT return the subprocess status code, because
2449 # a non-None value would trigger :func:`sys.displayhook` calls.
2459 # a non-None value would trigger :func:`sys.displayhook` calls.
2450 # Instead, we store the exit_code in user_ns.
2460 # Instead, we store the exit_code in user_ns.
2451 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2461 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2452
2462
2453 def system_raw(self, cmd):
2463 def system_raw(self, cmd):
2454 """Call the given cmd in a subprocess using os.system on Windows or
2464 """Call the given cmd in a subprocess using os.system on Windows or
2455 subprocess.call using the system shell on other platforms.
2465 subprocess.call using the system shell on other platforms.
2456
2466
2457 Parameters
2467 Parameters
2458 ----------
2468 ----------
2459 cmd : str
2469 cmd : str
2460 Command to execute.
2470 Command to execute.
2461 """
2471 """
2462 cmd = self.var_expand(cmd, depth=1)
2472 cmd = self.var_expand(cmd, depth=1)
2463 # warn if there is an IPython magic alternative.
2473 # warn if there is an IPython magic alternative.
2464 main_cmd = cmd.split()[0]
2474 main_cmd = cmd.split()[0]
2465 has_magic_alternatives = ("pip", "conda", "cd")
2475 has_magic_alternatives = ("pip", "conda", "cd")
2466
2476
2467 if main_cmd in has_magic_alternatives:
2477 if main_cmd in has_magic_alternatives:
2468 warnings.warn(
2478 warnings.warn(
2469 (
2479 (
2470 "You executed the system command !{0} which may not work "
2480 "You executed the system command !{0} which may not work "
2471 "as expected. Try the IPython magic %{0} instead."
2481 "as expected. Try the IPython magic %{0} instead."
2472 ).format(main_cmd)
2482 ).format(main_cmd)
2473 )
2483 )
2474
2484
2475 # protect os.system from UNC paths on Windows, which it can't handle:
2485 # protect os.system from UNC paths on Windows, which it can't handle:
2476 if sys.platform == 'win32':
2486 if sys.platform == 'win32':
2477 from IPython.utils._process_win32 import AvoidUNCPath
2487 from IPython.utils._process_win32 import AvoidUNCPath
2478 with AvoidUNCPath() as path:
2488 with AvoidUNCPath() as path:
2479 if path is not None:
2489 if path is not None:
2480 cmd = '"pushd %s &&"%s' % (path, cmd)
2490 cmd = '"pushd %s &&"%s' % (path, cmd)
2481 try:
2491 try:
2482 ec = os.system(cmd)
2492 ec = os.system(cmd)
2483 except KeyboardInterrupt:
2493 except KeyboardInterrupt:
2484 print('\n' + self.get_exception_only(), file=sys.stderr)
2494 print('\n' + self.get_exception_only(), file=sys.stderr)
2485 ec = -2
2495 ec = -2
2486 else:
2496 else:
2487 # For posix the result of the subprocess.call() below is an exit
2497 # For posix the result of the subprocess.call() below is an exit
2488 # code, which by convention is zero for success, positive for
2498 # code, which by convention is zero for success, positive for
2489 # program failure. Exit codes above 128 are reserved for signals,
2499 # program failure. Exit codes above 128 are reserved for signals,
2490 # and the formula for converting a signal to an exit code is usually
2500 # and the formula for converting a signal to an exit code is usually
2491 # signal_number+128. To more easily differentiate between exit
2501 # signal_number+128. To more easily differentiate between exit
2492 # codes and signals, ipython uses negative numbers. For instance
2502 # codes and signals, ipython uses negative numbers. For instance
2493 # since control-c is signal 2 but exit code 130, ipython's
2503 # since control-c is signal 2 but exit code 130, ipython's
2494 # _exit_code variable will read -2. Note that some shells like
2504 # _exit_code variable will read -2. Note that some shells like
2495 # csh and fish don't follow sh/bash conventions for exit codes.
2505 # csh and fish don't follow sh/bash conventions for exit codes.
2496 executable = os.environ.get('SHELL', None)
2506 executable = os.environ.get('SHELL', None)
2497 try:
2507 try:
2498 # Use env shell instead of default /bin/sh
2508 # Use env shell instead of default /bin/sh
2499 ec = subprocess.call(cmd, shell=True, executable=executable)
2509 ec = subprocess.call(cmd, shell=True, executable=executable)
2500 except KeyboardInterrupt:
2510 except KeyboardInterrupt:
2501 # intercept control-C; a long traceback is not useful here
2511 # intercept control-C; a long traceback is not useful here
2502 print('\n' + self.get_exception_only(), file=sys.stderr)
2512 print('\n' + self.get_exception_only(), file=sys.stderr)
2503 ec = 130
2513 ec = 130
2504 if ec > 128:
2514 if ec > 128:
2505 ec = -(ec - 128)
2515 ec = -(ec - 128)
2506
2516
2507 # We explicitly do NOT return the subprocess status code, because
2517 # We explicitly do NOT return the subprocess status code, because
2508 # a non-None value would trigger :func:`sys.displayhook` calls.
2518 # a non-None value would trigger :func:`sys.displayhook` calls.
2509 # Instead, we store the exit_code in user_ns. Note the semantics
2519 # Instead, we store the exit_code in user_ns. Note the semantics
2510 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2520 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2511 # but raising SystemExit(_exit_code) will give status 254!
2521 # but raising SystemExit(_exit_code) will give status 254!
2512 self.user_ns['_exit_code'] = ec
2522 self.user_ns['_exit_code'] = ec
2513
2523
2514 # use piped system by default, because it is better behaved
2524 # use piped system by default, because it is better behaved
2515 system = system_piped
2525 system = system_piped
2516
2526
2517 def getoutput(self, cmd, split=True, depth=0):
2527 def getoutput(self, cmd, split=True, depth=0):
2518 """Get output (possibly including stderr) from a subprocess.
2528 """Get output (possibly including stderr) from a subprocess.
2519
2529
2520 Parameters
2530 Parameters
2521 ----------
2531 ----------
2522 cmd : str
2532 cmd : str
2523 Command to execute (can not end in '&', as background processes are
2533 Command to execute (can not end in '&', as background processes are
2524 not supported.
2534 not supported.
2525 split : bool, optional
2535 split : bool, optional
2526 If True, split the output into an IPython SList. Otherwise, an
2536 If True, split the output into an IPython SList. Otherwise, an
2527 IPython LSString is returned. These are objects similar to normal
2537 IPython LSString is returned. These are objects similar to normal
2528 lists and strings, with a few convenience attributes for easier
2538 lists and strings, with a few convenience attributes for easier
2529 manipulation of line-based output. You can use '?' on them for
2539 manipulation of line-based output. You can use '?' on them for
2530 details.
2540 details.
2531 depth : int, optional
2541 depth : int, optional
2532 How many frames above the caller are the local variables which should
2542 How many frames above the caller are the local variables which should
2533 be expanded in the command string? The default (0) assumes that the
2543 be expanded in the command string? The default (0) assumes that the
2534 expansion variables are in the stack frame calling this function.
2544 expansion variables are in the stack frame calling this function.
2535 """
2545 """
2536 if cmd.rstrip().endswith('&'):
2546 if cmd.rstrip().endswith('&'):
2537 # this is *far* from a rigorous test
2547 # this is *far* from a rigorous test
2538 raise OSError("Background processes not supported.")
2548 raise OSError("Background processes not supported.")
2539 out = getoutput(self.var_expand(cmd, depth=depth+1))
2549 out = getoutput(self.var_expand(cmd, depth=depth+1))
2540 if split:
2550 if split:
2541 out = SList(out.splitlines())
2551 out = SList(out.splitlines())
2542 else:
2552 else:
2543 out = LSString(out)
2553 out = LSString(out)
2544 return out
2554 return out
2545
2555
2546 #-------------------------------------------------------------------------
2556 #-------------------------------------------------------------------------
2547 # Things related to aliases
2557 # Things related to aliases
2548 #-------------------------------------------------------------------------
2558 #-------------------------------------------------------------------------
2549
2559
2550 def init_alias(self):
2560 def init_alias(self):
2551 self.alias_manager = AliasManager(shell=self, parent=self)
2561 self.alias_manager = AliasManager(shell=self, parent=self)
2552 self.configurables.append(self.alias_manager)
2562 self.configurables.append(self.alias_manager)
2553
2563
2554 #-------------------------------------------------------------------------
2564 #-------------------------------------------------------------------------
2555 # Things related to extensions
2565 # Things related to extensions
2556 #-------------------------------------------------------------------------
2566 #-------------------------------------------------------------------------
2557
2567
2558 def init_extension_manager(self):
2568 def init_extension_manager(self):
2559 self.extension_manager = ExtensionManager(shell=self, parent=self)
2569 self.extension_manager = ExtensionManager(shell=self, parent=self)
2560 self.configurables.append(self.extension_manager)
2570 self.configurables.append(self.extension_manager)
2561
2571
2562 #-------------------------------------------------------------------------
2572 #-------------------------------------------------------------------------
2563 # Things related to payloads
2573 # Things related to payloads
2564 #-------------------------------------------------------------------------
2574 #-------------------------------------------------------------------------
2565
2575
2566 def init_payload(self):
2576 def init_payload(self):
2567 self.payload_manager = PayloadManager(parent=self)
2577 self.payload_manager = PayloadManager(parent=self)
2568 self.configurables.append(self.payload_manager)
2578 self.configurables.append(self.payload_manager)
2569
2579
2570 #-------------------------------------------------------------------------
2580 #-------------------------------------------------------------------------
2571 # Things related to the prefilter
2581 # Things related to the prefilter
2572 #-------------------------------------------------------------------------
2582 #-------------------------------------------------------------------------
2573
2583
2574 def init_prefilter(self):
2584 def init_prefilter(self):
2575 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2585 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2576 self.configurables.append(self.prefilter_manager)
2586 self.configurables.append(self.prefilter_manager)
2577 # Ultimately this will be refactored in the new interpreter code, but
2587 # Ultimately this will be refactored in the new interpreter code, but
2578 # for now, we should expose the main prefilter method (there's legacy
2588 # for now, we should expose the main prefilter method (there's legacy
2579 # code out there that may rely on this).
2589 # code out there that may rely on this).
2580 self.prefilter = self.prefilter_manager.prefilter_lines
2590 self.prefilter = self.prefilter_manager.prefilter_lines
2581
2591
2582 def auto_rewrite_input(self, cmd):
2592 def auto_rewrite_input(self, cmd):
2583 """Print to the screen the rewritten form of the user's command.
2593 """Print to the screen the rewritten form of the user's command.
2584
2594
2585 This shows visual feedback by rewriting input lines that cause
2595 This shows visual feedback by rewriting input lines that cause
2586 automatic calling to kick in, like::
2596 automatic calling to kick in, like::
2587
2597
2588 /f x
2598 /f x
2589
2599
2590 into::
2600 into::
2591
2601
2592 ------> f(x)
2602 ------> f(x)
2593
2603
2594 after the user's input prompt. This helps the user understand that the
2604 after the user's input prompt. This helps the user understand that the
2595 input line was transformed automatically by IPython.
2605 input line was transformed automatically by IPython.
2596 """
2606 """
2597 if not self.show_rewritten_input:
2607 if not self.show_rewritten_input:
2598 return
2608 return
2599
2609
2600 # This is overridden in TerminalInteractiveShell to use fancy prompts
2610 # This is overridden in TerminalInteractiveShell to use fancy prompts
2601 print("------> " + cmd)
2611 print("------> " + cmd)
2602
2612
2603 #-------------------------------------------------------------------------
2613 #-------------------------------------------------------------------------
2604 # Things related to extracting values/expressions from kernel and user_ns
2614 # Things related to extracting values/expressions from kernel and user_ns
2605 #-------------------------------------------------------------------------
2615 #-------------------------------------------------------------------------
2606
2616
2607 def _user_obj_error(self):
2617 def _user_obj_error(self):
2608 """return simple exception dict
2618 """return simple exception dict
2609
2619
2610 for use in user_expressions
2620 for use in user_expressions
2611 """
2621 """
2612
2622
2613 etype, evalue, tb = self._get_exc_info()
2623 etype, evalue, tb = self._get_exc_info()
2614 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2624 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2615
2625
2616 exc_info = {
2626 exc_info = {
2617 "status": "error",
2627 "status": "error",
2618 "traceback": stb,
2628 "traceback": stb,
2619 "ename": etype.__name__,
2629 "ename": etype.__name__,
2620 "evalue": py3compat.safe_unicode(evalue),
2630 "evalue": py3compat.safe_unicode(evalue),
2621 }
2631 }
2622
2632
2623 return exc_info
2633 return exc_info
2624
2634
2625 def _format_user_obj(self, obj):
2635 def _format_user_obj(self, obj):
2626 """format a user object to display dict
2636 """format a user object to display dict
2627
2637
2628 for use in user_expressions
2638 for use in user_expressions
2629 """
2639 """
2630
2640
2631 data, md = self.display_formatter.format(obj)
2641 data, md = self.display_formatter.format(obj)
2632 value = {
2642 value = {
2633 'status' : 'ok',
2643 'status' : 'ok',
2634 'data' : data,
2644 'data' : data,
2635 'metadata' : md,
2645 'metadata' : md,
2636 }
2646 }
2637 return value
2647 return value
2638
2648
2639 def user_expressions(self, expressions):
2649 def user_expressions(self, expressions):
2640 """Evaluate a dict of expressions in the user's namespace.
2650 """Evaluate a dict of expressions in the user's namespace.
2641
2651
2642 Parameters
2652 Parameters
2643 ----------
2653 ----------
2644 expressions : dict
2654 expressions : dict
2645 A dict with string keys and string values. The expression values
2655 A dict with string keys and string values. The expression values
2646 should be valid Python expressions, each of which will be evaluated
2656 should be valid Python expressions, each of which will be evaluated
2647 in the user namespace.
2657 in the user namespace.
2648
2658
2649 Returns
2659 Returns
2650 -------
2660 -------
2651 A dict, keyed like the input expressions dict, with the rich mime-typed
2661 A dict, keyed like the input expressions dict, with the rich mime-typed
2652 display_data of each value.
2662 display_data of each value.
2653 """
2663 """
2654 out = {}
2664 out = {}
2655 user_ns = self.user_ns
2665 user_ns = self.user_ns
2656 global_ns = self.user_global_ns
2666 global_ns = self.user_global_ns
2657
2667
2658 for key, expr in expressions.items():
2668 for key, expr in expressions.items():
2659 try:
2669 try:
2660 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2670 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2661 except:
2671 except:
2662 value = self._user_obj_error()
2672 value = self._user_obj_error()
2663 out[key] = value
2673 out[key] = value
2664 return out
2674 return out
2665
2675
2666 #-------------------------------------------------------------------------
2676 #-------------------------------------------------------------------------
2667 # Things related to the running of code
2677 # Things related to the running of code
2668 #-------------------------------------------------------------------------
2678 #-------------------------------------------------------------------------
2669
2679
2670 def ex(self, cmd):
2680 def ex(self, cmd):
2671 """Execute a normal python statement in user namespace."""
2681 """Execute a normal python statement in user namespace."""
2672 with self.builtin_trap:
2682 with self.builtin_trap:
2673 exec(cmd, self.user_global_ns, self.user_ns)
2683 exec(cmd, self.user_global_ns, self.user_ns)
2674
2684
2675 def ev(self, expr):
2685 def ev(self, expr):
2676 """Evaluate python expression expr in user namespace.
2686 """Evaluate python expression expr in user namespace.
2677
2687
2678 Returns the result of evaluation
2688 Returns the result of evaluation
2679 """
2689 """
2680 with self.builtin_trap:
2690 with self.builtin_trap:
2681 return eval(expr, self.user_global_ns, self.user_ns)
2691 return eval(expr, self.user_global_ns, self.user_ns)
2682
2692
2683 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2693 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2684 """A safe version of the builtin execfile().
2694 """A safe version of the builtin execfile().
2685
2695
2686 This version will never throw an exception, but instead print
2696 This version will never throw an exception, but instead print
2687 helpful error messages to the screen. This only works on pure
2697 helpful error messages to the screen. This only works on pure
2688 Python files with the .py extension.
2698 Python files with the .py extension.
2689
2699
2690 Parameters
2700 Parameters
2691 ----------
2701 ----------
2692 fname : string
2702 fname : string
2693 The name of the file to be executed.
2703 The name of the file to be executed.
2694 *where : tuple
2704 *where : tuple
2695 One or two namespaces, passed to execfile() as (globals,locals).
2705 One or two namespaces, passed to execfile() as (globals,locals).
2696 If only one is given, it is passed as both.
2706 If only one is given, it is passed as both.
2697 exit_ignore : bool (False)
2707 exit_ignore : bool (False)
2698 If True, then silence SystemExit for non-zero status (it is always
2708 If True, then silence SystemExit for non-zero status (it is always
2699 silenced for zero status, as it is so common).
2709 silenced for zero status, as it is so common).
2700 raise_exceptions : bool (False)
2710 raise_exceptions : bool (False)
2701 If True raise exceptions everywhere. Meant for testing.
2711 If True raise exceptions everywhere. Meant for testing.
2702 shell_futures : bool (False)
2712 shell_futures : bool (False)
2703 If True, the code will share future statements with the interactive
2713 If True, the code will share future statements with the interactive
2704 shell. It will both be affected by previous __future__ imports, and
2714 shell. It will both be affected by previous __future__ imports, and
2705 any __future__ imports in the code will affect the shell. If False,
2715 any __future__ imports in the code will affect the shell. If False,
2706 __future__ imports are not shared in either direction.
2716 __future__ imports are not shared in either direction.
2707
2717
2708 """
2718 """
2709 fname = Path(fname).expanduser().resolve()
2719 fname = Path(fname).expanduser().resolve()
2710
2720
2711 # Make sure we can open the file
2721 # Make sure we can open the file
2712 try:
2722 try:
2713 with fname.open("rb"):
2723 with fname.open("rb"):
2714 pass
2724 pass
2715 except:
2725 except:
2716 warn('Could not open file <%s> for safe execution.' % fname)
2726 warn('Could not open file <%s> for safe execution.' % fname)
2717 return
2727 return
2718
2728
2719 # Find things also in current directory. This is needed to mimic the
2729 # Find things also in current directory. This is needed to mimic the
2720 # behavior of running a script from the system command line, where
2730 # behavior of running a script from the system command line, where
2721 # Python inserts the script's directory into sys.path
2731 # Python inserts the script's directory into sys.path
2722 dname = str(fname.parent)
2732 dname = str(fname.parent)
2723
2733
2724 with prepended_to_syspath(dname), self.builtin_trap:
2734 with prepended_to_syspath(dname), self.builtin_trap:
2725 try:
2735 try:
2726 glob, loc = (where + (None, ))[:2]
2736 glob, loc = (where + (None, ))[:2]
2727 py3compat.execfile(
2737 py3compat.execfile(
2728 fname, glob, loc,
2738 fname, glob, loc,
2729 self.compile if shell_futures else None)
2739 self.compile if shell_futures else None)
2730 except SystemExit as status:
2740 except SystemExit as status:
2731 # If the call was made with 0 or None exit status (sys.exit(0)
2741 # If the call was made with 0 or None exit status (sys.exit(0)
2732 # or sys.exit() ), don't bother showing a traceback, as both of
2742 # or sys.exit() ), don't bother showing a traceback, as both of
2733 # these are considered normal by the OS:
2743 # these are considered normal by the OS:
2734 # > python -c'import sys;sys.exit(0)'; echo $?
2744 # > python -c'import sys;sys.exit(0)'; echo $?
2735 # 0
2745 # 0
2736 # > python -c'import sys;sys.exit()'; echo $?
2746 # > python -c'import sys;sys.exit()'; echo $?
2737 # 0
2747 # 0
2738 # For other exit status, we show the exception unless
2748 # For other exit status, we show the exception unless
2739 # explicitly silenced, but only in short form.
2749 # explicitly silenced, but only in short form.
2740 if status.code:
2750 if status.code:
2741 if raise_exceptions:
2751 if raise_exceptions:
2742 raise
2752 raise
2743 if not exit_ignore:
2753 if not exit_ignore:
2744 self.showtraceback(exception_only=True)
2754 self.showtraceback(exception_only=True)
2745 except:
2755 except:
2746 if raise_exceptions:
2756 if raise_exceptions:
2747 raise
2757 raise
2748 # tb offset is 2 because we wrap execfile
2758 # tb offset is 2 because we wrap execfile
2749 self.showtraceback(tb_offset=2)
2759 self.showtraceback(tb_offset=2)
2750
2760
2751 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2761 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2752 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2762 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2753
2763
2754 Parameters
2764 Parameters
2755 ----------
2765 ----------
2756 fname : str
2766 fname : str
2757 The name of the file to execute. The filename must have a
2767 The name of the file to execute. The filename must have a
2758 .ipy or .ipynb extension.
2768 .ipy or .ipynb extension.
2759 shell_futures : bool (False)
2769 shell_futures : bool (False)
2760 If True, the code will share future statements with the interactive
2770 If True, the code will share future statements with the interactive
2761 shell. It will both be affected by previous __future__ imports, and
2771 shell. It will both be affected by previous __future__ imports, and
2762 any __future__ imports in the code will affect the shell. If False,
2772 any __future__ imports in the code will affect the shell. If False,
2763 __future__ imports are not shared in either direction.
2773 __future__ imports are not shared in either direction.
2764 raise_exceptions : bool (False)
2774 raise_exceptions : bool (False)
2765 If True raise exceptions everywhere. Meant for testing.
2775 If True raise exceptions everywhere. Meant for testing.
2766 """
2776 """
2767 fname = Path(fname).expanduser().resolve()
2777 fname = Path(fname).expanduser().resolve()
2768
2778
2769 # Make sure we can open the file
2779 # Make sure we can open the file
2770 try:
2780 try:
2771 with fname.open("rb"):
2781 with fname.open("rb"):
2772 pass
2782 pass
2773 except:
2783 except:
2774 warn('Could not open file <%s> for safe execution.' % fname)
2784 warn('Could not open file <%s> for safe execution.' % fname)
2775 return
2785 return
2776
2786
2777 # Find things also in current directory. This is needed to mimic the
2787 # Find things also in current directory. This is needed to mimic the
2778 # behavior of running a script from the system command line, where
2788 # behavior of running a script from the system command line, where
2779 # Python inserts the script's directory into sys.path
2789 # Python inserts the script's directory into sys.path
2780 dname = str(fname.parent)
2790 dname = str(fname.parent)
2781
2791
2782 def get_cells():
2792 def get_cells():
2783 """generator for sequence of code blocks to run"""
2793 """generator for sequence of code blocks to run"""
2784 if fname.suffix == ".ipynb":
2794 if fname.suffix == ".ipynb":
2785 from nbformat import read
2795 from nbformat import read
2786 nb = read(fname, as_version=4)
2796 nb = read(fname, as_version=4)
2787 if not nb.cells:
2797 if not nb.cells:
2788 return
2798 return
2789 for cell in nb.cells:
2799 for cell in nb.cells:
2790 if cell.cell_type == 'code':
2800 if cell.cell_type == 'code':
2791 yield cell.source
2801 yield cell.source
2792 else:
2802 else:
2793 yield fname.read_text(encoding="utf-8")
2803 yield fname.read_text(encoding="utf-8")
2794
2804
2795 with prepended_to_syspath(dname):
2805 with prepended_to_syspath(dname):
2796 try:
2806 try:
2797 for cell in get_cells():
2807 for cell in get_cells():
2798 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2808 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2799 if raise_exceptions:
2809 if raise_exceptions:
2800 result.raise_error()
2810 result.raise_error()
2801 elif not result.success:
2811 elif not result.success:
2802 break
2812 break
2803 except:
2813 except:
2804 if raise_exceptions:
2814 if raise_exceptions:
2805 raise
2815 raise
2806 self.showtraceback()
2816 self.showtraceback()
2807 warn('Unknown failure executing file: <%s>' % fname)
2817 warn('Unknown failure executing file: <%s>' % fname)
2808
2818
2809 def safe_run_module(self, mod_name, where):
2819 def safe_run_module(self, mod_name, where):
2810 """A safe version of runpy.run_module().
2820 """A safe version of runpy.run_module().
2811
2821
2812 This version will never throw an exception, but instead print
2822 This version will never throw an exception, but instead print
2813 helpful error messages to the screen.
2823 helpful error messages to the screen.
2814
2824
2815 `SystemExit` exceptions with status code 0 or None are ignored.
2825 `SystemExit` exceptions with status code 0 or None are ignored.
2816
2826
2817 Parameters
2827 Parameters
2818 ----------
2828 ----------
2819 mod_name : string
2829 mod_name : string
2820 The name of the module to be executed.
2830 The name of the module to be executed.
2821 where : dict
2831 where : dict
2822 The globals namespace.
2832 The globals namespace.
2823 """
2833 """
2824 try:
2834 try:
2825 try:
2835 try:
2826 where.update(
2836 where.update(
2827 runpy.run_module(str(mod_name), run_name="__main__",
2837 runpy.run_module(str(mod_name), run_name="__main__",
2828 alter_sys=True)
2838 alter_sys=True)
2829 )
2839 )
2830 except SystemExit as status:
2840 except SystemExit as status:
2831 if status.code:
2841 if status.code:
2832 raise
2842 raise
2833 except:
2843 except:
2834 self.showtraceback()
2844 self.showtraceback()
2835 warn('Unknown failure executing module: <%s>' % mod_name)
2845 warn('Unknown failure executing module: <%s>' % mod_name)
2836
2846
2837 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2847 def run_cell(
2848 self,
2849 raw_cell,
2850 store_history=False,
2851 silent=False,
2852 shell_futures=True,
2853 cell_id=None,
2854 ):
2838 """Run a complete IPython cell.
2855 """Run a complete IPython cell.
2839
2856
2840 Parameters
2857 Parameters
2841 ----------
2858 ----------
2842 raw_cell : str
2859 raw_cell : str
2843 The code (including IPython code such as %magic functions) to run.
2860 The code (including IPython code such as %magic functions) to run.
2844 store_history : bool
2861 store_history : bool
2845 If True, the raw and translated cell will be stored in IPython's
2862 If True, the raw and translated cell will be stored in IPython's
2846 history. For user code calling back into IPython's machinery, this
2863 history. For user code calling back into IPython's machinery, this
2847 should be set to False.
2864 should be set to False.
2848 silent : bool
2865 silent : bool
2849 If True, avoid side-effects, such as implicit displayhooks and
2866 If True, avoid side-effects, such as implicit displayhooks and
2850 and logging. silent=True forces store_history=False.
2867 and logging. silent=True forces store_history=False.
2851 shell_futures : bool
2868 shell_futures : bool
2852 If True, the code will share future statements with the interactive
2869 If True, the code will share future statements with the interactive
2853 shell. It will both be affected by previous __future__ imports, and
2870 shell. It will both be affected by previous __future__ imports, and
2854 any __future__ imports in the code will affect the shell. If False,
2871 any __future__ imports in the code will affect the shell. If False,
2855 __future__ imports are not shared in either direction.
2872 __future__ imports are not shared in either direction.
2856
2873
2857 Returns
2874 Returns
2858 -------
2875 -------
2859 result : :class:`ExecutionResult`
2876 result : :class:`ExecutionResult`
2860 """
2877 """
2861 result = None
2878 result = None
2862 try:
2879 try:
2863 result = self._run_cell(
2880 result = self._run_cell(
2864 raw_cell, store_history, silent, shell_futures)
2881 raw_cell, store_history, silent, shell_futures, cell_id
2882 )
2865 finally:
2883 finally:
2866 self.events.trigger('post_execute')
2884 self.events.trigger('post_execute')
2867 if not silent:
2885 if not silent:
2868 self.events.trigger('post_run_cell', result)
2886 self.events.trigger('post_run_cell', result)
2869 return result
2887 return result
2870
2888
2871 def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool) -> ExecutionResult:
2889 def _run_cell(
2890 self,
2891 raw_cell: str,
2892 store_history: bool,
2893 silent: bool,
2894 shell_futures: bool,
2895 cell_id: str,
2896 ) -> ExecutionResult:
2872 """Internal method to run a complete IPython cell."""
2897 """Internal method to run a complete IPython cell."""
2873
2898
2874 # we need to avoid calling self.transform_cell multiple time on the same thing
2899 # we need to avoid calling self.transform_cell multiple time on the same thing
2875 # so we need to store some results:
2900 # so we need to store some results:
2876 preprocessing_exc_tuple = None
2901 preprocessing_exc_tuple = None
2877 try:
2902 try:
2878 transformed_cell = self.transform_cell(raw_cell)
2903 transformed_cell = self.transform_cell(raw_cell)
2879 except Exception:
2904 except Exception:
2880 transformed_cell = raw_cell
2905 transformed_cell = raw_cell
2881 preprocessing_exc_tuple = sys.exc_info()
2906 preprocessing_exc_tuple = sys.exc_info()
2882
2907
2883 assert transformed_cell is not None
2908 assert transformed_cell is not None
2884 coro = self.run_cell_async(
2909 coro = self.run_cell_async(
2885 raw_cell,
2910 raw_cell,
2886 store_history=store_history,
2911 store_history=store_history,
2887 silent=silent,
2912 silent=silent,
2888 shell_futures=shell_futures,
2913 shell_futures=shell_futures,
2889 transformed_cell=transformed_cell,
2914 transformed_cell=transformed_cell,
2890 preprocessing_exc_tuple=preprocessing_exc_tuple,
2915 preprocessing_exc_tuple=preprocessing_exc_tuple,
2916 cell_id=cell_id,
2891 )
2917 )
2892
2918
2893 # run_cell_async is async, but may not actually need an eventloop.
2919 # run_cell_async is async, but may not actually need an eventloop.
2894 # when this is the case, we want to run it using the pseudo_sync_runner
2920 # when this is the case, we want to run it using the pseudo_sync_runner
2895 # so that code can invoke eventloops (for example via the %run , and
2921 # so that code can invoke eventloops (for example via the %run , and
2896 # `%paste` magic.
2922 # `%paste` magic.
2897 if self.trio_runner:
2923 if self.trio_runner:
2898 runner = self.trio_runner
2924 runner = self.trio_runner
2899 elif self.should_run_async(
2925 elif self.should_run_async(
2900 raw_cell,
2926 raw_cell,
2901 transformed_cell=transformed_cell,
2927 transformed_cell=transformed_cell,
2902 preprocessing_exc_tuple=preprocessing_exc_tuple,
2928 preprocessing_exc_tuple=preprocessing_exc_tuple,
2903 ):
2929 ):
2904 runner = self.loop_runner
2930 runner = self.loop_runner
2905 else:
2931 else:
2906 runner = _pseudo_sync_runner
2932 runner = _pseudo_sync_runner
2907
2933
2908 try:
2934 try:
2909 return runner(coro)
2935 return runner(coro)
2910 except BaseException as e:
2936 except BaseException as e:
2911 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
2937 info = ExecutionInfo(
2938 raw_cell, store_history, silent, shell_futures, cell_id
2939 )
2912 result = ExecutionResult(info)
2940 result = ExecutionResult(info)
2913 result.error_in_exec = e
2941 result.error_in_exec = e
2914 self.showtraceback(running_compiled_code=True)
2942 self.showtraceback(running_compiled_code=True)
2915 return result
2943 return result
2916
2944
2917 def should_run_async(
2945 def should_run_async(
2918 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
2946 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
2919 ) -> bool:
2947 ) -> bool:
2920 """Return whether a cell should be run asynchronously via a coroutine runner
2948 """Return whether a cell should be run asynchronously via a coroutine runner
2921
2949
2922 Parameters
2950 Parameters
2923 ----------
2951 ----------
2924 raw_cell : str
2952 raw_cell : str
2925 The code to be executed
2953 The code to be executed
2926
2954
2927 Returns
2955 Returns
2928 -------
2956 -------
2929 result: bool
2957 result: bool
2930 Whether the code needs to be run with a coroutine runner or not
2958 Whether the code needs to be run with a coroutine runner or not
2931 .. versionadded:: 7.0
2959 .. versionadded:: 7.0
2932 """
2960 """
2933 if not self.autoawait:
2961 if not self.autoawait:
2934 return False
2962 return False
2935 if preprocessing_exc_tuple is not None:
2963 if preprocessing_exc_tuple is not None:
2936 return False
2964 return False
2937 assert preprocessing_exc_tuple is None
2965 assert preprocessing_exc_tuple is None
2938 if transformed_cell is None:
2966 if transformed_cell is None:
2939 warnings.warn(
2967 warnings.warn(
2940 "`should_run_async` will not call `transform_cell`"
2968 "`should_run_async` will not call `transform_cell`"
2941 " automatically in the future. Please pass the result to"
2969 " automatically in the future. Please pass the result to"
2942 " `transformed_cell` argument and any exception that happen"
2970 " `transformed_cell` argument and any exception that happen"
2943 " during the"
2971 " during the"
2944 "transform in `preprocessing_exc_tuple` in"
2972 "transform in `preprocessing_exc_tuple` in"
2945 " IPython 7.17 and above.",
2973 " IPython 7.17 and above.",
2946 DeprecationWarning,
2974 DeprecationWarning,
2947 stacklevel=2,
2975 stacklevel=2,
2948 )
2976 )
2949 try:
2977 try:
2950 cell = self.transform_cell(raw_cell)
2978 cell = self.transform_cell(raw_cell)
2951 except Exception:
2979 except Exception:
2952 # any exception during transform will be raised
2980 # any exception during transform will be raised
2953 # prior to execution
2981 # prior to execution
2954 return False
2982 return False
2955 else:
2983 else:
2956 cell = transformed_cell
2984 cell = transformed_cell
2957 return _should_be_async(cell)
2985 return _should_be_async(cell)
2958
2986
2959 async def run_cell_async(
2987 async def run_cell_async(
2960 self,
2988 self,
2961 raw_cell: str,
2989 raw_cell: str,
2962 store_history=False,
2990 store_history=False,
2963 silent=False,
2991 silent=False,
2964 shell_futures=True,
2992 shell_futures=True,
2965 *,
2993 *,
2966 transformed_cell: Optional[str] = None,
2994 transformed_cell: Optional[str] = None,
2967 preprocessing_exc_tuple: Optional[Any] = None
2995 preprocessing_exc_tuple: Optional[Any] = None,
2996 cell_id=None,
2968 ) -> ExecutionResult:
2997 ) -> ExecutionResult:
2969 """Run a complete IPython cell asynchronously.
2998 """Run a complete IPython cell asynchronously.
2970
2999
2971 Parameters
3000 Parameters
2972 ----------
3001 ----------
2973 raw_cell : str
3002 raw_cell : str
2974 The code (including IPython code such as %magic functions) to run.
3003 The code (including IPython code such as %magic functions) to run.
2975 store_history : bool
3004 store_history : bool
2976 If True, the raw and translated cell will be stored in IPython's
3005 If True, the raw and translated cell will be stored in IPython's
2977 history. For user code calling back into IPython's machinery, this
3006 history. For user code calling back into IPython's machinery, this
2978 should be set to False.
3007 should be set to False.
2979 silent : bool
3008 silent : bool
2980 If True, avoid side-effects, such as implicit displayhooks and
3009 If True, avoid side-effects, such as implicit displayhooks and
2981 and logging. silent=True forces store_history=False.
3010 and logging. silent=True forces store_history=False.
2982 shell_futures : bool
3011 shell_futures : bool
2983 If True, the code will share future statements with the interactive
3012 If True, the code will share future statements with the interactive
2984 shell. It will both be affected by previous __future__ imports, and
3013 shell. It will both be affected by previous __future__ imports, and
2985 any __future__ imports in the code will affect the shell. If False,
3014 any __future__ imports in the code will affect the shell. If False,
2986 __future__ imports are not shared in either direction.
3015 __future__ imports are not shared in either direction.
2987 transformed_cell: str
3016 transformed_cell: str
2988 cell that was passed through transformers
3017 cell that was passed through transformers
2989 preprocessing_exc_tuple:
3018 preprocessing_exc_tuple:
2990 trace if the transformation failed.
3019 trace if the transformation failed.
2991
3020
2992 Returns
3021 Returns
2993 -------
3022 -------
2994 result : :class:`ExecutionResult`
3023 result : :class:`ExecutionResult`
2995
3024
2996 .. versionadded:: 7.0
3025 .. versionadded:: 7.0
2997 """
3026 """
2998 info = ExecutionInfo(
3027 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id)
2999 raw_cell, store_history, silent, shell_futures)
3000 result = ExecutionResult(info)
3028 result = ExecutionResult(info)
3001
3029
3002 if (not raw_cell) or raw_cell.isspace():
3030 if (not raw_cell) or raw_cell.isspace():
3003 self.last_execution_succeeded = True
3031 self.last_execution_succeeded = True
3004 self.last_execution_result = result
3032 self.last_execution_result = result
3005 return result
3033 return result
3006
3034
3007 if silent:
3035 if silent:
3008 store_history = False
3036 store_history = False
3009
3037
3010 if store_history:
3038 if store_history:
3011 result.execution_count = self.execution_count
3039 result.execution_count = self.execution_count
3012
3040
3013 def error_before_exec(value):
3041 def error_before_exec(value):
3014 if store_history:
3042 if store_history:
3015 self.execution_count += 1
3043 self.execution_count += 1
3016 result.error_before_exec = value
3044 result.error_before_exec = value
3017 self.last_execution_succeeded = False
3045 self.last_execution_succeeded = False
3018 self.last_execution_result = result
3046 self.last_execution_result = result
3019 return result
3047 return result
3020
3048
3021 self.events.trigger('pre_execute')
3049 self.events.trigger('pre_execute')
3022 if not silent:
3050 if not silent:
3023 self.events.trigger('pre_run_cell', info)
3051 self.events.trigger('pre_run_cell', info)
3024
3052
3025 if transformed_cell is None:
3053 if transformed_cell is None:
3026 warnings.warn(
3054 warnings.warn(
3027 "`run_cell_async` will not call `transform_cell`"
3055 "`run_cell_async` will not call `transform_cell`"
3028 " automatically in the future. Please pass the result to"
3056 " automatically in the future. Please pass the result to"
3029 " `transformed_cell` argument and any exception that happen"
3057 " `transformed_cell` argument and any exception that happen"
3030 " during the"
3058 " during the"
3031 "transform in `preprocessing_exc_tuple` in"
3059 "transform in `preprocessing_exc_tuple` in"
3032 " IPython 7.17 and above.",
3060 " IPython 7.17 and above.",
3033 DeprecationWarning,
3061 DeprecationWarning,
3034 stacklevel=2,
3062 stacklevel=2,
3035 )
3063 )
3036 # If any of our input transformation (input_transformer_manager or
3064 # If any of our input transformation (input_transformer_manager or
3037 # prefilter_manager) raises an exception, we store it in this variable
3065 # prefilter_manager) raises an exception, we store it in this variable
3038 # so that we can display the error after logging the input and storing
3066 # so that we can display the error after logging the input and storing
3039 # it in the history.
3067 # it in the history.
3040 try:
3068 try:
3041 cell = self.transform_cell(raw_cell)
3069 cell = self.transform_cell(raw_cell)
3042 except Exception:
3070 except Exception:
3043 preprocessing_exc_tuple = sys.exc_info()
3071 preprocessing_exc_tuple = sys.exc_info()
3044 cell = raw_cell # cell has to exist so it can be stored/logged
3072 cell = raw_cell # cell has to exist so it can be stored/logged
3045 else:
3073 else:
3046 preprocessing_exc_tuple = None
3074 preprocessing_exc_tuple = None
3047 else:
3075 else:
3048 if preprocessing_exc_tuple is None:
3076 if preprocessing_exc_tuple is None:
3049 cell = transformed_cell
3077 cell = transformed_cell
3050 else:
3078 else:
3051 cell = raw_cell
3079 cell = raw_cell
3052
3080
3053 # Store raw and processed history
3081 # Store raw and processed history
3054 if store_history and raw_cell.strip(" %") != "paste":
3082 if store_history and raw_cell.strip(" %") != "paste":
3055 self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
3083 self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
3056 if not silent:
3084 if not silent:
3057 self.logger.log(cell, raw_cell)
3085 self.logger.log(cell, raw_cell)
3058
3086
3059 # Display the exception if input processing failed.
3087 # Display the exception if input processing failed.
3060 if preprocessing_exc_tuple is not None:
3088 if preprocessing_exc_tuple is not None:
3061 self.showtraceback(preprocessing_exc_tuple)
3089 self.showtraceback(preprocessing_exc_tuple)
3062 if store_history:
3090 if store_history:
3063 self.execution_count += 1
3091 self.execution_count += 1
3064 return error_before_exec(preprocessing_exc_tuple[1])
3092 return error_before_exec(preprocessing_exc_tuple[1])
3065
3093
3066 # Our own compiler remembers the __future__ environment. If we want to
3094 # Our own compiler remembers the __future__ environment. If we want to
3067 # run code with a separate __future__ environment, use the default
3095 # run code with a separate __future__ environment, use the default
3068 # compiler
3096 # compiler
3069 compiler = self.compile if shell_futures else self.compiler_class()
3097 compiler = self.compile if shell_futures else self.compiler_class()
3070
3098
3071 _run_async = False
3099 _run_async = False
3072
3100
3073 with self.builtin_trap:
3101 with self.builtin_trap:
3074 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
3102 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
3075
3103
3076 with self.display_trap:
3104 with self.display_trap:
3077 # Compile to bytecode
3105 # Compile to bytecode
3078 try:
3106 try:
3079 code_ast = compiler.ast_parse(cell, filename=cell_name)
3107 code_ast = compiler.ast_parse(cell, filename=cell_name)
3080 except self.custom_exceptions as e:
3108 except self.custom_exceptions as e:
3081 etype, value, tb = sys.exc_info()
3109 etype, value, tb = sys.exc_info()
3082 self.CustomTB(etype, value, tb)
3110 self.CustomTB(etype, value, tb)
3083 return error_before_exec(e)
3111 return error_before_exec(e)
3084 except IndentationError as e:
3112 except IndentationError as e:
3085 self.showindentationerror()
3113 self.showindentationerror()
3086 return error_before_exec(e)
3114 return error_before_exec(e)
3087 except (OverflowError, SyntaxError, ValueError, TypeError,
3115 except (OverflowError, SyntaxError, ValueError, TypeError,
3088 MemoryError) as e:
3116 MemoryError) as e:
3089 self.showsyntaxerror()
3117 self.showsyntaxerror()
3090 return error_before_exec(e)
3118 return error_before_exec(e)
3091
3119
3092 # Apply AST transformations
3120 # Apply AST transformations
3093 try:
3121 try:
3094 code_ast = self.transform_ast(code_ast)
3122 code_ast = self.transform_ast(code_ast)
3095 except InputRejected as e:
3123 except InputRejected as e:
3096 self.showtraceback()
3124 self.showtraceback()
3097 return error_before_exec(e)
3125 return error_before_exec(e)
3098
3126
3099 # Give the displayhook a reference to our ExecutionResult so it
3127 # Give the displayhook a reference to our ExecutionResult so it
3100 # can fill in the output value.
3128 # can fill in the output value.
3101 self.displayhook.exec_result = result
3129 self.displayhook.exec_result = result
3102
3130
3103 # Execute the user code
3131 # Execute the user code
3104 interactivity = "none" if silent else self.ast_node_interactivity
3132 interactivity = "none" if silent else self.ast_node_interactivity
3105
3133
3106 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3134 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3107 interactivity=interactivity, compiler=compiler, result=result)
3135 interactivity=interactivity, compiler=compiler, result=result)
3108
3136
3109 self.last_execution_succeeded = not has_raised
3137 self.last_execution_succeeded = not has_raised
3110 self.last_execution_result = result
3138 self.last_execution_result = result
3111
3139
3112 # Reset this so later displayed values do not modify the
3140 # Reset this so later displayed values do not modify the
3113 # ExecutionResult
3141 # ExecutionResult
3114 self.displayhook.exec_result = None
3142 self.displayhook.exec_result = None
3115
3143
3116 if store_history:
3144 if store_history:
3117 # Write output to the database. Does nothing unless
3145 # Write output to the database. Does nothing unless
3118 # history output logging is enabled.
3146 # history output logging is enabled.
3119 self.history_manager.store_output(self.execution_count)
3147 self.history_manager.store_output(self.execution_count)
3120 # Each cell is a *single* input, regardless of how many lines it has
3148 # Each cell is a *single* input, regardless of how many lines it has
3121 self.execution_count += 1
3149 self.execution_count += 1
3122
3150
3123 return result
3151 return result
3124
3152
3125 def transform_cell(self, raw_cell):
3153 def transform_cell(self, raw_cell):
3126 """Transform an input cell before parsing it.
3154 """Transform an input cell before parsing it.
3127
3155
3128 Static transformations, implemented in IPython.core.inputtransformer2,
3156 Static transformations, implemented in IPython.core.inputtransformer2,
3129 deal with things like ``%magic`` and ``!system`` commands.
3157 deal with things like ``%magic`` and ``!system`` commands.
3130 These run on all input.
3158 These run on all input.
3131 Dynamic transformations, for things like unescaped magics and the exit
3159 Dynamic transformations, for things like unescaped magics and the exit
3132 autocall, depend on the state of the interpreter.
3160 autocall, depend on the state of the interpreter.
3133 These only apply to single line inputs.
3161 These only apply to single line inputs.
3134
3162
3135 These string-based transformations are followed by AST transformations;
3163 These string-based transformations are followed by AST transformations;
3136 see :meth:`transform_ast`.
3164 see :meth:`transform_ast`.
3137 """
3165 """
3138 # Static input transformations
3166 # Static input transformations
3139 cell = self.input_transformer_manager.transform_cell(raw_cell)
3167 cell = self.input_transformer_manager.transform_cell(raw_cell)
3140
3168
3141 if len(cell.splitlines()) == 1:
3169 if len(cell.splitlines()) == 1:
3142 # Dynamic transformations - only applied for single line commands
3170 # Dynamic transformations - only applied for single line commands
3143 with self.builtin_trap:
3171 with self.builtin_trap:
3144 # use prefilter_lines to handle trailing newlines
3172 # use prefilter_lines to handle trailing newlines
3145 # restore trailing newline for ast.parse
3173 # restore trailing newline for ast.parse
3146 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3174 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3147
3175
3148 lines = cell.splitlines(keepends=True)
3176 lines = cell.splitlines(keepends=True)
3149 for transform in self.input_transformers_post:
3177 for transform in self.input_transformers_post:
3150 lines = transform(lines)
3178 lines = transform(lines)
3151 cell = ''.join(lines)
3179 cell = ''.join(lines)
3152
3180
3153 return cell
3181 return cell
3154
3182
3155 def transform_ast(self, node):
3183 def transform_ast(self, node):
3156 """Apply the AST transformations from self.ast_transformers
3184 """Apply the AST transformations from self.ast_transformers
3157
3185
3158 Parameters
3186 Parameters
3159 ----------
3187 ----------
3160 node : ast.Node
3188 node : ast.Node
3161 The root node to be transformed. Typically called with the ast.Module
3189 The root node to be transformed. Typically called with the ast.Module
3162 produced by parsing user input.
3190 produced by parsing user input.
3163
3191
3164 Returns
3192 Returns
3165 -------
3193 -------
3166 An ast.Node corresponding to the node it was called with. Note that it
3194 An ast.Node corresponding to the node it was called with. Note that it
3167 may also modify the passed object, so don't rely on references to the
3195 may also modify the passed object, so don't rely on references to the
3168 original AST.
3196 original AST.
3169 """
3197 """
3170 for transformer in self.ast_transformers:
3198 for transformer in self.ast_transformers:
3171 try:
3199 try:
3172 node = transformer.visit(node)
3200 node = transformer.visit(node)
3173 except InputRejected:
3201 except InputRejected:
3174 # User-supplied AST transformers can reject an input by raising
3202 # User-supplied AST transformers can reject an input by raising
3175 # an InputRejected. Short-circuit in this case so that we
3203 # an InputRejected. Short-circuit in this case so that we
3176 # don't unregister the transform.
3204 # don't unregister the transform.
3177 raise
3205 raise
3178 except Exception:
3206 except Exception:
3179 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3207 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3180 self.ast_transformers.remove(transformer)
3208 self.ast_transformers.remove(transformer)
3181
3209
3182 if self.ast_transformers:
3210 if self.ast_transformers:
3183 ast.fix_missing_locations(node)
3211 ast.fix_missing_locations(node)
3184 return node
3212 return node
3185
3213
3186 def _update_code_co_name(self, code):
3214 def _update_code_co_name(self, code):
3187 """Python 3.10 changed the behaviour so that whenever a code object
3215 """Python 3.10 changed the behaviour so that whenever a code object
3188 is assembled in the compile(ast) the co_firstlineno would be == 1.
3216 is assembled in the compile(ast) the co_firstlineno would be == 1.
3189
3217
3190 This makes pydevd/debugpy think that all cells invoked are the same
3218 This makes pydevd/debugpy think that all cells invoked are the same
3191 since it caches information based on (co_firstlineno, co_name, co_filename).
3219 since it caches information based on (co_firstlineno, co_name, co_filename).
3192
3220
3193 Given that, this function changes the code 'co_name' to be unique
3221 Given that, this function changes the code 'co_name' to be unique
3194 based on the first real lineno of the code (which also has a nice
3222 based on the first real lineno of the code (which also has a nice
3195 side effect of customizing the name so that it's not always <module>).
3223 side effect of customizing the name so that it's not always <module>).
3196
3224
3197 See: https://github.com/ipython/ipykernel/issues/841
3225 See: https://github.com/ipython/ipykernel/issues/841
3198 """
3226 """
3199 if not hasattr(code, "replace"):
3227 if not hasattr(code, "replace"):
3200 # It may not be available on older versions of Python (only
3228 # It may not be available on older versions of Python (only
3201 # available for 3.8 onwards).
3229 # available for 3.8 onwards).
3202 return code
3230 return code
3203 try:
3231 try:
3204 first_real_line = next(dis.findlinestarts(code))[1]
3232 first_real_line = next(dis.findlinestarts(code))[1]
3205 except StopIteration:
3233 except StopIteration:
3206 return code
3234 return code
3207 return code.replace(co_name="<cell line: %s>" % (first_real_line,))
3235 return code.replace(co_name="<cell line: %s>" % (first_real_line,))
3208
3236
3209 async def run_ast_nodes(
3237 async def run_ast_nodes(
3210 self,
3238 self,
3211 nodelist: ListType[stmt],
3239 nodelist: ListType[stmt],
3212 cell_name: str,
3240 cell_name: str,
3213 interactivity="last_expr",
3241 interactivity="last_expr",
3214 compiler=compile,
3242 compiler=compile,
3215 result=None,
3243 result=None,
3216 ):
3244 ):
3217 """Run a sequence of AST nodes. The execution mode depends on the
3245 """Run a sequence of AST nodes. The execution mode depends on the
3218 interactivity parameter.
3246 interactivity parameter.
3219
3247
3220 Parameters
3248 Parameters
3221 ----------
3249 ----------
3222 nodelist : list
3250 nodelist : list
3223 A sequence of AST nodes to run.
3251 A sequence of AST nodes to run.
3224 cell_name : str
3252 cell_name : str
3225 Will be passed to the compiler as the filename of the cell. Typically
3253 Will be passed to the compiler as the filename of the cell. Typically
3226 the value returned by ip.compile.cache(cell).
3254 the value returned by ip.compile.cache(cell).
3227 interactivity : str
3255 interactivity : str
3228 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3256 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3229 specifying which nodes should be run interactively (displaying output
3257 specifying which nodes should be run interactively (displaying output
3230 from expressions). 'last_expr' will run the last node interactively
3258 from expressions). 'last_expr' will run the last node interactively
3231 only if it is an expression (i.e. expressions in loops or other blocks
3259 only if it is an expression (i.e. expressions in loops or other blocks
3232 are not displayed) 'last_expr_or_assign' will run the last expression
3260 are not displayed) 'last_expr_or_assign' will run the last expression
3233 or the last assignment. Other values for this parameter will raise a
3261 or the last assignment. Other values for this parameter will raise a
3234 ValueError.
3262 ValueError.
3235
3263
3236 compiler : callable
3264 compiler : callable
3237 A function with the same interface as the built-in compile(), to turn
3265 A function with the same interface as the built-in compile(), to turn
3238 the AST nodes into code objects. Default is the built-in compile().
3266 the AST nodes into code objects. Default is the built-in compile().
3239 result : ExecutionResult, optional
3267 result : ExecutionResult, optional
3240 An object to store exceptions that occur during execution.
3268 An object to store exceptions that occur during execution.
3241
3269
3242 Returns
3270 Returns
3243 -------
3271 -------
3244 True if an exception occurred while running code, False if it finished
3272 True if an exception occurred while running code, False if it finished
3245 running.
3273 running.
3246 """
3274 """
3247 if not nodelist:
3275 if not nodelist:
3248 return
3276 return
3249
3277
3250
3278
3251 if interactivity == 'last_expr_or_assign':
3279 if interactivity == 'last_expr_or_assign':
3252 if isinstance(nodelist[-1], _assign_nodes):
3280 if isinstance(nodelist[-1], _assign_nodes):
3253 asg = nodelist[-1]
3281 asg = nodelist[-1]
3254 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3282 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3255 target = asg.targets[0]
3283 target = asg.targets[0]
3256 elif isinstance(asg, _single_targets_nodes):
3284 elif isinstance(asg, _single_targets_nodes):
3257 target = asg.target
3285 target = asg.target
3258 else:
3286 else:
3259 target = None
3287 target = None
3260 if isinstance(target, ast.Name):
3288 if isinstance(target, ast.Name):
3261 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3289 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3262 ast.fix_missing_locations(nnode)
3290 ast.fix_missing_locations(nnode)
3263 nodelist.append(nnode)
3291 nodelist.append(nnode)
3264 interactivity = 'last_expr'
3292 interactivity = 'last_expr'
3265
3293
3266 _async = False
3294 _async = False
3267 if interactivity == 'last_expr':
3295 if interactivity == 'last_expr':
3268 if isinstance(nodelist[-1], ast.Expr):
3296 if isinstance(nodelist[-1], ast.Expr):
3269 interactivity = "last"
3297 interactivity = "last"
3270 else:
3298 else:
3271 interactivity = "none"
3299 interactivity = "none"
3272
3300
3273 if interactivity == 'none':
3301 if interactivity == 'none':
3274 to_run_exec, to_run_interactive = nodelist, []
3302 to_run_exec, to_run_interactive = nodelist, []
3275 elif interactivity == 'last':
3303 elif interactivity == 'last':
3276 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3304 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3277 elif interactivity == 'all':
3305 elif interactivity == 'all':
3278 to_run_exec, to_run_interactive = [], nodelist
3306 to_run_exec, to_run_interactive = [], nodelist
3279 else:
3307 else:
3280 raise ValueError("Interactivity was %r" % interactivity)
3308 raise ValueError("Interactivity was %r" % interactivity)
3281
3309
3282 try:
3310 try:
3283
3311
3284 def compare(code):
3312 def compare(code):
3285 is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE
3313 is_async = inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE
3286 return is_async
3314 return is_async
3287
3315
3288 # refactor that to just change the mod constructor.
3316 # refactor that to just change the mod constructor.
3289 to_run = []
3317 to_run = []
3290 for node in to_run_exec:
3318 for node in to_run_exec:
3291 to_run.append((node, "exec"))
3319 to_run.append((node, "exec"))
3292
3320
3293 for node in to_run_interactive:
3321 for node in to_run_interactive:
3294 to_run.append((node, "single"))
3322 to_run.append((node, "single"))
3295
3323
3296 for node, mode in to_run:
3324 for node, mode in to_run:
3297 if mode == "exec":
3325 if mode == "exec":
3298 mod = Module([node], [])
3326 mod = Module([node], [])
3299 elif mode == "single":
3327 elif mode == "single":
3300 mod = ast.Interactive([node])
3328 mod = ast.Interactive([node])
3301 with compiler.extra_flags(
3329 with compiler.extra_flags(
3302 getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0)
3330 getattr(ast, "PyCF_ALLOW_TOP_LEVEL_AWAIT", 0x0)
3303 if self.autoawait
3331 if self.autoawait
3304 else 0x0
3332 else 0x0
3305 ):
3333 ):
3306 code = compiler(mod, cell_name, mode)
3334 code = compiler(mod, cell_name, mode)
3307 code = self._update_code_co_name(code)
3335 code = self._update_code_co_name(code)
3308 asy = compare(code)
3336 asy = compare(code)
3309 if await self.run_code(code, result, async_=asy):
3337 if await self.run_code(code, result, async_=asy):
3310 return True
3338 return True
3311
3339
3312 # Flush softspace
3340 # Flush softspace
3313 if softspace(sys.stdout, 0):
3341 if softspace(sys.stdout, 0):
3314 print()
3342 print()
3315
3343
3316 except:
3344 except:
3317 # It's possible to have exceptions raised here, typically by
3345 # It's possible to have exceptions raised here, typically by
3318 # compilation of odd code (such as a naked 'return' outside a
3346 # compilation of odd code (such as a naked 'return' outside a
3319 # function) that did parse but isn't valid. Typically the exception
3347 # function) that did parse but isn't valid. Typically the exception
3320 # is a SyntaxError, but it's safest just to catch anything and show
3348 # is a SyntaxError, but it's safest just to catch anything and show
3321 # the user a traceback.
3349 # the user a traceback.
3322
3350
3323 # We do only one try/except outside the loop to minimize the impact
3351 # We do only one try/except outside the loop to minimize the impact
3324 # on runtime, and also because if any node in the node list is
3352 # on runtime, and also because if any node in the node list is
3325 # broken, we should stop execution completely.
3353 # broken, we should stop execution completely.
3326 if result:
3354 if result:
3327 result.error_before_exec = sys.exc_info()[1]
3355 result.error_before_exec = sys.exc_info()[1]
3328 self.showtraceback()
3356 self.showtraceback()
3329 return True
3357 return True
3330
3358
3331 return False
3359 return False
3332
3360
3333 async def run_code(self, code_obj, result=None, *, async_=False):
3361 async def run_code(self, code_obj, result=None, *, async_=False):
3334 """Execute a code object.
3362 """Execute a code object.
3335
3363
3336 When an exception occurs, self.showtraceback() is called to display a
3364 When an exception occurs, self.showtraceback() is called to display a
3337 traceback.
3365 traceback.
3338
3366
3339 Parameters
3367 Parameters
3340 ----------
3368 ----------
3341 code_obj : code object
3369 code_obj : code object
3342 A compiled code object, to be executed
3370 A compiled code object, to be executed
3343 result : ExecutionResult, optional
3371 result : ExecutionResult, optional
3344 An object to store exceptions that occur during execution.
3372 An object to store exceptions that occur during execution.
3345 async_ : Bool (Experimental)
3373 async_ : Bool (Experimental)
3346 Attempt to run top-level asynchronous code in a default loop.
3374 Attempt to run top-level asynchronous code in a default loop.
3347
3375
3348 Returns
3376 Returns
3349 -------
3377 -------
3350 False : successful execution.
3378 False : successful execution.
3351 True : an error occurred.
3379 True : an error occurred.
3352 """
3380 """
3353 # special value to say that anything above is IPython and should be
3381 # special value to say that anything above is IPython and should be
3354 # hidden.
3382 # hidden.
3355 __tracebackhide__ = "__ipython_bottom__"
3383 __tracebackhide__ = "__ipython_bottom__"
3356 # Set our own excepthook in case the user code tries to call it
3384 # Set our own excepthook in case the user code tries to call it
3357 # directly, so that the IPython crash handler doesn't get triggered
3385 # directly, so that the IPython crash handler doesn't get triggered
3358 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3386 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3359
3387
3360 # we save the original sys.excepthook in the instance, in case config
3388 # we save the original sys.excepthook in the instance, in case config
3361 # code (such as magics) needs access to it.
3389 # code (such as magics) needs access to it.
3362 self.sys_excepthook = old_excepthook
3390 self.sys_excepthook = old_excepthook
3363 outflag = True # happens in more places, so it's easier as default
3391 outflag = True # happens in more places, so it's easier as default
3364 try:
3392 try:
3365 try:
3393 try:
3366 if async_:
3394 if async_:
3367 await eval(code_obj, self.user_global_ns, self.user_ns)
3395 await eval(code_obj, self.user_global_ns, self.user_ns)
3368 else:
3396 else:
3369 exec(code_obj, self.user_global_ns, self.user_ns)
3397 exec(code_obj, self.user_global_ns, self.user_ns)
3370 finally:
3398 finally:
3371 # Reset our crash handler in place
3399 # Reset our crash handler in place
3372 sys.excepthook = old_excepthook
3400 sys.excepthook = old_excepthook
3373 except SystemExit as e:
3401 except SystemExit as e:
3374 if result is not None:
3402 if result is not None:
3375 result.error_in_exec = e
3403 result.error_in_exec = e
3376 self.showtraceback(exception_only=True)
3404 self.showtraceback(exception_only=True)
3377 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3405 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3378 except self.custom_exceptions:
3406 except self.custom_exceptions:
3379 etype, value, tb = sys.exc_info()
3407 etype, value, tb = sys.exc_info()
3380 if result is not None:
3408 if result is not None:
3381 result.error_in_exec = value
3409 result.error_in_exec = value
3382 self.CustomTB(etype, value, tb)
3410 self.CustomTB(etype, value, tb)
3383 except:
3411 except:
3384 if result is not None:
3412 if result is not None:
3385 result.error_in_exec = sys.exc_info()[1]
3413 result.error_in_exec = sys.exc_info()[1]
3386 self.showtraceback(running_compiled_code=True)
3414 self.showtraceback(running_compiled_code=True)
3387 else:
3415 else:
3388 outflag = False
3416 outflag = False
3389 return outflag
3417 return outflag
3390
3418
3391 # For backwards compatibility
3419 # For backwards compatibility
3392 runcode = run_code
3420 runcode = run_code
3393
3421
3394 def check_complete(self, code: str) -> Tuple[str, str]:
3422 def check_complete(self, code: str) -> Tuple[str, str]:
3395 """Return whether a block of code is ready to execute, or should be continued
3423 """Return whether a block of code is ready to execute, or should be continued
3396
3424
3397 Parameters
3425 Parameters
3398 ----------
3426 ----------
3399 code : string
3427 code : string
3400 Python input code, which can be multiline.
3428 Python input code, which can be multiline.
3401
3429
3402 Returns
3430 Returns
3403 -------
3431 -------
3404 status : str
3432 status : str
3405 One of 'complete', 'incomplete', or 'invalid' if source is not a
3433 One of 'complete', 'incomplete', or 'invalid' if source is not a
3406 prefix of valid code.
3434 prefix of valid code.
3407 indent : str
3435 indent : str
3408 When status is 'incomplete', this is some whitespace to insert on
3436 When status is 'incomplete', this is some whitespace to insert on
3409 the next line of the prompt.
3437 the next line of the prompt.
3410 """
3438 """
3411 status, nspaces = self.input_transformer_manager.check_complete(code)
3439 status, nspaces = self.input_transformer_manager.check_complete(code)
3412 return status, ' ' * (nspaces or 0)
3440 return status, ' ' * (nspaces or 0)
3413
3441
3414 #-------------------------------------------------------------------------
3442 #-------------------------------------------------------------------------
3415 # Things related to GUI support and pylab
3443 # Things related to GUI support and pylab
3416 #-------------------------------------------------------------------------
3444 #-------------------------------------------------------------------------
3417
3445
3418 active_eventloop = None
3446 active_eventloop = None
3419
3447
3420 def enable_gui(self, gui=None):
3448 def enable_gui(self, gui=None):
3421 raise NotImplementedError('Implement enable_gui in a subclass')
3449 raise NotImplementedError('Implement enable_gui in a subclass')
3422
3450
3423 def enable_matplotlib(self, gui=None):
3451 def enable_matplotlib(self, gui=None):
3424 """Enable interactive matplotlib and inline figure support.
3452 """Enable interactive matplotlib and inline figure support.
3425
3453
3426 This takes the following steps:
3454 This takes the following steps:
3427
3455
3428 1. select the appropriate eventloop and matplotlib backend
3456 1. select the appropriate eventloop and matplotlib backend
3429 2. set up matplotlib for interactive use with that backend
3457 2. set up matplotlib for interactive use with that backend
3430 3. configure formatters for inline figure display
3458 3. configure formatters for inline figure display
3431 4. enable the selected gui eventloop
3459 4. enable the selected gui eventloop
3432
3460
3433 Parameters
3461 Parameters
3434 ----------
3462 ----------
3435 gui : optional, string
3463 gui : optional, string
3436 If given, dictates the choice of matplotlib GUI backend to use
3464 If given, dictates the choice of matplotlib GUI backend to use
3437 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3465 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3438 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3466 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3439 matplotlib (as dictated by the matplotlib build-time options plus the
3467 matplotlib (as dictated by the matplotlib build-time options plus the
3440 user's matplotlibrc configuration file). Note that not all backends
3468 user's matplotlibrc configuration file). Note that not all backends
3441 make sense in all contexts, for example a terminal ipython can't
3469 make sense in all contexts, for example a terminal ipython can't
3442 display figures inline.
3470 display figures inline.
3443 """
3471 """
3444 from matplotlib_inline.backend_inline import configure_inline_support
3472 from matplotlib_inline.backend_inline import configure_inline_support
3445
3473
3446 from IPython.core import pylabtools as pt
3474 from IPython.core import pylabtools as pt
3447 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3475 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3448
3476
3449 if gui != 'inline':
3477 if gui != 'inline':
3450 # If we have our first gui selection, store it
3478 # If we have our first gui selection, store it
3451 if self.pylab_gui_select is None:
3479 if self.pylab_gui_select is None:
3452 self.pylab_gui_select = gui
3480 self.pylab_gui_select = gui
3453 # Otherwise if they are different
3481 # Otherwise if they are different
3454 elif gui != self.pylab_gui_select:
3482 elif gui != self.pylab_gui_select:
3455 print('Warning: Cannot change to a different GUI toolkit: %s.'
3483 print('Warning: Cannot change to a different GUI toolkit: %s.'
3456 ' Using %s instead.' % (gui, self.pylab_gui_select))
3484 ' Using %s instead.' % (gui, self.pylab_gui_select))
3457 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3485 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3458
3486
3459 pt.activate_matplotlib(backend)
3487 pt.activate_matplotlib(backend)
3460 configure_inline_support(self, backend)
3488 configure_inline_support(self, backend)
3461
3489
3462 # Now we must activate the gui pylab wants to use, and fix %run to take
3490 # Now we must activate the gui pylab wants to use, and fix %run to take
3463 # plot updates into account
3491 # plot updates into account
3464 self.enable_gui(gui)
3492 self.enable_gui(gui)
3465 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3493 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3466 pt.mpl_runner(self.safe_execfile)
3494 pt.mpl_runner(self.safe_execfile)
3467
3495
3468 return gui, backend
3496 return gui, backend
3469
3497
3470 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3498 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3471 """Activate pylab support at runtime.
3499 """Activate pylab support at runtime.
3472
3500
3473 This turns on support for matplotlib, preloads into the interactive
3501 This turns on support for matplotlib, preloads into the interactive
3474 namespace all of numpy and pylab, and configures IPython to correctly
3502 namespace all of numpy and pylab, and configures IPython to correctly
3475 interact with the GUI event loop. The GUI backend to be used can be
3503 interact with the GUI event loop. The GUI backend to be used can be
3476 optionally selected with the optional ``gui`` argument.
3504 optionally selected with the optional ``gui`` argument.
3477
3505
3478 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3506 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3479
3507
3480 Parameters
3508 Parameters
3481 ----------
3509 ----------
3482 gui : optional, string
3510 gui : optional, string
3483 If given, dictates the choice of matplotlib GUI backend to use
3511 If given, dictates the choice of matplotlib GUI backend to use
3484 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3512 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3485 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3513 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3486 matplotlib (as dictated by the matplotlib build-time options plus the
3514 matplotlib (as dictated by the matplotlib build-time options plus the
3487 user's matplotlibrc configuration file). Note that not all backends
3515 user's matplotlibrc configuration file). Note that not all backends
3488 make sense in all contexts, for example a terminal ipython can't
3516 make sense in all contexts, for example a terminal ipython can't
3489 display figures inline.
3517 display figures inline.
3490 import_all : optional, bool, default: True
3518 import_all : optional, bool, default: True
3491 Whether to do `from numpy import *` and `from pylab import *`
3519 Whether to do `from numpy import *` and `from pylab import *`
3492 in addition to module imports.
3520 in addition to module imports.
3493 welcome_message : deprecated
3521 welcome_message : deprecated
3494 This argument is ignored, no welcome message will be displayed.
3522 This argument is ignored, no welcome message will be displayed.
3495 """
3523 """
3496 from IPython.core.pylabtools import import_pylab
3524 from IPython.core.pylabtools import import_pylab
3497
3525
3498 gui, backend = self.enable_matplotlib(gui)
3526 gui, backend = self.enable_matplotlib(gui)
3499
3527
3500 # We want to prevent the loading of pylab to pollute the user's
3528 # We want to prevent the loading of pylab to pollute the user's
3501 # namespace as shown by the %who* magics, so we execute the activation
3529 # namespace as shown by the %who* magics, so we execute the activation
3502 # code in an empty namespace, and we update *both* user_ns and
3530 # code in an empty namespace, and we update *both* user_ns and
3503 # user_ns_hidden with this information.
3531 # user_ns_hidden with this information.
3504 ns = {}
3532 ns = {}
3505 import_pylab(ns, import_all)
3533 import_pylab(ns, import_all)
3506 # warn about clobbered names
3534 # warn about clobbered names
3507 ignored = {"__builtins__"}
3535 ignored = {"__builtins__"}
3508 both = set(ns).intersection(self.user_ns).difference(ignored)
3536 both = set(ns).intersection(self.user_ns).difference(ignored)
3509 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3537 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3510 self.user_ns.update(ns)
3538 self.user_ns.update(ns)
3511 self.user_ns_hidden.update(ns)
3539 self.user_ns_hidden.update(ns)
3512 return gui, backend, clobbered
3540 return gui, backend, clobbered
3513
3541
3514 #-------------------------------------------------------------------------
3542 #-------------------------------------------------------------------------
3515 # Utilities
3543 # Utilities
3516 #-------------------------------------------------------------------------
3544 #-------------------------------------------------------------------------
3517
3545
3518 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3546 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3519 """Expand python variables in a string.
3547 """Expand python variables in a string.
3520
3548
3521 The depth argument indicates how many frames above the caller should
3549 The depth argument indicates how many frames above the caller should
3522 be walked to look for the local namespace where to expand variables.
3550 be walked to look for the local namespace where to expand variables.
3523
3551
3524 The global namespace for expansion is always the user's interactive
3552 The global namespace for expansion is always the user's interactive
3525 namespace.
3553 namespace.
3526 """
3554 """
3527 ns = self.user_ns.copy()
3555 ns = self.user_ns.copy()
3528 try:
3556 try:
3529 frame = sys._getframe(depth+1)
3557 frame = sys._getframe(depth+1)
3530 except ValueError:
3558 except ValueError:
3531 # This is thrown if there aren't that many frames on the stack,
3559 # This is thrown if there aren't that many frames on the stack,
3532 # e.g. if a script called run_line_magic() directly.
3560 # e.g. if a script called run_line_magic() directly.
3533 pass
3561 pass
3534 else:
3562 else:
3535 ns.update(frame.f_locals)
3563 ns.update(frame.f_locals)
3536
3564
3537 try:
3565 try:
3538 # We have to use .vformat() here, because 'self' is a valid and common
3566 # We have to use .vformat() here, because 'self' is a valid and common
3539 # name, and expanding **ns for .format() would make it collide with
3567 # name, and expanding **ns for .format() would make it collide with
3540 # the 'self' argument of the method.
3568 # the 'self' argument of the method.
3541 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3569 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3542 except Exception:
3570 except Exception:
3543 # if formatter couldn't format, just let it go untransformed
3571 # if formatter couldn't format, just let it go untransformed
3544 pass
3572 pass
3545 return cmd
3573 return cmd
3546
3574
3547 def mktempfile(self, data=None, prefix='ipython_edit_'):
3575 def mktempfile(self, data=None, prefix='ipython_edit_'):
3548 """Make a new tempfile and return its filename.
3576 """Make a new tempfile and return its filename.
3549
3577
3550 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3578 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3551 but it registers the created filename internally so ipython cleans it up
3579 but it registers the created filename internally so ipython cleans it up
3552 at exit time.
3580 at exit time.
3553
3581
3554 Optional inputs:
3582 Optional inputs:
3555
3583
3556 - data(None): if data is given, it gets written out to the temp file
3584 - data(None): if data is given, it gets written out to the temp file
3557 immediately, and the file is closed again."""
3585 immediately, and the file is closed again."""
3558
3586
3559 dir_path = Path(tempfile.mkdtemp(prefix=prefix))
3587 dir_path = Path(tempfile.mkdtemp(prefix=prefix))
3560 self.tempdirs.append(dir_path)
3588 self.tempdirs.append(dir_path)
3561
3589
3562 handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path))
3590 handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path))
3563 os.close(handle) # On Windows, there can only be one open handle on a file
3591 os.close(handle) # On Windows, there can only be one open handle on a file
3564
3592
3565 file_path = Path(filename)
3593 file_path = Path(filename)
3566 self.tempfiles.append(file_path)
3594 self.tempfiles.append(file_path)
3567
3595
3568 if data:
3596 if data:
3569 file_path.write_text(data, encoding="utf-8")
3597 file_path.write_text(data, encoding="utf-8")
3570 return filename
3598 return filename
3571
3599
3572 def ask_yes_no(self, prompt, default=None, interrupt=None):
3600 def ask_yes_no(self, prompt, default=None, interrupt=None):
3573 if self.quiet:
3601 if self.quiet:
3574 return True
3602 return True
3575 return ask_yes_no(prompt,default,interrupt)
3603 return ask_yes_no(prompt,default,interrupt)
3576
3604
3577 def show_usage(self):
3605 def show_usage(self):
3578 """Show a usage message"""
3606 """Show a usage message"""
3579 page.page(IPython.core.usage.interactive_usage)
3607 page.page(IPython.core.usage.interactive_usage)
3580
3608
3581 def extract_input_lines(self, range_str, raw=False):
3609 def extract_input_lines(self, range_str, raw=False):
3582 """Return as a string a set of input history slices.
3610 """Return as a string a set of input history slices.
3583
3611
3584 Parameters
3612 Parameters
3585 ----------
3613 ----------
3586 range_str : str
3614 range_str : str
3587 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3615 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3588 since this function is for use by magic functions which get their
3616 since this function is for use by magic functions which get their
3589 arguments as strings. The number before the / is the session
3617 arguments as strings. The number before the / is the session
3590 number: ~n goes n back from the current session.
3618 number: ~n goes n back from the current session.
3591
3619
3592 If empty string is given, returns history of current session
3620 If empty string is given, returns history of current session
3593 without the last input.
3621 without the last input.
3594
3622
3595 raw : bool, optional
3623 raw : bool, optional
3596 By default, the processed input is used. If this is true, the raw
3624 By default, the processed input is used. If this is true, the raw
3597 input history is used instead.
3625 input history is used instead.
3598
3626
3599 Notes
3627 Notes
3600 -----
3628 -----
3601 Slices can be described with two notations:
3629 Slices can be described with two notations:
3602
3630
3603 * ``N:M`` -> standard python form, means including items N...(M-1).
3631 * ``N:M`` -> standard python form, means including items N...(M-1).
3604 * ``N-M`` -> include items N..M (closed endpoint).
3632 * ``N-M`` -> include items N..M (closed endpoint).
3605 """
3633 """
3606 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3634 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3607 text = "\n".join(x for _, _, x in lines)
3635 text = "\n".join(x for _, _, x in lines)
3608
3636
3609 # Skip the last line, as it's probably the magic that called this
3637 # Skip the last line, as it's probably the magic that called this
3610 if not range_str:
3638 if not range_str:
3611 if "\n" not in text:
3639 if "\n" not in text:
3612 text = ""
3640 text = ""
3613 else:
3641 else:
3614 text = text[: text.rfind("\n")]
3642 text = text[: text.rfind("\n")]
3615
3643
3616 return text
3644 return text
3617
3645
3618 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3646 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3619 """Get a code string from history, file, url, or a string or macro.
3647 """Get a code string from history, file, url, or a string or macro.
3620
3648
3621 This is mainly used by magic functions.
3649 This is mainly used by magic functions.
3622
3650
3623 Parameters
3651 Parameters
3624 ----------
3652 ----------
3625 target : str
3653 target : str
3626 A string specifying code to retrieve. This will be tried respectively
3654 A string specifying code to retrieve. This will be tried respectively
3627 as: ranges of input history (see %history for syntax), url,
3655 as: ranges of input history (see %history for syntax), url,
3628 corresponding .py file, filename, or an expression evaluating to a
3656 corresponding .py file, filename, or an expression evaluating to a
3629 string or Macro in the user namespace.
3657 string or Macro in the user namespace.
3630
3658
3631 If empty string is given, returns complete history of current
3659 If empty string is given, returns complete history of current
3632 session, without the last line.
3660 session, without the last line.
3633
3661
3634 raw : bool
3662 raw : bool
3635 If true (default), retrieve raw history. Has no effect on the other
3663 If true (default), retrieve raw history. Has no effect on the other
3636 retrieval mechanisms.
3664 retrieval mechanisms.
3637
3665
3638 py_only : bool (default False)
3666 py_only : bool (default False)
3639 Only try to fetch python code, do not try alternative methods to decode file
3667 Only try to fetch python code, do not try alternative methods to decode file
3640 if unicode fails.
3668 if unicode fails.
3641
3669
3642 Returns
3670 Returns
3643 -------
3671 -------
3644 A string of code.
3672 A string of code.
3645 ValueError is raised if nothing is found, and TypeError if it evaluates
3673 ValueError is raised if nothing is found, and TypeError if it evaluates
3646 to an object of another type. In each case, .args[0] is a printable
3674 to an object of another type. In each case, .args[0] is a printable
3647 message.
3675 message.
3648 """
3676 """
3649 code = self.extract_input_lines(target, raw=raw) # Grab history
3677 code = self.extract_input_lines(target, raw=raw) # Grab history
3650 if code:
3678 if code:
3651 return code
3679 return code
3652 try:
3680 try:
3653 if target.startswith(('http://', 'https://')):
3681 if target.startswith(('http://', 'https://')):
3654 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3682 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3655 except UnicodeDecodeError as e:
3683 except UnicodeDecodeError as e:
3656 if not py_only :
3684 if not py_only :
3657 # Deferred import
3685 # Deferred import
3658 from urllib.request import urlopen
3686 from urllib.request import urlopen
3659 response = urlopen(target)
3687 response = urlopen(target)
3660 return response.read().decode('latin1')
3688 return response.read().decode('latin1')
3661 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3689 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3662
3690
3663 potential_target = [target]
3691 potential_target = [target]
3664 try :
3692 try :
3665 potential_target.insert(0,get_py_filename(target))
3693 potential_target.insert(0,get_py_filename(target))
3666 except IOError:
3694 except IOError:
3667 pass
3695 pass
3668
3696
3669 for tgt in potential_target :
3697 for tgt in potential_target :
3670 if os.path.isfile(tgt): # Read file
3698 if os.path.isfile(tgt): # Read file
3671 try :
3699 try :
3672 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3700 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3673 except UnicodeDecodeError as e:
3701 except UnicodeDecodeError as e:
3674 if not py_only :
3702 if not py_only :
3675 with io_open(tgt,'r', encoding='latin1') as f :
3703 with io_open(tgt,'r', encoding='latin1') as f :
3676 return f.read()
3704 return f.read()
3677 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3705 raise ValueError(("'%s' seem to be unreadable.") % target) from e
3678 elif os.path.isdir(os.path.expanduser(tgt)):
3706 elif os.path.isdir(os.path.expanduser(tgt)):
3679 raise ValueError("'%s' is a directory, not a regular file." % target)
3707 raise ValueError("'%s' is a directory, not a regular file." % target)
3680
3708
3681 if search_ns:
3709 if search_ns:
3682 # Inspect namespace to load object source
3710 # Inspect namespace to load object source
3683 object_info = self.object_inspect(target, detail_level=1)
3711 object_info = self.object_inspect(target, detail_level=1)
3684 if object_info['found'] and object_info['source']:
3712 if object_info['found'] and object_info['source']:
3685 return object_info['source']
3713 return object_info['source']
3686
3714
3687 try: # User namespace
3715 try: # User namespace
3688 codeobj = eval(target, self.user_ns)
3716 codeobj = eval(target, self.user_ns)
3689 except Exception as e:
3717 except Exception as e:
3690 raise ValueError(("'%s' was not found in history, as a file, url, "
3718 raise ValueError(("'%s' was not found in history, as a file, url, "
3691 "nor in the user namespace.") % target) from e
3719 "nor in the user namespace.") % target) from e
3692
3720
3693 if isinstance(codeobj, str):
3721 if isinstance(codeobj, str):
3694 return codeobj
3722 return codeobj
3695 elif isinstance(codeobj, Macro):
3723 elif isinstance(codeobj, Macro):
3696 return codeobj.value
3724 return codeobj.value
3697
3725
3698 raise TypeError("%s is neither a string nor a macro." % target,
3726 raise TypeError("%s is neither a string nor a macro." % target,
3699 codeobj)
3727 codeobj)
3700
3728
3701 def _atexit_once(self):
3729 def _atexit_once(self):
3702 """
3730 """
3703 At exist operation that need to be called at most once.
3731 At exist operation that need to be called at most once.
3704 Second call to this function per instance will do nothing.
3732 Second call to this function per instance will do nothing.
3705 """
3733 """
3706
3734
3707 if not getattr(self, "_atexit_once_called", False):
3735 if not getattr(self, "_atexit_once_called", False):
3708 self._atexit_once_called = True
3736 self._atexit_once_called = True
3709 # Clear all user namespaces to release all references cleanly.
3737 # Clear all user namespaces to release all references cleanly.
3710 self.reset(new_session=False)
3738 self.reset(new_session=False)
3711 # Close the history session (this stores the end time and line count)
3739 # Close the history session (this stores the end time and line count)
3712 # this must be *before* the tempfile cleanup, in case of temporary
3740 # this must be *before* the tempfile cleanup, in case of temporary
3713 # history db
3741 # history db
3714 self.history_manager.end_session()
3742 self.history_manager.end_session()
3715 self.history_manager = None
3743 self.history_manager = None
3716
3744
3717 #-------------------------------------------------------------------------
3745 #-------------------------------------------------------------------------
3718 # Things related to IPython exiting
3746 # Things related to IPython exiting
3719 #-------------------------------------------------------------------------
3747 #-------------------------------------------------------------------------
3720 def atexit_operations(self):
3748 def atexit_operations(self):
3721 """This will be executed at the time of exit.
3749 """This will be executed at the time of exit.
3722
3750
3723 Cleanup operations and saving of persistent data that is done
3751 Cleanup operations and saving of persistent data that is done
3724 unconditionally by IPython should be performed here.
3752 unconditionally by IPython should be performed here.
3725
3753
3726 For things that may depend on startup flags or platform specifics (such
3754 For things that may depend on startup flags or platform specifics (such
3727 as having readline or not), register a separate atexit function in the
3755 as having readline or not), register a separate atexit function in the
3728 code that has the appropriate information, rather than trying to
3756 code that has the appropriate information, rather than trying to
3729 clutter
3757 clutter
3730 """
3758 """
3731 self._atexit_once()
3759 self._atexit_once()
3732
3760
3733 # Cleanup all tempfiles and folders left around
3761 # Cleanup all tempfiles and folders left around
3734 for tfile in self.tempfiles:
3762 for tfile in self.tempfiles:
3735 try:
3763 try:
3736 tfile.unlink()
3764 tfile.unlink()
3737 self.tempfiles.remove(tfile)
3765 self.tempfiles.remove(tfile)
3738 except FileNotFoundError:
3766 except FileNotFoundError:
3739 pass
3767 pass
3740 del self.tempfiles
3768 del self.tempfiles
3741 for tdir in self.tempdirs:
3769 for tdir in self.tempdirs:
3742 try:
3770 try:
3743 tdir.rmdir()
3771 tdir.rmdir()
3744 self.tempdirs.remove(tdir)
3772 self.tempdirs.remove(tdir)
3745 except FileNotFoundError:
3773 except FileNotFoundError:
3746 pass
3774 pass
3747 del self.tempdirs
3775 del self.tempdirs
3748
3776
3749 # Restore user's cursor
3777 # Restore user's cursor
3750 if hasattr(self, "editing_mode") and self.editing_mode == "vi":
3778 if hasattr(self, "editing_mode") and self.editing_mode == "vi":
3751 sys.stdout.write("\x1b[0 q")
3779 sys.stdout.write("\x1b[0 q")
3752 sys.stdout.flush()
3780 sys.stdout.flush()
3753
3781
3754 def cleanup(self):
3782 def cleanup(self):
3755 self.restore_sys_module_state()
3783 self.restore_sys_module_state()
3756
3784
3757
3785
3758 # Overridden in terminal subclass to change prompts
3786 # Overridden in terminal subclass to change prompts
3759 def switch_doctest_mode(self, mode):
3787 def switch_doctest_mode(self, mode):
3760 pass
3788 pass
3761
3789
3762
3790
3763 class InteractiveShellABC(metaclass=abc.ABCMeta):
3791 class InteractiveShellABC(metaclass=abc.ABCMeta):
3764 """An abstract base class for InteractiveShell."""
3792 """An abstract base class for InteractiveShell."""
3765
3793
3766 InteractiveShellABC.register(InteractiveShell)
3794 InteractiveShellABC.register(InteractiveShell)
@@ -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()
General Comments 0
You need to be logged in to leave comments. Login now