##// END OF EJS Templates
Merge pull request #13628 from Carreau/auto-backport-of-pr-13600-on-7.x...
Matthias Bussonnier -
r27631:c3f199f9 merge
parent child Browse files
Show More
@@ -1,2117 +1,2117 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 warnings
124 import warnings
125 from contextlib import contextmanager
125 from contextlib import contextmanager
126 from importlib import import_module
126 from importlib import import_module
127 from types import SimpleNamespace
127 from types import SimpleNamespace
128 from typing import Iterable, Iterator, List, Tuple
128 from typing import Iterable, Iterator, List, Tuple
129
129
130 from IPython.core.error import TryNext
130 from IPython.core.error import TryNext
131 from IPython.core.inputtransformer2 import ESC_MAGIC
131 from IPython.core.inputtransformer2 import ESC_MAGIC
132 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
132 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
133 from IPython.core.oinspect import InspectColors
133 from IPython.core.oinspect import InspectColors
134 from IPython.utils import generics
134 from IPython.utils import generics
135 from IPython.utils.dir2 import dir2, get_real_method
135 from IPython.utils.dir2 import dir2, get_real_method
136 from IPython.utils.process import arg_split
136 from IPython.utils.process import arg_split
137 from traitlets import Bool, Enum, Int, observe
137 from traitlets import Bool, Enum, Int, observe
138 from traitlets.config.configurable import Configurable
138 from traitlets.config.configurable import Configurable
139
139
140 import __main__
140 import __main__
141
141
142 # skip module docstests
142 # skip module docstests
143 skip_doctest = True
143 skip_doctest = True
144
144
145 try:
145 try:
146 import jedi
146 import jedi
147 jedi.settings.case_insensitive_completion = False
147 jedi.settings.case_insensitive_completion = False
148 import jedi.api.helpers
148 import jedi.api.helpers
149 import jedi.api.classes
149 import jedi.api.classes
150 JEDI_INSTALLED = True
150 JEDI_INSTALLED = True
151 except ImportError:
151 except ImportError:
152 JEDI_INSTALLED = False
152 JEDI_INSTALLED = False
153 #-----------------------------------------------------------------------------
153 #-----------------------------------------------------------------------------
154 # Globals
154 # Globals
155 #-----------------------------------------------------------------------------
155 #-----------------------------------------------------------------------------
156
156
157 # Public API
157 # Public API
158 __all__ = ['Completer','IPCompleter']
158 __all__ = ['Completer','IPCompleter']
159
159
160 if sys.platform == 'win32':
160 if sys.platform == 'win32':
161 PROTECTABLES = ' '
161 PROTECTABLES = ' '
162 else:
162 else:
163 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
163 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
164
164
165 # Protect against returning an enormous number of completions which the frontend
165 # Protect against returning an enormous number of completions which the frontend
166 # may have trouble processing.
166 # may have trouble processing.
167 MATCHES_LIMIT = 500
167 MATCHES_LIMIT = 500
168
168
169
169
170 class Sentinel:
170 class Sentinel:
171 def __repr__(self):
171 def __repr__(self):
172 return "<deprecated sentinel>"
172 return "<deprecated sentinel>"
173
173
174
174
175 _deprecation_readline_sentinel = Sentinel()
175 _deprecation_readline_sentinel = Sentinel()
176
176
177
177
178 class ProvisionalCompleterWarning(FutureWarning):
178 class ProvisionalCompleterWarning(FutureWarning):
179 """
179 """
180 Exception raise by an experimental feature in this module.
180 Exception raise by an experimental feature in this module.
181
181
182 Wrap code in :any:`provisionalcompleter` context manager if you
182 Wrap code in :any:`provisionalcompleter` context manager if you
183 are certain you want to use an unstable feature.
183 are certain you want to use an unstable feature.
184 """
184 """
185 pass
185 pass
186
186
187 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
187 warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
188
188
189 @contextmanager
189 @contextmanager
190 def provisionalcompleter(action='ignore'):
190 def provisionalcompleter(action='ignore'):
191 """
191 """
192
192
193
193
194 This context manager has to be used in any place where unstable completer
194 This context manager has to be used in any place where unstable completer
195 behavior and API may be called.
195 behavior and API may be called.
196
196
197 >>> with provisionalcompleter():
197 >>> with provisionalcompleter():
198 ... completer.do_experimental_things() # works
198 ... completer.do_experimental_things() # works
199
199
200 >>> completer.do_experimental_things() # raises.
200 >>> completer.do_experimental_things() # raises.
201
201
202 .. note::
202 .. note::
203
203
204 Unstable
204 Unstable
205
205
206 By using this context manager you agree that the API in use may change
206 By using this context manager you agree that the API in use may change
207 without warning, and that you won't complain if they do so.
207 without warning, and that you won't complain if they do so.
208
208
209 You also understand that, if the API is not to your liking, you should report
209 You also understand that, if the API is not to your liking, you should report
210 a bug to explain your use case upstream.
210 a bug to explain your use case upstream.
211
211
212 We'll be happy to get your feedback, feature requests, and improvements on
212 We'll be happy to get your feedback, feature requests, and improvements on
213 any of the unstable APIs!
213 any of the unstable APIs!
214 """
214 """
215 with warnings.catch_warnings():
215 with warnings.catch_warnings():
216 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
216 warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
217 yield
217 yield
218
218
219
219
220 def has_open_quotes(s):
220 def has_open_quotes(s):
221 """Return whether a string has open quotes.
221 """Return whether a string has open quotes.
222
222
223 This simply counts whether the number of quote characters of either type in
223 This simply counts whether the number of quote characters of either type in
224 the string is odd.
224 the string is odd.
225
225
226 Returns
226 Returns
227 -------
227 -------
228 If there is an open quote, the quote character is returned. Else, return
228 If there is an open quote, the quote character is returned. Else, return
229 False.
229 False.
230 """
230 """
231 # We check " first, then ', so complex cases with nested quotes will get
231 # We check " first, then ', so complex cases with nested quotes will get
232 # the " to take precedence.
232 # the " to take precedence.
233 if s.count('"') % 2:
233 if s.count('"') % 2:
234 return '"'
234 return '"'
235 elif s.count("'") % 2:
235 elif s.count("'") % 2:
236 return "'"
236 return "'"
237 else:
237 else:
238 return False
238 return False
239
239
240
240
241 def protect_filename(s, protectables=PROTECTABLES):
241 def protect_filename(s, protectables=PROTECTABLES):
242 """Escape a string to protect certain characters."""
242 """Escape a string to protect certain characters."""
243 if set(s) & set(protectables):
243 if set(s) & set(protectables):
244 if sys.platform == "win32":
244 if sys.platform == "win32":
245 return '"' + s + '"'
245 return '"' + s + '"'
246 else:
246 else:
247 return "".join(("\\" + c if c in protectables else c) for c in s)
247 return "".join(("\\" + c if c in protectables else c) for c in s)
248 else:
248 else:
249 return s
249 return s
250
250
251
251
252 def expand_user(path:str) -> Tuple[str, bool, str]:
252 def expand_user(path:str) -> Tuple[str, bool, str]:
253 """Expand ``~``-style usernames in strings.
253 """Expand ``~``-style usernames in strings.
254
254
255 This is similar to :func:`os.path.expanduser`, but it computes and returns
255 This is similar to :func:`os.path.expanduser`, but it computes and returns
256 extra information that will be useful if the input was being used in
256 extra information that will be useful if the input was being used in
257 computing completions, and you wish to return the completions with the
257 computing completions, and you wish to return the completions with the
258 original '~' instead of its expanded value.
258 original '~' instead of its expanded value.
259
259
260 Parameters
260 Parameters
261 ----------
261 ----------
262 path : str
262 path : str
263 String to be expanded. If no ~ is present, the output is the same as the
263 String to be expanded. If no ~ is present, the output is the same as the
264 input.
264 input.
265
265
266 Returns
266 Returns
267 -------
267 -------
268 newpath : str
268 newpath : str
269 Result of ~ expansion in the input path.
269 Result of ~ expansion in the input path.
270 tilde_expand : bool
270 tilde_expand : bool
271 Whether any expansion was performed or not.
271 Whether any expansion was performed or not.
272 tilde_val : str
272 tilde_val : str
273 The value that ~ was replaced with.
273 The value that ~ was replaced with.
274 """
274 """
275 # Default values
275 # Default values
276 tilde_expand = False
276 tilde_expand = False
277 tilde_val = ''
277 tilde_val = ''
278 newpath = path
278 newpath = path
279
279
280 if path.startswith('~'):
280 if path.startswith('~'):
281 tilde_expand = True
281 tilde_expand = True
282 rest = len(path)-1
282 rest = len(path)-1
283 newpath = os.path.expanduser(path)
283 newpath = os.path.expanduser(path)
284 if rest:
284 if rest:
285 tilde_val = newpath[:-rest]
285 tilde_val = newpath[:-rest]
286 else:
286 else:
287 tilde_val = newpath
287 tilde_val = newpath
288
288
289 return newpath, tilde_expand, tilde_val
289 return newpath, tilde_expand, tilde_val
290
290
291
291
292 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
292 def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
293 """Does the opposite of expand_user, with its outputs.
293 """Does the opposite of expand_user, with its outputs.
294 """
294 """
295 if tilde_expand:
295 if tilde_expand:
296 return path.replace(tilde_val, '~')
296 return path.replace(tilde_val, '~')
297 else:
297 else:
298 return path
298 return path
299
299
300
300
301 def completions_sorting_key(word):
301 def completions_sorting_key(word):
302 """key for sorting completions
302 """key for sorting completions
303
303
304 This does several things:
304 This does several things:
305
305
306 - Demote any completions starting with underscores to the end
306 - Demote any completions starting with underscores to the end
307 - Insert any %magic and %%cellmagic completions in the alphabetical order
307 - Insert any %magic and %%cellmagic completions in the alphabetical order
308 by their name
308 by their name
309 """
309 """
310 prio1, prio2 = 0, 0
310 prio1, prio2 = 0, 0
311
311
312 if word.startswith('__'):
312 if word.startswith('__'):
313 prio1 = 2
313 prio1 = 2
314 elif word.startswith('_'):
314 elif word.startswith('_'):
315 prio1 = 1
315 prio1 = 1
316
316
317 if word.endswith('='):
317 if word.endswith('='):
318 prio1 = -1
318 prio1 = -1
319
319
320 if word.startswith('%%'):
320 if word.startswith('%%'):
321 # If there's another % in there, this is something else, so leave it alone
321 # If there's another % in there, this is something else, so leave it alone
322 if not "%" in word[2:]:
322 if not "%" in word[2:]:
323 word = word[2:]
323 word = word[2:]
324 prio2 = 2
324 prio2 = 2
325 elif word.startswith('%'):
325 elif word.startswith('%'):
326 if not "%" in word[1:]:
326 if not "%" in word[1:]:
327 word = word[1:]
327 word = word[1:]
328 prio2 = 1
328 prio2 = 1
329
329
330 return prio1, word, prio2
330 return prio1, word, prio2
331
331
332
332
333 class _FakeJediCompletion:
333 class _FakeJediCompletion:
334 """
334 """
335 This is a workaround to communicate to the UI that Jedi has crashed and to
335 This is a workaround to communicate to the UI that Jedi has crashed and to
336 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
336 report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
337
337
338 Added in IPython 6.0 so should likely be removed for 7.0
338 Added in IPython 6.0 so should likely be removed for 7.0
339
339
340 """
340 """
341
341
342 def __init__(self, name):
342 def __init__(self, name):
343
343
344 self.name = name
344 self.name = name
345 self.complete = name
345 self.complete = name
346 self.type = 'crashed'
346 self.type = 'crashed'
347 self.name_with_symbols = name
347 self.name_with_symbols = name
348 self.signature = ''
348 self.signature = ''
349 self._origin = 'fake'
349 self._origin = 'fake'
350
350
351 def __repr__(self):
351 def __repr__(self):
352 return '<Fake completion object jedi has crashed>'
352 return '<Fake completion object jedi has crashed>'
353
353
354
354
355 class Completion:
355 class Completion:
356 """
356 """
357 Completion object used and return by IPython completers.
357 Completion object used and return by IPython completers.
358
358
359 .. warning::
359 .. warning::
360
360
361 Unstable
361 Unstable
362
362
363 This function is unstable, API may change without warning.
363 This function is unstable, API may change without warning.
364 It will also raise unless use in proper context manager.
364 It will also raise unless use in proper context manager.
365
365
366 This act as a middle ground :any:`Completion` object between the
366 This act as a middle ground :any:`Completion` object between the
367 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
367 :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
368 object. While Jedi need a lot of information about evaluator and how the
368 object. While Jedi need a lot of information about evaluator and how the
369 code should be ran/inspected, PromptToolkit (and other frontend) mostly
369 code should be ran/inspected, PromptToolkit (and other frontend) mostly
370 need user facing information.
370 need user facing information.
371
371
372 - Which range should be replaced replaced by what.
372 - Which range should be replaced replaced by what.
373 - Some metadata (like completion type), or meta information to displayed to
373 - Some metadata (like completion type), or meta information to displayed to
374 the use user.
374 the use user.
375
375
376 For debugging purpose we can also store the origin of the completion (``jedi``,
376 For debugging purpose we can also store the origin of the completion (``jedi``,
377 ``IPython.python_matches``, ``IPython.magics_matches``...).
377 ``IPython.python_matches``, ``IPython.magics_matches``...).
378 """
378 """
379
379
380 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
380 __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
381
381
382 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
382 def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
383 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
383 warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
384 "It may change without warnings. "
384 "It may change without warnings. "
385 "Use in corresponding context manager.",
385 "Use in corresponding context manager.",
386 category=ProvisionalCompleterWarning, stacklevel=2)
386 category=ProvisionalCompleterWarning, stacklevel=2)
387
387
388 self.start = start
388 self.start = start
389 self.end = end
389 self.end = end
390 self.text = text
390 self.text = text
391 self.type = type
391 self.type = type
392 self.signature = signature
392 self.signature = signature
393 self._origin = _origin
393 self._origin = _origin
394
394
395 def __repr__(self):
395 def __repr__(self):
396 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
396 return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
397 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
397 (self.start, self.end, self.text, self.type or '?', self.signature or '?')
398
398
399 def __eq__(self, other)->Bool:
399 def __eq__(self, other)->Bool:
400 """
400 """
401 Equality and hash do not hash the type (as some completer may not be
401 Equality and hash do not hash the type (as some completer may not be
402 able to infer the type), but are use to (partially) de-duplicate
402 able to infer the type), but are use to (partially) de-duplicate
403 completion.
403 completion.
404
404
405 Completely de-duplicating completion is a bit tricker that just
405 Completely de-duplicating completion is a bit tricker that just
406 comparing as it depends on surrounding text, which Completions are not
406 comparing as it depends on surrounding text, which Completions are not
407 aware of.
407 aware of.
408 """
408 """
409 return self.start == other.start and \
409 return self.start == other.start and \
410 self.end == other.end and \
410 self.end == other.end and \
411 self.text == other.text
411 self.text == other.text
412
412
413 def __hash__(self):
413 def __hash__(self):
414 return hash((self.start, self.end, self.text))
414 return hash((self.start, self.end, self.text))
415
415
416
416
417 _IC = Iterable[Completion]
417 _IC = Iterable[Completion]
418
418
419
419
420 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
420 def _deduplicate_completions(text: str, completions: _IC)-> _IC:
421 """
421 """
422 Deduplicate a set of completions.
422 Deduplicate a set of completions.
423
423
424 .. warning::
424 .. warning::
425
425
426 Unstable
426 Unstable
427
427
428 This function is unstable, API may change without warning.
428 This function is unstable, API may change without warning.
429
429
430 Parameters
430 Parameters
431 ----------
431 ----------
432 text: str
432 text: str
433 text that should be completed.
433 text that should be completed.
434 completions: Iterator[Completion]
434 completions: Iterator[Completion]
435 iterator over the completions to deduplicate
435 iterator over the completions to deduplicate
436
436
437 Yields
437 Yields
438 ------
438 ------
439 `Completions` objects
439 `Completions` objects
440
440
441
441
442 Completions coming from multiple sources, may be different but end up having
442 Completions coming from multiple sources, may be different but end up having
443 the same effect when applied to ``text``. If this is the case, this will
443 the same effect when applied to ``text``. If this is the case, this will
444 consider completions as equal and only emit the first encountered.
444 consider completions as equal and only emit the first encountered.
445
445
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=False)->_IC:
465 def rectify_completions(text: str, completions: _IC, *, _debug=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
482
483
483
484 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
484 :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
485 the Jupyter Protocol requires them to behave like so. This will readjust
485 the Jupyter Protocol requires them to behave like so. This will readjust
486 the completion to have the same ``start`` and ``end`` by padding both
486 the completion to have the same ``start`` and ``end`` by padding both
487 extremities with surrounding text.
487 extremities with surrounding text.
488
488
489 During stabilisation should support a ``_debug`` option to log which
489 During stabilisation should support a ``_debug`` option to log which
490 completion are return by the IPython completer and not found in Jedi in
490 completion are return by the IPython completer and not found in Jedi in
491 order to make upstream bug report.
491 order to make upstream bug report.
492 """
492 """
493 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
493 warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
494 "It may change without warnings. "
494 "It may change without warnings. "
495 "Use in corresponding context manager.",
495 "Use in corresponding context manager.",
496 category=ProvisionalCompleterWarning, stacklevel=2)
496 category=ProvisionalCompleterWarning, stacklevel=2)
497
497
498 completions = list(completions)
498 completions = list(completions)
499 if not completions:
499 if not completions:
500 return
500 return
501 starts = (c.start for c in completions)
501 starts = (c.start for c in completions)
502 ends = (c.end for c in completions)
502 ends = (c.end for c in completions)
503
503
504 new_start = min(starts)
504 new_start = min(starts)
505 new_end = max(ends)
505 new_end = max(ends)
506
506
507 seen_jedi = set()
507 seen_jedi = set()
508 seen_python_matches = set()
508 seen_python_matches = set()
509 for c in completions:
509 for c in completions:
510 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
510 new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
511 if c._origin == 'jedi':
511 if c._origin == 'jedi':
512 seen_jedi.add(new_text)
512 seen_jedi.add(new_text)
513 elif c._origin == 'IPCompleter.python_matches':
513 elif c._origin == 'IPCompleter.python_matches':
514 seen_python_matches.add(new_text)
514 seen_python_matches.add(new_text)
515 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
515 yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
516 diff = seen_python_matches.difference(seen_jedi)
516 diff = seen_python_matches.difference(seen_jedi)
517 if diff and _debug:
517 if diff and _debug:
518 print('IPython.python matches have extras:', diff)
518 print('IPython.python matches have extras:', diff)
519
519
520
520
521 if sys.platform == 'win32':
521 if sys.platform == 'win32':
522 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
522 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
523 else:
523 else:
524 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
524 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
525
525
526 GREEDY_DELIMS = ' =\r\n'
526 GREEDY_DELIMS = ' =\r\n'
527
527
528
528
529 class CompletionSplitter(object):
529 class CompletionSplitter(object):
530 """An object to split an input line in a manner similar to readline.
530 """An object to split an input line in a manner similar to readline.
531
531
532 By having our own implementation, we can expose readline-like completion in
532 By having our own implementation, we can expose readline-like completion in
533 a uniform manner to all frontends. This object only needs to be given the
533 a uniform manner to all frontends. This object only needs to be given the
534 line of text to be split and the cursor position on said line, and it
534 line of text to be split and the cursor position on said line, and it
535 returns the 'word' to be completed on at the cursor after splitting the
535 returns the 'word' to be completed on at the cursor after splitting the
536 entire line.
536 entire line.
537
537
538 What characters are used as splitting delimiters can be controlled by
538 What characters are used as splitting delimiters can be controlled by
539 setting the ``delims`` attribute (this is a property that internally
539 setting the ``delims`` attribute (this is a property that internally
540 automatically builds the necessary regular expression)"""
540 automatically builds the necessary regular expression)"""
541
541
542 # Private interface
542 # Private interface
543
543
544 # A string of delimiter characters. The default value makes sense for
544 # A string of delimiter characters. The default value makes sense for
545 # IPython's most typical usage patterns.
545 # IPython's most typical usage patterns.
546 _delims = DELIMS
546 _delims = DELIMS
547
547
548 # The expression (a normal string) to be compiled into a regular expression
548 # The expression (a normal string) to be compiled into a regular expression
549 # for actual splitting. We store it as an attribute mostly for ease of
549 # for actual splitting. We store it as an attribute mostly for ease of
550 # debugging, since this type of code can be so tricky to debug.
550 # debugging, since this type of code can be so tricky to debug.
551 _delim_expr = None
551 _delim_expr = None
552
552
553 # The regular expression that does the actual splitting
553 # The regular expression that does the actual splitting
554 _delim_re = None
554 _delim_re = None
555
555
556 def __init__(self, delims=None):
556 def __init__(self, delims=None):
557 delims = CompletionSplitter._delims if delims is None else delims
557 delims = CompletionSplitter._delims if delims is None else delims
558 self.delims = delims
558 self.delims = delims
559
559
560 @property
560 @property
561 def delims(self):
561 def delims(self):
562 """Return the string of delimiter characters."""
562 """Return the string of delimiter characters."""
563 return self._delims
563 return self._delims
564
564
565 @delims.setter
565 @delims.setter
566 def delims(self, delims):
566 def delims(self, delims):
567 """Set the delimiters for line splitting."""
567 """Set the delimiters for line splitting."""
568 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
568 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
569 self._delim_re = re.compile(expr)
569 self._delim_re = re.compile(expr)
570 self._delims = delims
570 self._delims = delims
571 self._delim_expr = expr
571 self._delim_expr = expr
572
572
573 def split_line(self, line, cursor_pos=None):
573 def split_line(self, line, cursor_pos=None):
574 """Split a line of text with a cursor at the given position.
574 """Split a line of text with a cursor at the given position.
575 """
575 """
576 l = line if cursor_pos is None else line[:cursor_pos]
576 l = line if cursor_pos is None else line[:cursor_pos]
577 return self._delim_re.split(l)[-1]
577 return self._delim_re.split(l)[-1]
578
578
579
579
580
580
581 class Completer(Configurable):
581 class Completer(Configurable):
582
582
583 greedy = Bool(False,
583 greedy = Bool(False,
584 help="""Activate greedy completion
584 help="""Activate greedy completion
585 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
585 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
586
586
587 This will enable completion on elements of lists, results of function calls, etc.,
587 This will enable completion on elements of lists, results of function calls, etc.,
588 but can be unsafe because the code is actually evaluated on TAB.
588 but can be unsafe because the code is actually evaluated on TAB.
589 """
589 """
590 ).tag(config=True)
590 ).tag(config=True)
591
591
592 use_jedi = Bool(default_value=JEDI_INSTALLED,
592 use_jedi = Bool(default_value=JEDI_INSTALLED,
593 help="Experimental: Use Jedi to generate autocompletions. "
593 help="Experimental: Use Jedi to generate autocompletions. "
594 "Default to True if jedi is installed.").tag(config=True)
594 "Default to True if jedi is installed.").tag(config=True)
595
595
596 jedi_compute_type_timeout = Int(default_value=400,
596 jedi_compute_type_timeout = Int(default_value=400,
597 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
597 help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
598 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
598 Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
599 performance by preventing jedi to build its cache.
599 performance by preventing jedi to build its cache.
600 """).tag(config=True)
600 """).tag(config=True)
601
601
602 debug = Bool(default_value=False,
602 debug = Bool(default_value=False,
603 help='Enable debug for the Completer. Mostly print extra '
603 help='Enable debug for the Completer. Mostly print extra '
604 'information for experimental jedi integration.')\
604 'information for experimental jedi integration.')\
605 .tag(config=True)
605 .tag(config=True)
606
606
607 backslash_combining_completions = Bool(True,
607 backslash_combining_completions = Bool(True,
608 help="Enable unicode completions, e.g. \\alpha<tab> . "
608 help="Enable unicode completions, e.g. \\alpha<tab> . "
609 "Includes completion of latex commands, unicode names, and expanding "
609 "Includes completion of latex commands, unicode names, and expanding "
610 "unicode characters back to latex commands.").tag(config=True)
610 "unicode characters back to latex commands.").tag(config=True)
611
611
612
612
613
613
614 def __init__(self, namespace=None, global_namespace=None, **kwargs):
614 def __init__(self, namespace=None, global_namespace=None, **kwargs):
615 """Create a new completer for the command line.
615 """Create a new completer for the command line.
616
616
617 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
617 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
618
618
619 If unspecified, the default namespace where completions are performed
619 If unspecified, the default namespace where completions are performed
620 is __main__ (technically, __main__.__dict__). Namespaces should be
620 is __main__ (technically, __main__.__dict__). Namespaces should be
621 given as dictionaries.
621 given as dictionaries.
622
622
623 An optional second namespace can be given. This allows the completer
623 An optional second namespace can be given. This allows the completer
624 to handle cases where both the local and global scopes need to be
624 to handle cases where both the local and global scopes need to be
625 distinguished.
625 distinguished.
626 """
626 """
627
627
628 # Don't bind to namespace quite yet, but flag whether the user wants a
628 # Don't bind to namespace quite yet, but flag whether the user wants a
629 # specific namespace or to use __main__.__dict__. This will allow us
629 # specific namespace or to use __main__.__dict__. This will allow us
630 # to bind to __main__.__dict__ at completion time, not now.
630 # to bind to __main__.__dict__ at completion time, not now.
631 if namespace is None:
631 if namespace is None:
632 self.use_main_ns = True
632 self.use_main_ns = True
633 else:
633 else:
634 self.use_main_ns = False
634 self.use_main_ns = False
635 self.namespace = namespace
635 self.namespace = namespace
636
636
637 # The global namespace, if given, can be bound directly
637 # The global namespace, if given, can be bound directly
638 if global_namespace is None:
638 if global_namespace is None:
639 self.global_namespace = {}
639 self.global_namespace = {}
640 else:
640 else:
641 self.global_namespace = global_namespace
641 self.global_namespace = global_namespace
642
642
643 self.custom_matchers = []
643 self.custom_matchers = []
644
644
645 super(Completer, self).__init__(**kwargs)
645 super(Completer, self).__init__(**kwargs)
646
646
647 def complete(self, text, state):
647 def complete(self, text, state):
648 """Return the next possible completion for 'text'.
648 """Return the next possible completion for 'text'.
649
649
650 This is called successively with state == 0, 1, 2, ... until it
650 This is called successively with state == 0, 1, 2, ... until it
651 returns None. The completion should begin with 'text'.
651 returns None. The completion should begin with 'text'.
652
652
653 """
653 """
654 if self.use_main_ns:
654 if self.use_main_ns:
655 self.namespace = __main__.__dict__
655 self.namespace = __main__.__dict__
656
656
657 if state == 0:
657 if state == 0:
658 if "." in text:
658 if "." in text:
659 self.matches = self.attr_matches(text)
659 self.matches = self.attr_matches(text)
660 else:
660 else:
661 self.matches = self.global_matches(text)
661 self.matches = self.global_matches(text)
662 try:
662 try:
663 return self.matches[state]
663 return self.matches[state]
664 except IndexError:
664 except IndexError:
665 return None
665 return None
666
666
667 def global_matches(self, text):
667 def global_matches(self, text):
668 """Compute matches when text is a simple name.
668 """Compute matches when text is a simple name.
669
669
670 Return a list of all keywords, built-in functions and names currently
670 Return a list of all keywords, built-in functions and names currently
671 defined in self.namespace or self.global_namespace that match.
671 defined in self.namespace or self.global_namespace that match.
672
672
673 """
673 """
674 matches = []
674 matches = []
675 match_append = matches.append
675 match_append = matches.append
676 n = len(text)
676 n = len(text)
677 for lst in [keyword.kwlist,
677 for lst in [keyword.kwlist,
678 builtin_mod.__dict__.keys(),
678 builtin_mod.__dict__.keys(),
679 self.namespace.keys(),
679 self.namespace.keys(),
680 self.global_namespace.keys()]:
680 self.global_namespace.keys()]:
681 for word in lst:
681 for word in lst:
682 if word[:n] == text and word != "__builtins__":
682 if word[:n] == text and word != "__builtins__":
683 match_append(word)
683 match_append(word)
684
684
685 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
685 snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
686 for lst in [self.namespace.keys(),
686 for lst in [self.namespace.keys(),
687 self.global_namespace.keys()]:
687 self.global_namespace.keys()]:
688 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
688 shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
689 for word in lst if snake_case_re.match(word)}
689 for word in lst if snake_case_re.match(word)}
690 for word in shortened.keys():
690 for word in shortened.keys():
691 if word[:n] == text and word != "__builtins__":
691 if word[:n] == text and word != "__builtins__":
692 match_append(shortened[word])
692 match_append(shortened[word])
693 return matches
693 return matches
694
694
695 def attr_matches(self, text):
695 def attr_matches(self, text):
696 """Compute matches when text contains a dot.
696 """Compute matches when text contains a dot.
697
697
698 Assuming the text is of the form NAME.NAME....[NAME], and is
698 Assuming the text is of the form NAME.NAME....[NAME], and is
699 evaluatable in self.namespace or self.global_namespace, it will be
699 evaluatable in self.namespace or self.global_namespace, it will be
700 evaluated and its attributes (as revealed by dir()) are used as
700 evaluated and its attributes (as revealed by dir()) are used as
701 possible completions. (For class instances, class members are
701 possible completions. (For class instances, class members are
702 also considered.)
702 also considered.)
703
703
704 WARNING: this can still invoke arbitrary C code, if an object
704 WARNING: this can still invoke arbitrary C code, if an object
705 with a __getattr__ hook is evaluated.
705 with a __getattr__ hook is evaluated.
706
706
707 """
707 """
708
708
709 # Another option, seems to work great. Catches things like ''.<tab>
709 # Another option, seems to work great. Catches things like ''.<tab>
710 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
710 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
711
711
712 if m:
712 if m:
713 expr, attr = m.group(1, 3)
713 expr, attr = m.group(1, 3)
714 elif self.greedy:
714 elif self.greedy:
715 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
715 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
716 if not m2:
716 if not m2:
717 return []
717 return []
718 expr, attr = m2.group(1,2)
718 expr, attr = m2.group(1,2)
719 else:
719 else:
720 return []
720 return []
721
721
722 try:
722 try:
723 obj = eval(expr, self.namespace)
723 obj = eval(expr, self.namespace)
724 except:
724 except:
725 try:
725 try:
726 obj = eval(expr, self.global_namespace)
726 obj = eval(expr, self.global_namespace)
727 except:
727 except:
728 return []
728 return []
729
729
730 if self.limit_to__all__ and hasattr(obj, '__all__'):
730 if self.limit_to__all__ and hasattr(obj, '__all__'):
731 words = get__all__entries(obj)
731 words = get__all__entries(obj)
732 else:
732 else:
733 words = dir2(obj)
733 words = dir2(obj)
734
734
735 try:
735 try:
736 words = generics.complete_object(obj, words)
736 words = generics.complete_object(obj, words)
737 except TryNext:
737 except TryNext:
738 pass
738 pass
739 except AssertionError:
739 except AssertionError:
740 raise
740 raise
741 except Exception:
741 except Exception:
742 # Silence errors from completion function
742 # Silence errors from completion function
743 #raise # dbg
743 #raise # dbg
744 pass
744 pass
745 # Build match list to return
745 # Build match list to return
746 n = len(attr)
746 n = len(attr)
747 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
747 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
748
748
749
749
750 def get__all__entries(obj):
750 def get__all__entries(obj):
751 """returns the strings in the __all__ attribute"""
751 """returns the strings in the __all__ attribute"""
752 try:
752 try:
753 words = getattr(obj, '__all__')
753 words = getattr(obj, '__all__')
754 except:
754 except:
755 return []
755 return []
756
756
757 return [w for w in words if isinstance(w, str)]
757 return [w for w in words if isinstance(w, str)]
758
758
759
759
760 def match_dict_keys(keys: List[str], prefix: str, delims: str):
760 def match_dict_keys(keys: List[str], prefix: str, delims: str):
761 """Used by dict_key_matches, matching the prefix to a list of keys
761 """Used by dict_key_matches, matching the prefix to a list of keys
762
762
763 Parameters
763 Parameters
764 ==========
764 ==========
765 keys:
765 keys:
766 list of keys in dictionary currently being completed.
766 list of keys in dictionary currently being completed.
767 prefix:
767 prefix:
768 Part of the text already typed by the user. e.g. `mydict[b'fo`
768 Part of the text already typed by the user. e.g. `mydict[b'fo`
769 delims:
769 delims:
770 String of delimiters to consider when finding the current key.
770 String of delimiters to consider when finding the current key.
771
771
772 Returns
772 Returns
773 =======
773 =======
774
774
775 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
775 A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
776 ``quote`` being the quote that need to be used to close current string.
776 ``quote`` being the quote that need to be used to close current string.
777 ``token_start`` the position where the replacement should start occurring,
777 ``token_start`` the position where the replacement should start occurring,
778 ``matches`` a list of replacement/completion
778 ``matches`` a list of replacement/completion
779
779
780 """
780 """
781 if not prefix:
781 if not prefix:
782 return None, 0, [repr(k) for k in keys
782 return None, 0, [repr(k) for k in keys
783 if isinstance(k, (str, bytes))]
783 if isinstance(k, (str, bytes))]
784 quote_match = re.search('["\']', prefix)
784 quote_match = re.search('["\']', prefix)
785 quote = quote_match.group()
785 quote = quote_match.group()
786 try:
786 try:
787 prefix_str = eval(prefix + quote, {})
787 prefix_str = eval(prefix + quote, {})
788 except Exception:
788 except Exception:
789 return None, 0, []
789 return None, 0, []
790
790
791 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
791 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
792 token_match = re.search(pattern, prefix, re.UNICODE)
792 token_match = re.search(pattern, prefix, re.UNICODE)
793 token_start = token_match.start()
793 token_start = token_match.start()
794 token_prefix = token_match.group()
794 token_prefix = token_match.group()
795
795
796 matched = []
796 matched = []
797 for key in keys:
797 for key in keys:
798 try:
798 try:
799 if not key.startswith(prefix_str):
799 if not key.startswith(prefix_str):
800 continue
800 continue
801 except (AttributeError, TypeError, UnicodeError):
801 except (AttributeError, TypeError, UnicodeError):
802 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
802 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
803 continue
803 continue
804
804
805 # reformat remainder of key to begin with prefix
805 # reformat remainder of key to begin with prefix
806 rem = key[len(prefix_str):]
806 rem = key[len(prefix_str):]
807 # force repr wrapped in '
807 # force repr wrapped in '
808 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
808 rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
809 if rem_repr.startswith('u') and prefix[0] not in 'uU':
809 if rem_repr.startswith('u') and prefix[0] not in 'uU':
810 # Found key is unicode, but prefix is Py2 string.
810 # Found key is unicode, but prefix is Py2 string.
811 # Therefore attempt to interpret key as string.
811 # Therefore attempt to interpret key as string.
812 try:
812 try:
813 rem_repr = repr(rem.encode('ascii') + '"')
813 rem_repr = repr(rem.encode('ascii') + '"')
814 except UnicodeEncodeError:
814 except UnicodeEncodeError:
815 continue
815 continue
816
816
817 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
817 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
818 if quote == '"':
818 if quote == '"':
819 # The entered prefix is quoted with ",
819 # The entered prefix is quoted with ",
820 # but the match is quoted with '.
820 # but the match is quoted with '.
821 # A contained " hence needs escaping for comparison:
821 # A contained " hence needs escaping for comparison:
822 rem_repr = rem_repr.replace('"', '\\"')
822 rem_repr = rem_repr.replace('"', '\\"')
823
823
824 # then reinsert prefix from start of token
824 # then reinsert prefix from start of token
825 matched.append('%s%s' % (token_prefix, rem_repr))
825 matched.append('%s%s' % (token_prefix, rem_repr))
826 return quote, token_start, matched
826 return quote, token_start, matched
827
827
828
828
829 def cursor_to_position(text:str, line:int, column:int)->int:
829 def cursor_to_position(text:str, line:int, column:int)->int:
830 """
830 """
831
831
832 Convert the (line,column) position of the cursor in text to an offset in a
832 Convert the (line,column) position of the cursor in text to an offset in a
833 string.
833 string.
834
834
835 Parameters
835 Parameters
836 ----------
836 ----------
837
837
838 text : str
838 text : str
839 The text in which to calculate the cursor offset
839 The text in which to calculate the cursor offset
840 line : int
840 line : int
841 Line of the cursor; 0-indexed
841 Line of the cursor; 0-indexed
842 column : int
842 column : int
843 Column of the cursor 0-indexed
843 Column of the cursor 0-indexed
844
844
845 Return
845 Return
846 ------
846 ------
847 Position of the cursor in ``text``, 0-indexed.
847 Position of the cursor in ``text``, 0-indexed.
848
848
849 See Also
849 See Also
850 --------
850 --------
851 position_to_cursor: reciprocal of this function
851 position_to_cursor: reciprocal of this function
852
852
853 """
853 """
854 lines = text.split('\n')
854 lines = text.split('\n')
855 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
855 assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
856
856
857 return sum(len(l) + 1 for l in lines[:line]) + column
857 return sum(len(l) + 1 for l in lines[:line]) + column
858
858
859 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
859 def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
860 """
860 """
861 Convert the position of the cursor in text (0 indexed) to a line
861 Convert the position of the cursor in text (0 indexed) to a line
862 number(0-indexed) and a column number (0-indexed) pair
862 number(0-indexed) and a column number (0-indexed) pair
863
863
864 Position should be a valid position in ``text``.
864 Position should be a valid position in ``text``.
865
865
866 Parameters
866 Parameters
867 ----------
867 ----------
868
868
869 text : str
869 text : str
870 The text in which to calculate the cursor offset
870 The text in which to calculate the cursor offset
871 offset : int
871 offset : int
872 Position of the cursor in ``text``, 0-indexed.
872 Position of the cursor in ``text``, 0-indexed.
873
873
874 Return
874 Return
875 ------
875 ------
876 (line, column) : (int, int)
876 (line, column) : (int, int)
877 Line of the cursor; 0-indexed, column of the cursor 0-indexed
877 Line of the cursor; 0-indexed, column of the cursor 0-indexed
878
878
879
879
880 See Also
880 See Also
881 --------
881 --------
882 cursor_to_position : reciprocal of this function
882 cursor_to_position : reciprocal of this function
883
883
884
884
885 """
885 """
886
886
887 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
887 assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
888
888
889 before = text[:offset]
889 before = text[:offset]
890 blines = before.split('\n') # ! splitnes trim trailing \n
890 blines = before.split('\n') # ! splitnes trim trailing \n
891 line = before.count('\n')
891 line = before.count('\n')
892 col = len(blines[-1])
892 col = len(blines[-1])
893 return line, col
893 return line, col
894
894
895
895
896 def _safe_isinstance(obj, module, class_name):
896 def _safe_isinstance(obj, module, class_name):
897 """Checks if obj is an instance of module.class_name if loaded
897 """Checks if obj is an instance of module.class_name if loaded
898 """
898 """
899 return (module in sys.modules and
899 return (module in sys.modules and
900 isinstance(obj, getattr(import_module(module), class_name)))
900 isinstance(obj, getattr(import_module(module), class_name)))
901
901
902
902
903 def back_unicode_name_matches(text):
903 def back_unicode_name_matches(text):
904 u"""Match unicode characters back to unicode name
904 u"""Match unicode characters back to unicode name
905
905
906 This does ``β˜ƒ`` -> ``\\snowman``
906 This does ``β˜ƒ`` -> ``\\snowman``
907
907
908 Note that snowman is not a valid python3 combining character but will be expanded.
908 Note that snowman is not a valid python3 combining character but will be expanded.
909 Though it will not recombine back to the snowman character by the completion machinery.
909 Though it will not recombine back to the snowman character by the completion machinery.
910
910
911 This will not either back-complete standard sequences like \\n, \\b ...
911 This will not either back-complete standard sequences like \\n, \\b ...
912
912
913 Used on Python 3 only.
913 Used on Python 3 only.
914 """
914 """
915 if len(text)<2:
915 if len(text)<2:
916 return u'', ()
916 return u'', ()
917 maybe_slash = text[-2]
917 maybe_slash = text[-2]
918 if maybe_slash != '\\':
918 if maybe_slash != '\\':
919 return u'', ()
919 return u'', ()
920
920
921 char = text[-1]
921 char = text[-1]
922 # no expand on quote for completion in strings.
922 # no expand on quote for completion in strings.
923 # nor backcomplete standard ascii keys
923 # nor backcomplete standard ascii keys
924 if char in string.ascii_letters or char in ['"',"'"]:
924 if char in string.ascii_letters or char in ['"',"'"]:
925 return u'', ()
925 return u'', ()
926 try :
926 try :
927 unic = unicodedata.name(char)
927 unic = unicodedata.name(char)
928 return '\\'+char,['\\'+unic]
928 return '\\'+char,['\\'+unic]
929 except KeyError:
929 except KeyError:
930 pass
930 pass
931 return u'', ()
931 return u'', ()
932
932
933 def back_latex_name_matches(text:str):
933 def back_latex_name_matches(text:str):
934 """Match latex characters back to unicode name
934 """Match latex characters back to unicode name
935
935
936 This does ``\\β„΅`` -> ``\\aleph``
936 This does ``\\β„΅`` -> ``\\aleph``
937
937
938 Used on Python 3 only.
938 Used on Python 3 only.
939 """
939 """
940 if len(text)<2:
940 if len(text)<2:
941 return u'', ()
941 return u'', ()
942 maybe_slash = text[-2]
942 maybe_slash = text[-2]
943 if maybe_slash != '\\':
943 if maybe_slash != '\\':
944 return u'', ()
944 return u'', ()
945
945
946
946
947 char = text[-1]
947 char = text[-1]
948 # no expand on quote for completion in strings.
948 # no expand on quote for completion in strings.
949 # nor backcomplete standard ascii keys
949 # nor backcomplete standard ascii keys
950 if char in string.ascii_letters or char in ['"',"'"]:
950 if char in string.ascii_letters or char in ['"',"'"]:
951 return u'', ()
951 return u'', ()
952 try :
952 try :
953 latex = reverse_latex_symbol[char]
953 latex = reverse_latex_symbol[char]
954 # '\\' replace the \ as well
954 # '\\' replace the \ as well
955 return '\\'+char,[latex]
955 return '\\'+char,[latex]
956 except KeyError:
956 except KeyError:
957 pass
957 pass
958 return u'', ()
958 return u'', ()
959
959
960
960
961 def _formatparamchildren(parameter) -> str:
961 def _formatparamchildren(parameter) -> str:
962 """
962 """
963 Get parameter name and value from Jedi Private API
963 Get parameter name and value from Jedi Private API
964
964
965 Jedi does not expose a simple way to get `param=value` from its API.
965 Jedi does not expose a simple way to get `param=value` from its API.
966
966
967 Parameter
967 Parameter
968 =========
968 =========
969
969
970 parameter:
970 parameter:
971 Jedi's function `Param`
971 Jedi's function `Param`
972
972
973 Returns
973 Returns
974 =======
974 =======
975
975
976 A string like 'a', 'b=1', '*args', '**kwargs'
976 A string like 'a', 'b=1', '*args', '**kwargs'
977
977
978
978
979 """
979 """
980 description = parameter.description
980 description = parameter.description
981 if not description.startswith('param '):
981 if not description.startswith('param '):
982 raise ValueError('Jedi function parameter description have change format.'
982 raise ValueError('Jedi function parameter description have change format.'
983 'Expected "param ...", found %r".' % description)
983 'Expected "param ...", found %r".' % description)
984 return description[6:]
984 return description[6:]
985
985
986 def _make_signature(completion)-> str:
986 def _make_signature(completion)-> str:
987 """
987 """
988 Make the signature from a jedi completion
988 Make the signature from a jedi completion
989
989
990 Parameter
990 Parameter
991 =========
991 =========
992
992
993 completion: jedi.Completion
993 completion: jedi.Completion
994 object does not complete a function type
994 object does not complete a function type
995
995
996 Returns
996 Returns
997 =======
997 =======
998
998
999 a string consisting of the function signature, with the parenthesis but
999 a string consisting of the function signature, with the parenthesis but
1000 without the function name. example:
1000 without the function name. example:
1001 `(a, *args, b=1, **kwargs)`
1001 `(a, *args, b=1, **kwargs)`
1002
1002
1003 """
1003 """
1004
1004
1005 # it looks like this might work on jedi 0.17
1005 # it looks like this might work on jedi 0.17
1006 if hasattr(completion, 'get_signatures'):
1006 if hasattr(completion, 'get_signatures'):
1007 signatures = completion.get_signatures()
1007 signatures = completion.get_signatures()
1008 if not signatures:
1008 if not signatures:
1009 return '(?)'
1009 return '(?)'
1010
1010
1011 c0 = completion.get_signatures()[0]
1011 c0 = completion.get_signatures()[0]
1012 return '('+c0.to_string().split('(', maxsplit=1)[1]
1012 return '('+c0.to_string().split('(', maxsplit=1)[1]
1013
1013
1014 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1014 return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
1015 for p in signature.defined_names()) if f])
1015 for p in signature.defined_names()) if f])
1016
1016
1017 class IPCompleter(Completer):
1017 class IPCompleter(Completer):
1018 """Extension of the completer class with IPython-specific features"""
1018 """Extension of the completer class with IPython-specific features"""
1019
1019
1020 _names = None
1020 _names = None
1021
1021
1022 @observe('greedy')
1022 @observe('greedy')
1023 def _greedy_changed(self, change):
1023 def _greedy_changed(self, change):
1024 """update the splitter and readline delims when greedy is changed"""
1024 """update the splitter and readline delims when greedy is changed"""
1025 if change['new']:
1025 if change['new']:
1026 self.splitter.delims = GREEDY_DELIMS
1026 self.splitter.delims = GREEDY_DELIMS
1027 else:
1027 else:
1028 self.splitter.delims = DELIMS
1028 self.splitter.delims = DELIMS
1029
1029
1030 dict_keys_only = Bool(False,
1030 dict_keys_only = Bool(False,
1031 help="""Whether to show dict key matches only""")
1031 help="""Whether to show dict key matches only""")
1032
1032
1033 merge_completions = Bool(True,
1033 merge_completions = Bool(True,
1034 help="""Whether to merge completion results into a single list
1034 help="""Whether to merge completion results into a single list
1035
1035
1036 If False, only the completion results from the first non-empty
1036 If False, only the completion results from the first non-empty
1037 completer will be returned.
1037 completer will be returned.
1038 """
1038 """
1039 ).tag(config=True)
1039 ).tag(config=True)
1040 omit__names = Enum((0,1,2), default_value=2,
1040 omit__names = Enum((0,1,2), default_value=2,
1041 help="""Instruct the completer to omit private method names
1041 help="""Instruct the completer to omit private method names
1042
1042
1043 Specifically, when completing on ``object.<tab>``.
1043 Specifically, when completing on ``object.<tab>``.
1044
1044
1045 When 2 [default]: all names that start with '_' will be excluded.
1045 When 2 [default]: all names that start with '_' will be excluded.
1046
1046
1047 When 1: all 'magic' names (``__foo__``) will be excluded.
1047 When 1: all 'magic' names (``__foo__``) will be excluded.
1048
1048
1049 When 0: nothing will be excluded.
1049 When 0: nothing will be excluded.
1050 """
1050 """
1051 ).tag(config=True)
1051 ).tag(config=True)
1052 limit_to__all__ = Bool(False,
1052 limit_to__all__ = Bool(False,
1053 help="""
1053 help="""
1054 DEPRECATED as of version 5.0.
1054 DEPRECATED as of version 5.0.
1055
1055
1056 Instruct the completer to use __all__ for the completion
1056 Instruct the completer to use __all__ for the completion
1057
1057
1058 Specifically, when completing on ``object.<tab>``.
1058 Specifically, when completing on ``object.<tab>``.
1059
1059
1060 When True: only those names in obj.__all__ will be included.
1060 When True: only those names in obj.__all__ will be included.
1061
1061
1062 When False [default]: the __all__ attribute is ignored
1062 When False [default]: the __all__ attribute is ignored
1063 """,
1063 """,
1064 ).tag(config=True)
1064 ).tag(config=True)
1065
1065
1066 @observe('limit_to__all__')
1066 @observe('limit_to__all__')
1067 def _limit_to_all_changed(self, change):
1067 def _limit_to_all_changed(self, change):
1068 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1068 warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
1069 'value has been deprecated since IPython 5.0, will be made to have '
1069 'value has been deprecated since IPython 5.0, will be made to have '
1070 'no effects and then removed in future version of IPython.',
1070 'no effects and then removed in future version of IPython.',
1071 UserWarning)
1071 UserWarning)
1072
1072
1073 def __init__(self, shell=None, namespace=None, global_namespace=None,
1073 def __init__(self, shell=None, namespace=None, global_namespace=None,
1074 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
1074 use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
1075 """IPCompleter() -> completer
1075 """IPCompleter() -> completer
1076
1076
1077 Return a completer object.
1077 Return a completer object.
1078
1078
1079 Parameters
1079 Parameters
1080 ----------
1080 ----------
1081
1081
1082 shell
1082 shell
1083 a pointer to the ipython shell itself. This is needed
1083 a pointer to the ipython shell itself. This is needed
1084 because this completer knows about magic functions, and those can
1084 because this completer knows about magic functions, and those can
1085 only be accessed via the ipython instance.
1085 only be accessed via the ipython instance.
1086
1086
1087 namespace : dict, optional
1087 namespace : dict, optional
1088 an optional dict where completions are performed.
1088 an optional dict where completions are performed.
1089
1089
1090 global_namespace : dict, optional
1090 global_namespace : dict, optional
1091 secondary optional dict for completions, to
1091 secondary optional dict for completions, to
1092 handle cases (such as IPython embedded inside functions) where
1092 handle cases (such as IPython embedded inside functions) where
1093 both Python scopes are visible.
1093 both Python scopes are visible.
1094
1094
1095 use_readline : bool, optional
1095 use_readline : bool, optional
1096 DEPRECATED, ignored since IPython 6.0, will have no effects
1096 DEPRECATED, ignored since IPython 6.0, will have no effects
1097 """
1097 """
1098
1098
1099 self.magic_escape = ESC_MAGIC
1099 self.magic_escape = ESC_MAGIC
1100 self.splitter = CompletionSplitter()
1100 self.splitter = CompletionSplitter()
1101
1101
1102 if use_readline is not _deprecation_readline_sentinel:
1102 if use_readline is not _deprecation_readline_sentinel:
1103 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
1103 warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
1104 DeprecationWarning, stacklevel=2)
1104 DeprecationWarning, stacklevel=2)
1105
1105
1106 # _greedy_changed() depends on splitter and readline being defined:
1106 # _greedy_changed() depends on splitter and readline being defined:
1107 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
1107 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
1108 config=config, **kwargs)
1108 config=config, **kwargs)
1109
1109
1110 # List where completion matches will be stored
1110 # List where completion matches will be stored
1111 self.matches = []
1111 self.matches = []
1112 self.shell = shell
1112 self.shell = shell
1113 # Regexp to split filenames with spaces in them
1113 # Regexp to split filenames with spaces in them
1114 self.space_name_re = re.compile(r'([^\\] )')
1114 self.space_name_re = re.compile(r'([^\\] )')
1115 # Hold a local ref. to glob.glob for speed
1115 # Hold a local ref. to glob.glob for speed
1116 self.glob = glob.glob
1116 self.glob = glob.glob
1117
1117
1118 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1118 # Determine if we are running on 'dumb' terminals, like (X)Emacs
1119 # buffers, to avoid completion problems.
1119 # buffers, to avoid completion problems.
1120 term = os.environ.get('TERM','xterm')
1120 term = os.environ.get('TERM','xterm')
1121 self.dumb_terminal = term in ['dumb','emacs']
1121 self.dumb_terminal = term in ['dumb','emacs']
1122
1122
1123 # Special handling of backslashes needed in win32 platforms
1123 # Special handling of backslashes needed in win32 platforms
1124 if sys.platform == "win32":
1124 if sys.platform == "win32":
1125 self.clean_glob = self._clean_glob_win32
1125 self.clean_glob = self._clean_glob_win32
1126 else:
1126 else:
1127 self.clean_glob = self._clean_glob
1127 self.clean_glob = self._clean_glob
1128
1128
1129 #regexp to parse docstring for function signature
1129 #regexp to parse docstring for function signature
1130 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1130 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1131 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1131 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1132 #use this if positional argument name is also needed
1132 #use this if positional argument name is also needed
1133 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1133 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
1134
1134
1135 self.magic_arg_matchers = [
1135 self.magic_arg_matchers = [
1136 self.magic_config_matches,
1136 self.magic_config_matches,
1137 self.magic_color_matches,
1137 self.magic_color_matches,
1138 ]
1138 ]
1139
1139
1140 # This is set externally by InteractiveShell
1140 # This is set externally by InteractiveShell
1141 self.custom_completers = None
1141 self.custom_completers = None
1142
1142
1143 @property
1143 @property
1144 def matchers(self):
1144 def matchers(self):
1145 """All active matcher routines for completion"""
1145 """All active matcher routines for completion"""
1146 if self.dict_keys_only:
1146 if self.dict_keys_only:
1147 return [self.dict_key_matches]
1147 return [self.dict_key_matches]
1148
1148
1149 if self.use_jedi:
1149 if self.use_jedi:
1150 return [
1150 return [
1151 *self.custom_matchers,
1151 *self.custom_matchers,
1152 self.dict_key_matches,
1152 self.dict_key_matches,
1153 self.file_matches,
1153 self.file_matches,
1154 self.magic_matches,
1154 self.magic_matches,
1155 ]
1155 ]
1156 else:
1156 else:
1157 return [
1157 return [
1158 *self.custom_matchers,
1158 *self.custom_matchers,
1159 self.dict_key_matches,
1159 self.dict_key_matches,
1160 self.python_matches,
1160 self.python_matches,
1161 self.file_matches,
1161 self.file_matches,
1162 self.magic_matches,
1162 self.magic_matches,
1163 self.python_func_kw_matches,
1163 self.python_func_kw_matches,
1164 ]
1164 ]
1165
1165
1166 def all_completions(self, text) -> List[str]:
1166 def all_completions(self, text) -> List[str]:
1167 """
1167 """
1168 Wrapper around the completion methods for the benefit of emacs.
1168 Wrapper around the completion methods for the benefit of emacs.
1169 """
1169 """
1170 prefix = text.rpartition('.')[0]
1170 prefix = text.rpartition('.')[0]
1171 with provisionalcompleter():
1171 with provisionalcompleter():
1172 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1172 return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
1173 for c in self.completions(text, len(text))]
1173 for c in self.completions(text, len(text))]
1174
1174
1175 return self.complete(text)[1]
1175 return self.complete(text)[1]
1176
1176
1177 def _clean_glob(self, text):
1177 def _clean_glob(self, text):
1178 return self.glob("%s*" % text)
1178 return self.glob("%s*" % text)
1179
1179
1180 def _clean_glob_win32(self,text):
1180 def _clean_glob_win32(self,text):
1181 return [f.replace("\\","/")
1181 return [f.replace("\\","/")
1182 for f in self.glob("%s*" % text)]
1182 for f in self.glob("%s*" % text)]
1183
1183
1184 def file_matches(self, text):
1184 def file_matches(self, text):
1185 """Match filenames, expanding ~USER type strings.
1185 """Match filenames, expanding ~USER type strings.
1186
1186
1187 Most of the seemingly convoluted logic in this completer is an
1187 Most of the seemingly convoluted logic in this completer is an
1188 attempt to handle filenames with spaces in them. And yet it's not
1188 attempt to handle filenames with spaces in them. And yet it's not
1189 quite perfect, because Python's readline doesn't expose all of the
1189 quite perfect, because Python's readline doesn't expose all of the
1190 GNU readline details needed for this to be done correctly.
1190 GNU readline details needed for this to be done correctly.
1191
1191
1192 For a filename with a space in it, the printed completions will be
1192 For a filename with a space in it, the printed completions will be
1193 only the parts after what's already been typed (instead of the
1193 only the parts after what's already been typed (instead of the
1194 full completions, as is normally done). I don't think with the
1194 full completions, as is normally done). I don't think with the
1195 current (as of Python 2.3) Python readline it's possible to do
1195 current (as of Python 2.3) Python readline it's possible to do
1196 better."""
1196 better."""
1197
1197
1198 # chars that require escaping with backslash - i.e. chars
1198 # chars that require escaping with backslash - i.e. chars
1199 # that readline treats incorrectly as delimiters, but we
1199 # that readline treats incorrectly as delimiters, but we
1200 # don't want to treat as delimiters in filename matching
1200 # don't want to treat as delimiters in filename matching
1201 # when escaped with backslash
1201 # when escaped with backslash
1202 if text.startswith('!'):
1202 if text.startswith('!'):
1203 text = text[1:]
1203 text = text[1:]
1204 text_prefix = u'!'
1204 text_prefix = u'!'
1205 else:
1205 else:
1206 text_prefix = u''
1206 text_prefix = u''
1207
1207
1208 text_until_cursor = self.text_until_cursor
1208 text_until_cursor = self.text_until_cursor
1209 # track strings with open quotes
1209 # track strings with open quotes
1210 open_quotes = has_open_quotes(text_until_cursor)
1210 open_quotes = has_open_quotes(text_until_cursor)
1211
1211
1212 if '(' in text_until_cursor or '[' in text_until_cursor:
1212 if '(' in text_until_cursor or '[' in text_until_cursor:
1213 lsplit = text
1213 lsplit = text
1214 else:
1214 else:
1215 try:
1215 try:
1216 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1216 # arg_split ~ shlex.split, but with unicode bugs fixed by us
1217 lsplit = arg_split(text_until_cursor)[-1]
1217 lsplit = arg_split(text_until_cursor)[-1]
1218 except ValueError:
1218 except ValueError:
1219 # typically an unmatched ", or backslash without escaped char.
1219 # typically an unmatched ", or backslash without escaped char.
1220 if open_quotes:
1220 if open_quotes:
1221 lsplit = text_until_cursor.split(open_quotes)[-1]
1221 lsplit = text_until_cursor.split(open_quotes)[-1]
1222 else:
1222 else:
1223 return []
1223 return []
1224 except IndexError:
1224 except IndexError:
1225 # tab pressed on empty line
1225 # tab pressed on empty line
1226 lsplit = ""
1226 lsplit = ""
1227
1227
1228 if not open_quotes and lsplit != protect_filename(lsplit):
1228 if not open_quotes and lsplit != protect_filename(lsplit):
1229 # if protectables are found, do matching on the whole escaped name
1229 # if protectables are found, do matching on the whole escaped name
1230 has_protectables = True
1230 has_protectables = True
1231 text0,text = text,lsplit
1231 text0,text = text,lsplit
1232 else:
1232 else:
1233 has_protectables = False
1233 has_protectables = False
1234 text = os.path.expanduser(text)
1234 text = os.path.expanduser(text)
1235
1235
1236 if text == "":
1236 if text == "":
1237 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1237 return [text_prefix + protect_filename(f) for f in self.glob("*")]
1238
1238
1239 # Compute the matches from the filesystem
1239 # Compute the matches from the filesystem
1240 if sys.platform == 'win32':
1240 if sys.platform == 'win32':
1241 m0 = self.clean_glob(text)
1241 m0 = self.clean_glob(text)
1242 else:
1242 else:
1243 m0 = self.clean_glob(text.replace('\\', ''))
1243 m0 = self.clean_glob(text.replace('\\', ''))
1244
1244
1245 if has_protectables:
1245 if has_protectables:
1246 # If we had protectables, we need to revert our changes to the
1246 # If we had protectables, we need to revert our changes to the
1247 # beginning of filename so that we don't double-write the part
1247 # beginning of filename so that we don't double-write the part
1248 # of the filename we have so far
1248 # of the filename we have so far
1249 len_lsplit = len(lsplit)
1249 len_lsplit = len(lsplit)
1250 matches = [text_prefix + text0 +
1250 matches = [text_prefix + text0 +
1251 protect_filename(f[len_lsplit:]) for f in m0]
1251 protect_filename(f[len_lsplit:]) for f in m0]
1252 else:
1252 else:
1253 if open_quotes:
1253 if open_quotes:
1254 # if we have a string with an open quote, we don't need to
1254 # if we have a string with an open quote, we don't need to
1255 # protect the names beyond the quote (and we _shouldn't_, as
1255 # protect the names beyond the quote (and we _shouldn't_, as
1256 # it would cause bugs when the filesystem call is made).
1256 # it would cause bugs when the filesystem call is made).
1257 matches = m0 if sys.platform == "win32" else\
1257 matches = m0 if sys.platform == "win32" else\
1258 [protect_filename(f, open_quotes) for f in m0]
1258 [protect_filename(f, open_quotes) for f in m0]
1259 else:
1259 else:
1260 matches = [text_prefix +
1260 matches = [text_prefix +
1261 protect_filename(f) for f in m0]
1261 protect_filename(f) for f in m0]
1262
1262
1263 # Mark directories in input list by appending '/' to their names.
1263 # Mark directories in input list by appending '/' to their names.
1264 return [x+'/' if os.path.isdir(x) else x for x in matches]
1264 return [x+'/' if os.path.isdir(x) else x for x in matches]
1265
1265
1266 def magic_matches(self, text):
1266 def magic_matches(self, text):
1267 """Match magics"""
1267 """Match magics"""
1268 # Get all shell magics now rather than statically, so magics loaded at
1268 # Get all shell magics now rather than statically, so magics loaded at
1269 # runtime show up too.
1269 # runtime show up too.
1270 lsm = self.shell.magics_manager.lsmagic()
1270 lsm = self.shell.magics_manager.lsmagic()
1271 line_magics = lsm['line']
1271 line_magics = lsm['line']
1272 cell_magics = lsm['cell']
1272 cell_magics = lsm['cell']
1273 pre = self.magic_escape
1273 pre = self.magic_escape
1274 pre2 = pre+pre
1274 pre2 = pre+pre
1275
1275
1276 explicit_magic = text.startswith(pre)
1276 explicit_magic = text.startswith(pre)
1277
1277
1278 # Completion logic:
1278 # Completion logic:
1279 # - user gives %%: only do cell magics
1279 # - user gives %%: only do cell magics
1280 # - user gives %: do both line and cell magics
1280 # - user gives %: do both line and cell magics
1281 # - no prefix: do both
1281 # - no prefix: do both
1282 # In other words, line magics are skipped if the user gives %% explicitly
1282 # In other words, line magics are skipped if the user gives %% explicitly
1283 #
1283 #
1284 # We also exclude magics that match any currently visible names:
1284 # We also exclude magics that match any currently visible names:
1285 # https://github.com/ipython/ipython/issues/4877, unless the user has
1285 # https://github.com/ipython/ipython/issues/4877, unless the user has
1286 # typed a %:
1286 # typed a %:
1287 # https://github.com/ipython/ipython/issues/10754
1287 # https://github.com/ipython/ipython/issues/10754
1288 bare_text = text.lstrip(pre)
1288 bare_text = text.lstrip(pre)
1289 global_matches = self.global_matches(bare_text)
1289 global_matches = self.global_matches(bare_text)
1290 if not explicit_magic:
1290 if not explicit_magic:
1291 def matches(magic):
1291 def matches(magic):
1292 """
1292 """
1293 Filter magics, in particular remove magics that match
1293 Filter magics, in particular remove magics that match
1294 a name present in global namespace.
1294 a name present in global namespace.
1295 """
1295 """
1296 return ( magic.startswith(bare_text) and
1296 return ( magic.startswith(bare_text) and
1297 magic not in global_matches )
1297 magic not in global_matches )
1298 else:
1298 else:
1299 def matches(magic):
1299 def matches(magic):
1300 return magic.startswith(bare_text)
1300 return magic.startswith(bare_text)
1301
1301
1302 comp = [ pre2+m for m in cell_magics if matches(m)]
1302 comp = [ pre2+m for m in cell_magics if matches(m)]
1303 if not text.startswith(pre2):
1303 if not text.startswith(pre2):
1304 comp += [ pre+m for m in line_magics if matches(m)]
1304 comp += [ pre+m for m in line_magics if matches(m)]
1305
1305
1306 return comp
1306 return comp
1307
1307
1308 def magic_config_matches(self, text:str) -> List[str]:
1308 def magic_config_matches(self, text:str) -> List[str]:
1309 """ Match class names and attributes for %config magic """
1309 """ Match class names and attributes for %config magic """
1310 texts = text.strip().split()
1310 texts = text.strip().split()
1311
1311
1312 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1312 if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
1313 # get all configuration classes
1313 # get all configuration classes
1314 classes = sorted(set([ c for c in self.shell.configurables
1314 classes = sorted(set([ c for c in self.shell.configurables
1315 if c.__class__.class_traits(config=True)
1315 if c.__class__.class_traits(config=True)
1316 ]), key=lambda x: x.__class__.__name__)
1316 ]), key=lambda x: x.__class__.__name__)
1317 classnames = [ c.__class__.__name__ for c in classes ]
1317 classnames = [ c.__class__.__name__ for c in classes ]
1318
1318
1319 # return all classnames if config or %config is given
1319 # return all classnames if config or %config is given
1320 if len(texts) == 1:
1320 if len(texts) == 1:
1321 return classnames
1321 return classnames
1322
1322
1323 # match classname
1323 # match classname
1324 classname_texts = texts[1].split('.')
1324 classname_texts = texts[1].split('.')
1325 classname = classname_texts[0]
1325 classname = classname_texts[0]
1326 classname_matches = [ c for c in classnames
1326 classname_matches = [ c for c in classnames
1327 if c.startswith(classname) ]
1327 if c.startswith(classname) ]
1328
1328
1329 # return matched classes or the matched class with attributes
1329 # return matched classes or the matched class with attributes
1330 if texts[1].find('.') < 0:
1330 if texts[1].find('.') < 0:
1331 return classname_matches
1331 return classname_matches
1332 elif len(classname_matches) == 1 and \
1332 elif len(classname_matches) == 1 and \
1333 classname_matches[0] == classname:
1333 classname_matches[0] == classname:
1334 cls = classes[classnames.index(classname)].__class__
1334 cls = classes[classnames.index(classname)].__class__
1335 help = cls.class_get_help()
1335 help = cls.class_get_help()
1336 # strip leading '--' from cl-args:
1336 # strip leading '--' from cl-args:
1337 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1337 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1338 return [ attr.split('=')[0]
1338 return [ attr.split('=')[0]
1339 for attr in help.strip().splitlines()
1339 for attr in help.strip().splitlines()
1340 if attr.startswith(texts[1]) ]
1340 if attr.startswith(texts[1]) ]
1341 return []
1341 return []
1342
1342
1343 def magic_color_matches(self, text:str) -> List[str] :
1343 def magic_color_matches(self, text:str) -> List[str] :
1344 """ Match color schemes for %colors magic"""
1344 """ Match color schemes for %colors magic"""
1345 texts = text.split()
1345 texts = text.split()
1346 if text.endswith(' '):
1346 if text.endswith(' '):
1347 # .split() strips off the trailing whitespace. Add '' back
1347 # .split() strips off the trailing whitespace. Add '' back
1348 # so that: '%colors ' -> ['%colors', '']
1348 # so that: '%colors ' -> ['%colors', '']
1349 texts.append('')
1349 texts.append('')
1350
1350
1351 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1351 if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
1352 prefix = texts[1]
1352 prefix = texts[1]
1353 return [ color for color in InspectColors.keys()
1353 return [ color for color in InspectColors.keys()
1354 if color.startswith(prefix) ]
1354 if color.startswith(prefix) ]
1355 return []
1355 return []
1356
1356
1357 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str):
1357 def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str):
1358 """
1358 """
1359
1359
1360 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1360 Return a list of :any:`jedi.api.Completions` object from a ``text`` and
1361 cursor position.
1361 cursor position.
1362
1362
1363 Parameters
1363 Parameters
1364 ----------
1364 ----------
1365 cursor_column : int
1365 cursor_column : int
1366 column position of the cursor in ``text``, 0-indexed.
1366 column position of the cursor in ``text``, 0-indexed.
1367 cursor_line : int
1367 cursor_line : int
1368 line position of the cursor in ``text``, 0-indexed
1368 line position of the cursor in ``text``, 0-indexed
1369 text : str
1369 text : str
1370 text to complete
1370 text to complete
1371
1371
1372 Debugging
1372 Debugging
1373 ---------
1373 ---------
1374
1374
1375 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1375 If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
1376 object containing a string with the Jedi debug information attached.
1376 object containing a string with the Jedi debug information attached.
1377 """
1377 """
1378 namespaces = [self.namespace]
1378 namespaces = [self.namespace]
1379 if self.global_namespace is not None:
1379 if self.global_namespace is not None:
1380 namespaces.append(self.global_namespace)
1380 namespaces.append(self.global_namespace)
1381
1381
1382 completion_filter = lambda x:x
1382 completion_filter = lambda x:x
1383 offset = cursor_to_position(text, cursor_line, cursor_column)
1383 offset = cursor_to_position(text, cursor_line, cursor_column)
1384 # filter output if we are completing for object members
1384 # filter output if we are completing for object members
1385 if offset:
1385 if offset:
1386 pre = text[offset-1]
1386 pre = text[offset-1]
1387 if pre == '.':
1387 if pre == '.':
1388 if self.omit__names == 2:
1388 if self.omit__names == 2:
1389 completion_filter = lambda c:not c.name.startswith('_')
1389 completion_filter = lambda c:not c.name.startswith('_')
1390 elif self.omit__names == 1:
1390 elif self.omit__names == 1:
1391 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1391 completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
1392 elif self.omit__names == 0:
1392 elif self.omit__names == 0:
1393 completion_filter = lambda x:x
1393 completion_filter = lambda x:x
1394 else:
1394 else:
1395 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1395 raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
1396
1396
1397 interpreter = jedi.Interpreter(text[:offset], namespaces)
1397 interpreter = jedi.Interpreter(text[:offset], namespaces)
1398 try_jedi = True
1398 try_jedi = True
1399
1399
1400 try:
1400 try:
1401 # find the first token in the current tree -- if it is a ' or " then we are in a string
1401 # find the first token in the current tree -- if it is a ' or " then we are in a string
1402 completing_string = False
1402 completing_string = False
1403 try:
1403 try:
1404 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1404 first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
1405 except StopIteration:
1405 except StopIteration:
1406 pass
1406 pass
1407 else:
1407 else:
1408 # note the value may be ', ", or it may also be ''' or """, or
1408 # note the value may be ', ", or it may also be ''' or """, or
1409 # in some cases, """what/you/typed..., but all of these are
1409 # in some cases, """what/you/typed..., but all of these are
1410 # strings.
1410 # strings.
1411 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1411 completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
1412
1412
1413 # if we are in a string jedi is likely not the right candidate for
1413 # if we are in a string jedi is likely not the right candidate for
1414 # now. Skip it.
1414 # now. Skip it.
1415 try_jedi = not completing_string
1415 try_jedi = not completing_string
1416 except Exception as e:
1416 except Exception as e:
1417 # many of things can go wrong, we are using private API just don't crash.
1417 # many of things can go wrong, we are using private API just don't crash.
1418 if self.debug:
1418 if self.debug:
1419 print("Error detecting if completing a non-finished string :", e, '|')
1419 print("Error detecting if completing a non-finished string :", e, '|')
1420
1420
1421 if not try_jedi:
1421 if not try_jedi:
1422 return []
1422 return []
1423 try:
1423 try:
1424 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1424 return filter(completion_filter, interpreter.complete(column=cursor_column, line=cursor_line + 1))
1425 except Exception as e:
1425 except Exception as e:
1426 if self.debug:
1426 if self.debug:
1427 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1427 return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
1428 else:
1428 else:
1429 return []
1429 return []
1430
1430
1431 def python_matches(self, text):
1431 def python_matches(self, text):
1432 """Match attributes or global python names"""
1432 """Match attributes or global python names"""
1433 if "." in text:
1433 if "." in text:
1434 try:
1434 try:
1435 matches = self.attr_matches(text)
1435 matches = self.attr_matches(text)
1436 if text.endswith('.') and self.omit__names:
1436 if text.endswith('.') and self.omit__names:
1437 if self.omit__names == 1:
1437 if self.omit__names == 1:
1438 # true if txt is _not_ a __ name, false otherwise:
1438 # true if txt is _not_ a __ name, false otherwise:
1439 no__name = (lambda txt:
1439 no__name = (lambda txt:
1440 re.match(r'.*\.__.*?__',txt) is None)
1440 re.match(r'.*\.__.*?__',txt) is None)
1441 else:
1441 else:
1442 # true if txt is _not_ a _ name, false otherwise:
1442 # true if txt is _not_ a _ name, false otherwise:
1443 no__name = (lambda txt:
1443 no__name = (lambda txt:
1444 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1444 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
1445 matches = filter(no__name, matches)
1445 matches = filter(no__name, matches)
1446 except NameError:
1446 except NameError:
1447 # catches <undefined attributes>.<tab>
1447 # catches <undefined attributes>.<tab>
1448 matches = []
1448 matches = []
1449 else:
1449 else:
1450 matches = self.global_matches(text)
1450 matches = self.global_matches(text)
1451 return matches
1451 return matches
1452
1452
1453 def _default_arguments_from_docstring(self, doc):
1453 def _default_arguments_from_docstring(self, doc):
1454 """Parse the first line of docstring for call signature.
1454 """Parse the first line of docstring for call signature.
1455
1455
1456 Docstring should be of the form 'min(iterable[, key=func])\n'.
1456 Docstring should be of the form 'min(iterable[, key=func])\n'.
1457 It can also parse cython docstring of the form
1457 It can also parse cython docstring of the form
1458 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1458 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
1459 """
1459 """
1460 if doc is None:
1460 if doc is None:
1461 return []
1461 return []
1462
1462
1463 #care only the firstline
1463 #care only the firstline
1464 line = doc.lstrip().splitlines()[0]
1464 line = doc.lstrip().splitlines()[0]
1465
1465
1466 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1466 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
1467 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1467 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
1468 sig = self.docstring_sig_re.search(line)
1468 sig = self.docstring_sig_re.search(line)
1469 if sig is None:
1469 if sig is None:
1470 return []
1470 return []
1471 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1471 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
1472 sig = sig.groups()[0].split(',')
1472 sig = sig.groups()[0].split(',')
1473 ret = []
1473 ret = []
1474 for s in sig:
1474 for s in sig:
1475 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1475 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
1476 ret += self.docstring_kwd_re.findall(s)
1476 ret += self.docstring_kwd_re.findall(s)
1477 return ret
1477 return ret
1478
1478
1479 def _default_arguments(self, obj):
1479 def _default_arguments(self, obj):
1480 """Return the list of default arguments of obj if it is callable,
1480 """Return the list of default arguments of obj if it is callable,
1481 or empty list otherwise."""
1481 or empty list otherwise."""
1482 call_obj = obj
1482 call_obj = obj
1483 ret = []
1483 ret = []
1484 if inspect.isbuiltin(obj):
1484 if inspect.isbuiltin(obj):
1485 pass
1485 pass
1486 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1486 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
1487 if inspect.isclass(obj):
1487 if inspect.isclass(obj):
1488 #for cython embedsignature=True the constructor docstring
1488 #for cython embedsignature=True the constructor docstring
1489 #belongs to the object itself not __init__
1489 #belongs to the object itself not __init__
1490 ret += self._default_arguments_from_docstring(
1490 ret += self._default_arguments_from_docstring(
1491 getattr(obj, '__doc__', ''))
1491 getattr(obj, '__doc__', ''))
1492 # for classes, check for __init__,__new__
1492 # for classes, check for __init__,__new__
1493 call_obj = (getattr(obj, '__init__', None) or
1493 call_obj = (getattr(obj, '__init__', None) or
1494 getattr(obj, '__new__', None))
1494 getattr(obj, '__new__', None))
1495 # for all others, check if they are __call__able
1495 # for all others, check if they are __call__able
1496 elif hasattr(obj, '__call__'):
1496 elif hasattr(obj, '__call__'):
1497 call_obj = obj.__call__
1497 call_obj = obj.__call__
1498 ret += self._default_arguments_from_docstring(
1498 ret += self._default_arguments_from_docstring(
1499 getattr(call_obj, '__doc__', ''))
1499 getattr(call_obj, '__doc__', ''))
1500
1500
1501 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1501 _keeps = (inspect.Parameter.KEYWORD_ONLY,
1502 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1502 inspect.Parameter.POSITIONAL_OR_KEYWORD)
1503
1503
1504 try:
1504 try:
1505 sig = inspect.signature(obj)
1505 sig = inspect.signature(obj)
1506 ret.extend(k for k, v in sig.parameters.items() if
1506 ret.extend(k for k, v in sig.parameters.items() if
1507 v.kind in _keeps)
1507 v.kind in _keeps)
1508 except ValueError:
1508 except ValueError:
1509 pass
1509 pass
1510
1510
1511 return list(set(ret))
1511 return list(set(ret))
1512
1512
1513 def python_func_kw_matches(self,text):
1513 def python_func_kw_matches(self,text):
1514 """Match named parameters (kwargs) of the last open function"""
1514 """Match named parameters (kwargs) of the last open function"""
1515
1515
1516 if "." in text: # a parameter cannot be dotted
1516 if "." in text: # a parameter cannot be dotted
1517 return []
1517 return []
1518 try: regexp = self.__funcParamsRegex
1518 try: regexp = self.__funcParamsRegex
1519 except AttributeError:
1519 except AttributeError:
1520 regexp = self.__funcParamsRegex = re.compile(r'''
1520 regexp = self.__funcParamsRegex = re.compile(r'''
1521 '.*?(?<!\\)' | # single quoted strings or
1521 '.*?(?<!\\)' | # single quoted strings or
1522 ".*?(?<!\\)" | # double quoted strings or
1522 ".*?(?<!\\)" | # double quoted strings or
1523 \w+ | # identifier
1523 \w+ | # identifier
1524 \S # other characters
1524 \S # other characters
1525 ''', re.VERBOSE | re.DOTALL)
1525 ''', re.VERBOSE | re.DOTALL)
1526 # 1. find the nearest identifier that comes before an unclosed
1526 # 1. find the nearest identifier that comes before an unclosed
1527 # parenthesis before the cursor
1527 # parenthesis before the cursor
1528 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1528 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
1529 tokens = regexp.findall(self.text_until_cursor)
1529 tokens = regexp.findall(self.text_until_cursor)
1530 iterTokens = reversed(tokens); openPar = 0
1530 iterTokens = reversed(tokens); openPar = 0
1531
1531
1532 for token in iterTokens:
1532 for token in iterTokens:
1533 if token == ')':
1533 if token == ')':
1534 openPar -= 1
1534 openPar -= 1
1535 elif token == '(':
1535 elif token == '(':
1536 openPar += 1
1536 openPar += 1
1537 if openPar > 0:
1537 if openPar > 0:
1538 # found the last unclosed parenthesis
1538 # found the last unclosed parenthesis
1539 break
1539 break
1540 else:
1540 else:
1541 return []
1541 return []
1542 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1542 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
1543 ids = []
1543 ids = []
1544 isId = re.compile(r'\w+$').match
1544 isId = re.compile(r'\w+$').match
1545
1545
1546 while True:
1546 while True:
1547 try:
1547 try:
1548 ids.append(next(iterTokens))
1548 ids.append(next(iterTokens))
1549 if not isId(ids[-1]):
1549 if not isId(ids[-1]):
1550 ids.pop(); break
1550 ids.pop(); break
1551 if not next(iterTokens) == '.':
1551 if not next(iterTokens) == '.':
1552 break
1552 break
1553 except StopIteration:
1553 except StopIteration:
1554 break
1554 break
1555
1555
1556 # Find all named arguments already assigned to, as to avoid suggesting
1556 # Find all named arguments already assigned to, as to avoid suggesting
1557 # them again
1557 # them again
1558 usedNamedArgs = set()
1558 usedNamedArgs = set()
1559 par_level = -1
1559 par_level = -1
1560 for token, next_token in zip(tokens, tokens[1:]):
1560 for token, next_token in zip(tokens, tokens[1:]):
1561 if token == '(':
1561 if token == '(':
1562 par_level += 1
1562 par_level += 1
1563 elif token == ')':
1563 elif token == ')':
1564 par_level -= 1
1564 par_level -= 1
1565
1565
1566 if par_level != 0:
1566 if par_level != 0:
1567 continue
1567 continue
1568
1568
1569 if next_token != '=':
1569 if next_token != '=':
1570 continue
1570 continue
1571
1571
1572 usedNamedArgs.add(token)
1572 usedNamedArgs.add(token)
1573
1573
1574 argMatches = []
1574 argMatches = []
1575 try:
1575 try:
1576 callableObj = '.'.join(ids[::-1])
1576 callableObj = '.'.join(ids[::-1])
1577 namedArgs = self._default_arguments(eval(callableObj,
1577 namedArgs = self._default_arguments(eval(callableObj,
1578 self.namespace))
1578 self.namespace))
1579
1579
1580 # Remove used named arguments from the list, no need to show twice
1580 # Remove used named arguments from the list, no need to show twice
1581 for namedArg in set(namedArgs) - usedNamedArgs:
1581 for namedArg in set(namedArgs) - usedNamedArgs:
1582 if namedArg.startswith(text):
1582 if namedArg.startswith(text):
1583 argMatches.append(u"%s=" %namedArg)
1583 argMatches.append(u"%s=" %namedArg)
1584 except:
1584 except:
1585 pass
1585 pass
1586
1586
1587 return argMatches
1587 return argMatches
1588
1588
1589 def dict_key_matches(self, text):
1589 def dict_key_matches(self, text):
1590 "Match string keys in a dictionary, after e.g. 'foo[' "
1590 "Match string keys in a dictionary, after e.g. 'foo[' "
1591 def get_keys(obj):
1591 def get_keys(obj):
1592 # Objects can define their own completions by defining an
1592 # Objects can define their own completions by defining an
1593 # _ipy_key_completions_() method.
1593 # _ipy_key_completions_() method.
1594 method = get_real_method(obj, '_ipython_key_completions_')
1594 method = get_real_method(obj, '_ipython_key_completions_')
1595 if method is not None:
1595 if method is not None:
1596 return method()
1596 return method()
1597
1597
1598 # Special case some common in-memory dict-like types
1598 # Special case some common in-memory dict-like types
1599 if isinstance(obj, dict) or\
1599 if isinstance(obj, dict) or\
1600 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1600 _safe_isinstance(obj, 'pandas', 'DataFrame'):
1601 try:
1601 try:
1602 return list(obj.keys())
1602 return list(obj.keys())
1603 except Exception:
1603 except Exception:
1604 return []
1604 return []
1605 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1605 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
1606 _safe_isinstance(obj, 'numpy', 'void'):
1606 _safe_isinstance(obj, 'numpy', 'void'):
1607 return obj.dtype.names or []
1607 return obj.dtype.names or []
1608 return []
1608 return []
1609
1609
1610 try:
1610 try:
1611 regexps = self.__dict_key_regexps
1611 regexps = self.__dict_key_regexps
1612 except AttributeError:
1612 except AttributeError:
1613 dict_key_re_fmt = r'''(?x)
1613 dict_key_re_fmt = r'''(?x)
1614 ( # match dict-referring expression wrt greedy setting
1614 ( # match dict-referring expression wrt greedy setting
1615 %s
1615 %s
1616 )
1616 )
1617 \[ # open bracket
1617 \[ # open bracket
1618 \s* # and optional whitespace
1618 \s* # and optional whitespace
1619 ([uUbB]? # string prefix (r not handled)
1619 ([uUbB]? # string prefix (r not handled)
1620 (?: # unclosed string
1620 (?: # unclosed string
1621 '(?:[^']|(?<!\\)\\')*
1621 '(?:[^']|(?<!\\)\\')*
1622 |
1622 |
1623 "(?:[^"]|(?<!\\)\\")*
1623 "(?:[^"]|(?<!\\)\\")*
1624 )
1624 )
1625 )?
1625 )?
1626 $
1626 $
1627 '''
1627 '''
1628 regexps = self.__dict_key_regexps = {
1628 regexps = self.__dict_key_regexps = {
1629 False: re.compile(dict_key_re_fmt % r'''
1629 False: re.compile(dict_key_re_fmt % r'''
1630 # identifiers separated by .
1630 # identifiers separated by .
1631 (?!\d)\w+
1631 (?!\d)\w+
1632 (?:\.(?!\d)\w+)*
1632 (?:\.(?!\d)\w+)*
1633 '''),
1633 '''),
1634 True: re.compile(dict_key_re_fmt % '''
1634 True: re.compile(dict_key_re_fmt % '''
1635 .+
1635 .+
1636 ''')
1636 ''')
1637 }
1637 }
1638
1638
1639 match = regexps[self.greedy].search(self.text_until_cursor)
1639 match = regexps[self.greedy].search(self.text_until_cursor)
1640 if match is None:
1640 if match is None:
1641 return []
1641 return []
1642
1642
1643 expr, prefix = match.groups()
1643 expr, prefix = match.groups()
1644 try:
1644 try:
1645 obj = eval(expr, self.namespace)
1645 obj = eval(expr, self.namespace)
1646 except Exception:
1646 except Exception:
1647 try:
1647 try:
1648 obj = eval(expr, self.global_namespace)
1648 obj = eval(expr, self.global_namespace)
1649 except Exception:
1649 except Exception:
1650 return []
1650 return []
1651
1651
1652 keys = get_keys(obj)
1652 keys = get_keys(obj)
1653 if not keys:
1653 if not keys:
1654 return keys
1654 return keys
1655 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1655 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1656 if not matches:
1656 if not matches:
1657 return matches
1657 return matches
1658
1658
1659 # get the cursor position of
1659 # get the cursor position of
1660 # - the text being completed
1660 # - the text being completed
1661 # - the start of the key text
1661 # - the start of the key text
1662 # - the start of the completion
1662 # - the start of the completion
1663 text_start = len(self.text_until_cursor) - len(text)
1663 text_start = len(self.text_until_cursor) - len(text)
1664 if prefix:
1664 if prefix:
1665 key_start = match.start(2)
1665 key_start = match.start(2)
1666 completion_start = key_start + token_offset
1666 completion_start = key_start + token_offset
1667 else:
1667 else:
1668 key_start = completion_start = match.end()
1668 key_start = completion_start = match.end()
1669
1669
1670 # grab the leading prefix, to make sure all completions start with `text`
1670 # grab the leading prefix, to make sure all completions start with `text`
1671 if text_start > key_start:
1671 if text_start > key_start:
1672 leading = ''
1672 leading = ''
1673 else:
1673 else:
1674 leading = text[text_start:completion_start]
1674 leading = text[text_start:completion_start]
1675
1675
1676 # the index of the `[` character
1676 # the index of the `[` character
1677 bracket_idx = match.end(1)
1677 bracket_idx = match.end(1)
1678
1678
1679 # append closing quote and bracket as appropriate
1679 # append closing quote and bracket as appropriate
1680 # this is *not* appropriate if the opening quote or bracket is outside
1680 # this is *not* appropriate if the opening quote or bracket is outside
1681 # the text given to this method
1681 # the text given to this method
1682 suf = ''
1682 suf = ''
1683 continuation = self.line_buffer[len(self.text_until_cursor):]
1683 continuation = self.line_buffer[len(self.text_until_cursor):]
1684 if key_start > text_start and closing_quote:
1684 if key_start > text_start and closing_quote:
1685 # quotes were opened inside text, maybe close them
1685 # quotes were opened inside text, maybe close them
1686 if continuation.startswith(closing_quote):
1686 if continuation.startswith(closing_quote):
1687 continuation = continuation[len(closing_quote):]
1687 continuation = continuation[len(closing_quote):]
1688 else:
1688 else:
1689 suf += closing_quote
1689 suf += closing_quote
1690 if bracket_idx > text_start:
1690 if bracket_idx > text_start:
1691 # brackets were opened inside text, maybe close them
1691 # brackets were opened inside text, maybe close them
1692 if not continuation.startswith(']'):
1692 if not continuation.startswith(']'):
1693 suf += ']'
1693 suf += ']'
1694
1694
1695 return [leading + k + suf for k in matches]
1695 return [leading + k + suf for k in matches]
1696
1696
1697 def unicode_name_matches(self, text):
1697 def unicode_name_matches(self, text):
1698 u"""Match Latex-like syntax for unicode characters base
1698 u"""Match Latex-like syntax for unicode characters base
1699 on the name of the character.
1699 on the name of the character.
1700
1700
1701 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1701 This does ``\\GREEK SMALL LETTER ETA`` -> ``Ξ·``
1702
1702
1703 Works only on valid python 3 identifier, or on combining characters that
1703 Works only on valid python 3 identifier, or on combining characters that
1704 will combine to form a valid identifier.
1704 will combine to form a valid identifier.
1705
1705
1706 Used on Python 3 only.
1706 Used on Python 3 only.
1707 """
1707 """
1708 slashpos = text.rfind('\\')
1708 slashpos = text.rfind('\\')
1709 if slashpos > -1:
1709 if slashpos > -1:
1710 s = text[slashpos+1:]
1710 s = text[slashpos+1:]
1711 try :
1711 try :
1712 unic = unicodedata.lookup(s)
1712 unic = unicodedata.lookup(s)
1713 # allow combining chars
1713 # allow combining chars
1714 if ('a'+unic).isidentifier():
1714 if ('a'+unic).isidentifier():
1715 return '\\'+s,[unic]
1715 return '\\'+s,[unic]
1716 except KeyError:
1716 except KeyError:
1717 pass
1717 pass
1718 return u'', []
1718 return u'', []
1719
1719
1720
1720
1721 def latex_matches(self, text):
1721 def latex_matches(self, text):
1722 u"""Match Latex syntax for unicode characters.
1722 u"""Match Latex syntax for unicode characters.
1723
1723
1724 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1724 This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``Ξ±``
1725 """
1725 """
1726 slashpos = text.rfind('\\')
1726 slashpos = text.rfind('\\')
1727 if slashpos > -1:
1727 if slashpos > -1:
1728 s = text[slashpos:]
1728 s = text[slashpos:]
1729 if s in latex_symbols:
1729 if s in latex_symbols:
1730 # Try to complete a full latex symbol to unicode
1730 # Try to complete a full latex symbol to unicode
1731 # \\alpha -> Ξ±
1731 # \\alpha -> Ξ±
1732 return s, [latex_symbols[s]]
1732 return s, [latex_symbols[s]]
1733 else:
1733 else:
1734 # If a user has partially typed a latex symbol, give them
1734 # If a user has partially typed a latex symbol, give them
1735 # a full list of options \al -> [\aleph, \alpha]
1735 # a full list of options \al -> [\aleph, \alpha]
1736 matches = [k for k in latex_symbols if k.startswith(s)]
1736 matches = [k for k in latex_symbols if k.startswith(s)]
1737 if matches:
1737 if matches:
1738 return s, matches
1738 return s, matches
1739 return u'', []
1739 return u'', []
1740
1740
1741 def dispatch_custom_completer(self, text):
1741 def dispatch_custom_completer(self, text):
1742 if not self.custom_completers:
1742 if not self.custom_completers:
1743 return
1743 return
1744
1744
1745 line = self.line_buffer
1745 line = self.line_buffer
1746 if not line.strip():
1746 if not line.strip():
1747 return None
1747 return None
1748
1748
1749 # Create a little structure to pass all the relevant information about
1749 # Create a little structure to pass all the relevant information about
1750 # the current completion to any custom completer.
1750 # the current completion to any custom completer.
1751 event = SimpleNamespace()
1751 event = SimpleNamespace()
1752 event.line = line
1752 event.line = line
1753 event.symbol = text
1753 event.symbol = text
1754 cmd = line.split(None,1)[0]
1754 cmd = line.split(None,1)[0]
1755 event.command = cmd
1755 event.command = cmd
1756 event.text_until_cursor = self.text_until_cursor
1756 event.text_until_cursor = self.text_until_cursor
1757
1757
1758 # for foo etc, try also to find completer for %foo
1758 # for foo etc, try also to find completer for %foo
1759 if not cmd.startswith(self.magic_escape):
1759 if not cmd.startswith(self.magic_escape):
1760 try_magic = self.custom_completers.s_matches(
1760 try_magic = self.custom_completers.s_matches(
1761 self.magic_escape + cmd)
1761 self.magic_escape + cmd)
1762 else:
1762 else:
1763 try_magic = []
1763 try_magic = []
1764
1764
1765 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1765 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1766 try_magic,
1766 try_magic,
1767 self.custom_completers.flat_matches(self.text_until_cursor)):
1767 self.custom_completers.flat_matches(self.text_until_cursor)):
1768 try:
1768 try:
1769 res = c(event)
1769 res = c(event)
1770 if res:
1770 if res:
1771 # first, try case sensitive match
1771 # first, try case sensitive match
1772 withcase = [r for r in res if r.startswith(text)]
1772 withcase = [r for r in res if r.startswith(text)]
1773 if withcase:
1773 if withcase:
1774 return withcase
1774 return withcase
1775 # if none, then case insensitive ones are ok too
1775 # if none, then case insensitive ones are ok too
1776 text_low = text.lower()
1776 text_low = text.lower()
1777 return [r for r in res if r.lower().startswith(text_low)]
1777 return [r for r in res if r.lower().startswith(text_low)]
1778 except TryNext:
1778 except TryNext:
1779 pass
1779 pass
1780 except KeyboardInterrupt:
1780 except KeyboardInterrupt:
1781 """
1781 """
1782 If custom completer take too long,
1782 If custom completer take too long,
1783 let keyboard interrupt abort and return nothing.
1783 let keyboard interrupt abort and return nothing.
1784 """
1784 """
1785 break
1785 break
1786
1786
1787 return None
1787 return None
1788
1788
1789 def completions(self, text: str, offset: int)->Iterator[Completion]:
1789 def completions(self, text: str, offset: int)->Iterator[Completion]:
1790 """
1790 """
1791 Returns an iterator over the possible completions
1791 Returns an iterator over the possible completions
1792
1792
1793 .. warning::
1793 .. warning::
1794
1794
1795 Unstable
1795 Unstable
1796
1796
1797 This function is unstable, API may change without warning.
1797 This function is unstable, API may change without warning.
1798 It will also raise unless use in proper context manager.
1798 It will also raise unless use in proper context manager.
1799
1799
1800 Parameters
1800 Parameters
1801 ----------
1801 ----------
1802
1802
1803 text:str
1803 text:str
1804 Full text of the current input, multi line string.
1804 Full text of the current input, multi line string.
1805 offset:int
1805 offset:int
1806 Integer representing the position of the cursor in ``text``. Offset
1806 Integer representing the position of the cursor in ``text``. Offset
1807 is 0-based indexed.
1807 is 0-based indexed.
1808
1808
1809 Yields
1809 Yields
1810 ------
1810 ------
1811 :any:`Completion` object
1811 :any:`Completion` object
1812
1812
1813
1813
1814 The cursor on a text can either be seen as being "in between"
1814 The cursor on a text can either be seen as being "in between"
1815 characters or "On" a character depending on the interface visible to
1815 characters or "On" a character depending on the interface visible to
1816 the user. For consistency the cursor being on "in between" characters X
1816 the user. For consistency the cursor being on "in between" characters X
1817 and Y is equivalent to the cursor being "on" character Y, that is to say
1817 and Y is equivalent to the cursor being "on" character Y, that is to say
1818 the character the cursor is on is considered as being after the cursor.
1818 the character the cursor is on is considered as being after the cursor.
1819
1819
1820 Combining characters may span more that one position in the
1820 Combining characters may span more that one position in the
1821 text.
1821 text.
1822
1822
1823
1823
1824 .. note::
1824 .. note::
1825
1825
1826 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1826 If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
1827 fake Completion token to distinguish completion returned by Jedi
1827 fake Completion token to distinguish completion returned by Jedi
1828 and usual IPython completion.
1828 and usual IPython completion.
1829
1829
1830 .. note::
1830 .. note::
1831
1831
1832 Completions are not completely deduplicated yet. If identical
1832 Completions are not completely deduplicated yet. If identical
1833 completions are coming from different sources this function does not
1833 completions are coming from different sources this function does not
1834 ensure that each completion object will only be present once.
1834 ensure that each completion object will only be present once.
1835 """
1835 """
1836 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1836 warnings.warn("_complete is a provisional API (as of IPython 6.0). "
1837 "It may change without warnings. "
1837 "It may change without warnings. "
1838 "Use in corresponding context manager.",
1838 "Use in corresponding context manager.",
1839 category=ProvisionalCompleterWarning, stacklevel=2)
1839 category=ProvisionalCompleterWarning, stacklevel=2)
1840
1840
1841 seen = set()
1841 seen = set()
1842 try:
1842 try:
1843 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1843 for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
1844 if c and (c in seen):
1844 if c and (c in seen):
1845 continue
1845 continue
1846 yield c
1846 yield c
1847 seen.add(c)
1847 seen.add(c)
1848 except KeyboardInterrupt:
1848 except KeyboardInterrupt:
1849 """if completions take too long and users send keyboard interrupt,
1849 """if completions take too long and users send keyboard interrupt,
1850 do not crash and return ASAP. """
1850 do not crash and return ASAP. """
1851 pass
1851 pass
1852
1852
1853 def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]:
1853 def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]:
1854 """
1854 """
1855 Core completion module.Same signature as :any:`completions`, with the
1855 Core completion module.Same signature as :any:`completions`, with the
1856 extra `timeout` parameter (in seconds).
1856 extra `timeout` parameter (in seconds).
1857
1857
1858
1858
1859 Computing jedi's completion ``.type`` can be quite expensive (it is a
1859 Computing jedi's completion ``.type`` can be quite expensive (it is a
1860 lazy property) and can require some warm-up, more warm up than just
1860 lazy property) and can require some warm-up, more warm up than just
1861 computing the ``name`` of a completion. The warm-up can be :
1861 computing the ``name`` of a completion. The warm-up can be :
1862
1862
1863 - Long warm-up the first time a module is encountered after
1863 - Long warm-up the first time a module is encountered after
1864 install/update: actually build parse/inference tree.
1864 install/update: actually build parse/inference tree.
1865
1865
1866 - first time the module is encountered in a session: load tree from
1866 - first time the module is encountered in a session: load tree from
1867 disk.
1867 disk.
1868
1868
1869 We don't want to block completions for tens of seconds so we give the
1869 We don't want to block completions for tens of seconds so we give the
1870 completer a "budget" of ``_timeout`` seconds per invocation to compute
1870 completer a "budget" of ``_timeout`` seconds per invocation to compute
1871 completions types, the completions that have not yet been computed will
1871 completions types, the completions that have not yet been computed will
1872 be marked as "unknown" an will have a chance to be computed next round
1872 be marked as "unknown" an will have a chance to be computed next round
1873 are things get cached.
1873 are things get cached.
1874
1874
1875 Keep in mind that Jedi is not the only thing treating the completion so
1875 Keep in mind that Jedi is not the only thing treating the completion so
1876 keep the timeout short-ish as if we take more than 0.3 second we still
1876 keep the timeout short-ish as if we take more than 0.3 second we still
1877 have lots of processing to do.
1877 have lots of processing to do.
1878
1878
1879 """
1879 """
1880 deadline = time.monotonic() + _timeout
1880 deadline = time.monotonic() + _timeout
1881
1881
1882
1882
1883 before = full_text[:offset]
1883 before = full_text[:offset]
1884 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1884 cursor_line, cursor_column = position_to_cursor(full_text, offset)
1885
1885
1886 matched_text, matches, matches_origin, jedi_matches = self._complete(
1886 matched_text, matches, matches_origin, jedi_matches = self._complete(
1887 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1887 full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
1888
1888
1889 iter_jm = iter(jedi_matches)
1889 iter_jm = iter(jedi_matches)
1890 if _timeout:
1890 if _timeout:
1891 for jm in iter_jm:
1891 for jm in iter_jm:
1892 try:
1892 try:
1893 type_ = jm.type
1893 type_ = jm.type
1894 except Exception:
1894 except Exception:
1895 if self.debug:
1895 if self.debug:
1896 print("Error in Jedi getting type of ", jm)
1896 print("Error in Jedi getting type of ", jm)
1897 type_ = None
1897 type_ = None
1898 delta = len(jm.name_with_symbols) - len(jm.complete)
1898 delta = len(jm.name_with_symbols) - len(jm.complete)
1899 if type_ == 'function':
1899 if type_ == 'function':
1900 signature = _make_signature(jm)
1900 signature = _make_signature(jm)
1901 else:
1901 else:
1902 signature = ''
1902 signature = ''
1903 yield Completion(start=offset - delta,
1903 yield Completion(start=offset - delta,
1904 end=offset,
1904 end=offset,
1905 text=jm.name_with_symbols,
1905 text=jm.name_with_symbols,
1906 type=type_,
1906 type=type_,
1907 signature=signature,
1907 signature=signature,
1908 _origin='jedi')
1908 _origin='jedi')
1909
1909
1910 if time.monotonic() > deadline:
1910 if time.monotonic() > deadline:
1911 break
1911 break
1912
1912
1913 for jm in iter_jm:
1913 for jm in iter_jm:
1914 delta = len(jm.name_with_symbols) - len(jm.complete)
1914 delta = len(jm.name_with_symbols) - len(jm.complete)
1915 yield Completion(start=offset - delta,
1915 yield Completion(start=offset - delta,
1916 end=offset,
1916 end=offset,
1917 text=jm.name_with_symbols,
1917 text=jm.name_with_symbols,
1918 type='<unknown>', # don't compute type for speed
1918 type='<unknown>', # don't compute type for speed
1919 _origin='jedi',
1919 _origin='jedi',
1920 signature='')
1920 signature='')
1921
1921
1922
1922
1923 start_offset = before.rfind(matched_text)
1923 start_offset = before.rfind(matched_text)
1924
1924
1925 # TODO:
1925 # TODO:
1926 # Suppress this, right now just for debug.
1926 # Suppress this, right now just for debug.
1927 if jedi_matches and matches and self.debug:
1927 if jedi_matches and matches and self.debug:
1928 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
1928 yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
1929 _origin='debug', type='none', signature='')
1929 _origin='debug', type='none', signature='')
1930
1930
1931 # I'm unsure if this is always true, so let's assert and see if it
1931 # I'm unsure if this is always true, so let's assert and see if it
1932 # crash
1932 # crash
1933 assert before.endswith(matched_text)
1933 assert before.endswith(matched_text)
1934 for m, t in zip(matches, matches_origin):
1934 for m, t in zip(matches, matches_origin):
1935 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
1935 yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
1936
1936
1937
1937
1938 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1938 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1939 """Find completions for the given text and line context.
1939 """Find completions for the given text and line context.
1940
1940
1941 Note that both the text and the line_buffer are optional, but at least
1941 Note that both the text and the line_buffer are optional, but at least
1942 one of them must be given.
1942 one of them must be given.
1943
1943
1944 Parameters
1944 Parameters
1945 ----------
1945 ----------
1946 text : string, optional
1946 text : string, optional
1947 Text to perform the completion on. If not given, the line buffer
1947 Text to perform the completion on. If not given, the line buffer
1948 is split using the instance's CompletionSplitter object.
1948 is split using the instance's CompletionSplitter object.
1949
1949
1950 line_buffer : string, optional
1950 line_buffer : string, optional
1951 If not given, the completer attempts to obtain the current line
1951 If not given, the completer attempts to obtain the current line
1952 buffer via readline. This keyword allows clients which are
1952 buffer via readline. This keyword allows clients which are
1953 requesting for text completions in non-readline contexts to inform
1953 requesting for text completions in non-readline contexts to inform
1954 the completer of the entire text.
1954 the completer of the entire text.
1955
1955
1956 cursor_pos : int, optional
1956 cursor_pos : int, optional
1957 Index of the cursor in the full line buffer. Should be provided by
1957 Index of the cursor in the full line buffer. Should be provided by
1958 remote frontends where kernel has no access to frontend state.
1958 remote frontends where kernel has no access to frontend state.
1959
1959
1960 Returns
1960 Returns
1961 -------
1961 -------
1962 text : str
1962 text : str
1963 Text that was actually used in the completion.
1963 Text that was actually used in the completion.
1964
1964
1965 matches : list
1965 matches : list
1966 A list of completion matches.
1966 A list of completion matches.
1967
1967
1968
1968
1969 .. note::
1969 .. note::
1970
1970
1971 This API is likely to be deprecated and replaced by
1971 This API is likely to be deprecated and replaced by
1972 :any:`IPCompleter.completions` in the future.
1972 :any:`IPCompleter.completions` in the future.
1973
1973
1974
1974
1975 """
1975 """
1976 warnings.warn('`Completer.complete` is pending deprecation since '
1976 warnings.warn('`Completer.complete` is pending deprecation since '
1977 'IPython 6.0 and will be replaced by `Completer.completions`.',
1977 'IPython 6.0 and will be replaced by `Completer.completions`.',
1978 PendingDeprecationWarning)
1978 PendingDeprecationWarning)
1979 # potential todo, FOLD the 3rd throw away argument of _complete
1979 # potential todo, FOLD the 3rd throw away argument of _complete
1980 # into the first 2 one.
1980 # into the first 2 one.
1981 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
1981 return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
1982
1982
1983 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
1983 def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
1984 full_text=None) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]:
1984 full_text=None) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]:
1985 """
1985 """
1986
1986
1987 Like complete but can also returns raw jedi completions as well as the
1987 Like complete but can also returns raw jedi completions as well as the
1988 origin of the completion text. This could (and should) be made much
1988 origin of the completion text. This could (and should) be made much
1989 cleaner but that will be simpler once we drop the old (and stateful)
1989 cleaner but that will be simpler once we drop the old (and stateful)
1990 :any:`complete` API.
1990 :any:`complete` API.
1991
1991
1992
1992
1993 With current provisional API, cursor_pos act both (depending on the
1993 With current provisional API, cursor_pos act both (depending on the
1994 caller) as the offset in the ``text`` or ``line_buffer``, or as the
1994 caller) as the offset in the ``text`` or ``line_buffer``, or as the
1995 ``column`` when passing multiline strings this could/should be renamed
1995 ``column`` when passing multiline strings this could/should be renamed
1996 but would add extra noise.
1996 but would add extra noise.
1997 """
1997 """
1998
1998
1999 # if the cursor position isn't given, the only sane assumption we can
1999 # if the cursor position isn't given, the only sane assumption we can
2000 # make is that it's at the end of the line (the common case)
2000 # make is that it's at the end of the line (the common case)
2001 if cursor_pos is None:
2001 if cursor_pos is None:
2002 cursor_pos = len(line_buffer) if text is None else len(text)
2002 cursor_pos = len(line_buffer) if text is None else len(text)
2003
2003
2004 if self.use_main_ns:
2004 if self.use_main_ns:
2005 self.namespace = __main__.__dict__
2005 self.namespace = __main__.__dict__
2006
2006
2007 # if text is either None or an empty string, rely on the line buffer
2007 # if text is either None or an empty string, rely on the line buffer
2008 if (not line_buffer) and full_text:
2008 if (not line_buffer) and full_text:
2009 line_buffer = full_text.split('\n')[cursor_line]
2009 line_buffer = full_text.split('\n')[cursor_line]
2010 if not text: # issue #11508: check line_buffer before calling split_line
2010 if not text: # issue #11508: check line_buffer before calling split_line
2011 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2011 text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
2012
2012
2013 if self.backslash_combining_completions:
2013 if self.backslash_combining_completions:
2014 # allow deactivation of these on windows.
2014 # allow deactivation of these on windows.
2015 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2015 base_text = text if not line_buffer else line_buffer[:cursor_pos]
2016 latex_text, latex_matches = self.latex_matches(base_text)
2016 latex_text, latex_matches = self.latex_matches(base_text)
2017 if latex_matches:
2017 if latex_matches:
2018 return latex_text, latex_matches, ['latex_matches']*len(latex_matches), ()
2018 return latex_text, latex_matches, ['latex_matches']*len(latex_matches), ()
2019 name_text = ''
2019 name_text = ''
2020 name_matches = []
2020 name_matches = []
2021 # need to add self.fwd_unicode_match() function here when done
2021 # need to add self.fwd_unicode_match() function here when done
2022 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches, self.fwd_unicode_match):
2022 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches, self.fwd_unicode_match):
2023 name_text, name_matches = meth(base_text)
2023 name_text, name_matches = meth(base_text)
2024 if name_text:
2024 if name_text:
2025 return name_text, name_matches[:MATCHES_LIMIT], \
2025 return name_text, name_matches[:MATCHES_LIMIT], \
2026 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ()
2026 [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ()
2027
2027
2028
2028
2029 # If no line buffer is given, assume the input text is all there was
2029 # If no line buffer is given, assume the input text is all there was
2030 if line_buffer is None:
2030 if line_buffer is None:
2031 line_buffer = text
2031 line_buffer = text
2032
2032
2033 self.line_buffer = line_buffer
2033 self.line_buffer = line_buffer
2034 self.text_until_cursor = self.line_buffer[:cursor_pos]
2034 self.text_until_cursor = self.line_buffer[:cursor_pos]
2035
2035
2036 # Do magic arg matches
2036 # Do magic arg matches
2037 for matcher in self.magic_arg_matchers:
2037 for matcher in self.magic_arg_matchers:
2038 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2038 matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
2039 if matches:
2039 if matches:
2040 origins = [matcher.__qualname__] * len(matches)
2040 origins = [matcher.__qualname__] * len(matches)
2041 return text, matches, origins, ()
2041 return text, matches, origins, ()
2042
2042
2043 # Start with a clean slate of completions
2043 # Start with a clean slate of completions
2044 matches = []
2044 matches = []
2045
2045
2046 # FIXME: we should extend our api to return a dict with completions for
2046 # FIXME: we should extend our api to return a dict with completions for
2047 # different types of objects. The rlcomplete() method could then
2047 # different types of objects. The rlcomplete() method could then
2048 # simply collapse the dict into a list for readline, but we'd have
2048 # simply collapse the dict into a list for readline, but we'd have
2049 # richer completion semantics in other environments.
2049 # richer completion semantics in other environments.
2050 completions = ()
2050 completions = ()
2051 if self.use_jedi:
2051 if self.use_jedi:
2052 if not full_text:
2052 if not full_text:
2053 full_text = line_buffer
2053 full_text = line_buffer
2054 completions = self._jedi_matches(
2054 completions = self._jedi_matches(
2055 cursor_pos, cursor_line, full_text)
2055 cursor_pos, cursor_line, full_text)
2056
2056
2057 if self.merge_completions:
2057 if self.merge_completions:
2058 matches = []
2058 matches = []
2059 for matcher in self.matchers:
2059 for matcher in self.matchers:
2060 try:
2060 try:
2061 matches.extend([(m, matcher.__qualname__)
2061 matches.extend([(m, matcher.__qualname__)
2062 for m in matcher(text)])
2062 for m in matcher(text)])
2063 except:
2063 except:
2064 # Show the ugly traceback if the matcher causes an
2064 # Show the ugly traceback if the matcher causes an
2065 # exception, but do NOT crash the kernel!
2065 # exception, but do NOT crash the kernel!
2066 sys.excepthook(*sys.exc_info())
2066 sys.excepthook(*sys.exc_info())
2067 else:
2067 else:
2068 for matcher in self.matchers:
2068 for matcher in self.matchers:
2069 matches = [(m, matcher.__qualname__)
2069 matches = [(m, matcher.__qualname__)
2070 for m in matcher(text)]
2070 for m in matcher(text)]
2071 if matches:
2071 if matches:
2072 break
2072 break
2073
2073
2074 seen = set()
2074 seen = set()
2075 filtered_matches = set()
2075 filtered_matches = set()
2076 for m in matches:
2076 for m in matches:
2077 t, c = m
2077 t, c = m
2078 if t not in seen:
2078 if t not in seen:
2079 filtered_matches.add(m)
2079 filtered_matches.add(m)
2080 seen.add(t)
2080 seen.add(t)
2081
2081
2082 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2082 _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
2083
2083
2084 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2084 custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
2085
2085
2086 _filtered_matches = custom_res or _filtered_matches
2086 _filtered_matches = custom_res or _filtered_matches
2087
2087
2088 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2088 _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
2089 _matches = [m[0] for m in _filtered_matches]
2089 _matches = [m[0] for m in _filtered_matches]
2090 origins = [m[1] for m in _filtered_matches]
2090 origins = [m[1] for m in _filtered_matches]
2091
2091
2092 self.matches = _matches
2092 self.matches = _matches
2093
2093
2094 return text, _matches, origins, completions
2094 return text, _matches, origins, completions
2095
2095
2096 def fwd_unicode_match(self, text:str) -> Tuple[str, list]:
2096 def fwd_unicode_match(self, text:str) -> Tuple[str, list]:
2097 if self._names is None:
2097 if self._names is None:
2098 self._names = []
2098 self._names = []
2099 for c in range(0,0x10FFFF + 1):
2099 for c in range(0,0x10FFFF + 1):
2100 try:
2100 try:
2101 self._names.append(unicodedata.name(chr(c)))
2101 self._names.append(unicodedata.name(chr(c)))
2102 except ValueError:
2102 except ValueError:
2103 pass
2103 pass
2104
2104
2105 slashpos = text.rfind('\\')
2105 slashpos = text.rfind('\\')
2106 # if text starts with slash
2106 # if text starts with slash
2107 if slashpos > -1:
2107 if slashpos > -1:
2108 s = text[slashpos+1:]
2108 s = text[slashpos+1:]
2109 candidates = [x for x in self._names if x.startswith(s)]
2109 candidates = [x for x in self._names if x.startswith(s)]
2110 if candidates:
2110 if candidates:
2111 return s, candidates
2111 return s, candidates
2112 else:
2112 else:
2113 return '', ()
2113 return '', ()
2114
2114
2115 # if text does not start with slash
2115 # if text does not start with slash
2116 else:
2116 else:
2117 return u'', ()
2117 return u'', ()
@@ -1,3907 +1,3935 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 sys
24 import sys
25 import tempfile
25 import tempfile
26 import traceback
26 import traceback
27 import types
27 import types
28 import subprocess
28 import subprocess
29 import warnings
29 import warnings
30 from io import open as io_open
30 from io import open as io_open
31
31
32 from pathlib import Path
32 from pathlib import Path
33 from pickleshare import PickleShareDB
33 from pickleshare import PickleShareDB
34
34
35 from traitlets.config.configurable import SingletonConfigurable
35 from traitlets.config.configurable import SingletonConfigurable
36 from traitlets.utils.importstring import import_item
36 from traitlets.utils.importstring import import_item
37 from IPython.core import oinspect
37 from IPython.core import oinspect
38 from IPython.core import magic
38 from IPython.core import magic
39 from IPython.core import page
39 from IPython.core import page
40 from IPython.core import prefilter
40 from IPython.core import prefilter
41 from IPython.core import ultratb
41 from IPython.core import ultratb
42 from IPython.core.alias import Alias, AliasManager
42 from IPython.core.alias import Alias, AliasManager
43 from IPython.core.autocall import ExitAutocall
43 from IPython.core.autocall import ExitAutocall
44 from IPython.core.builtin_trap import BuiltinTrap
44 from IPython.core.builtin_trap import BuiltinTrap
45 from IPython.core.events import EventManager, available_events
45 from IPython.core.events import EventManager, available_events
46 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
46 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
47 from IPython.core.debugger import InterruptiblePdb
47 from IPython.core.debugger import InterruptiblePdb
48 from IPython.core.display_trap import DisplayTrap
48 from IPython.core.display_trap import DisplayTrap
49 from IPython.core.displayhook import DisplayHook
49 from IPython.core.displayhook import DisplayHook
50 from IPython.core.displaypub import DisplayPublisher
50 from IPython.core.displaypub import DisplayPublisher
51 from IPython.core.error import InputRejected, UsageError
51 from IPython.core.error import InputRejected, UsageError
52 from IPython.core.extensions import ExtensionManager
52 from IPython.core.extensions import ExtensionManager
53 from IPython.core.formatters import DisplayFormatter
53 from IPython.core.formatters import DisplayFormatter
54 from IPython.core.history import HistoryManager
54 from IPython.core.history import HistoryManager
55 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
55 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
56 from IPython.core.logger import Logger
56 from IPython.core.logger import Logger
57 from IPython.core.macro import Macro
57 from IPython.core.macro import Macro
58 from IPython.core.payload import PayloadManager
58 from IPython.core.payload import PayloadManager
59 from IPython.core.prefilter import PrefilterManager
59 from IPython.core.prefilter import PrefilterManager
60 from IPython.core.profiledir import ProfileDir
60 from IPython.core.profiledir import ProfileDir
61 from IPython.core.usage import default_banner
61 from IPython.core.usage import default_banner
62 from IPython.display import display
62 from IPython.display import display
63 from IPython.testing.skipdoctest import skip_doctest
63 from IPython.testing.skipdoctest import skip_doctest
64 from IPython.utils import PyColorize
64 from IPython.utils import PyColorize
65 from IPython.utils import io
65 from IPython.utils import io
66 from IPython.utils import py3compat
66 from IPython.utils import py3compat
67 from IPython.utils import openpy
67 from IPython.utils import openpy
68 from IPython.utils.decorators import undoc
68 from IPython.utils.decorators import undoc
69 from IPython.utils.io import ask_yes_no
69 from IPython.utils.io import ask_yes_no
70 from IPython.utils.ipstruct import Struct
70 from IPython.utils.ipstruct import Struct
71 from IPython.paths import get_ipython_dir
71 from IPython.paths import get_ipython_dir
72 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
72 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
73 from IPython.utils.process import system, getoutput
73 from IPython.utils.process import system, getoutput
74 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.strdispatch import StrDispatch
75 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.syspathcontext import prepended_to_syspath
76 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
77 from IPython.utils.tempdir import TemporaryDirectory
77 from IPython.utils.tempdir import TemporaryDirectory
78 from traitlets import (
78 from traitlets import (
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
80 observe, default, validate, Any
80 observe, default, validate, Any
81 )
81 )
82 from warnings import warn
82 from warnings import warn
83 from logging import error
83 from logging import error
84 import IPython.core.hooks
84 import IPython.core.hooks
85
85
86 from typing import List as ListType, Tuple, Optional
86 from typing import List as ListType, Tuple, Optional
87 from ast import AST
87 from ast import AST
88
88
89 # NoOpContext is deprecated, but ipykernel imports it from here.
89 # NoOpContext is deprecated, but ipykernel imports it from here.
90 # See https://github.com/ipython/ipykernel/issues/157
90 # See https://github.com/ipython/ipykernel/issues/157
91 # (2016, let's try to remove than in IPython 8.0)
91 # (2016, let's try to remove than in IPython 8.0)
92 from IPython.utils.contexts import NoOpContext
92 from IPython.utils.contexts import NoOpContext
93
93
94 try:
94 try:
95 import docrepr.sphinxify as sphx
95 import docrepr.sphinxify as sphx
96
96
97 def sphinxify(oinfo):
97 def sphinxify(oinfo):
98 wrapped_docstring = sphx.wrap_main_docstring(oinfo)
98 wrapped_docstring = sphx.wrap_main_docstring(oinfo)
99
99
100 def sphinxify_docstring(docstring):
100 def sphinxify_docstring(docstring):
101 with TemporaryDirectory() as dirname:
101 with TemporaryDirectory() as dirname:
102 return {
102 return {
103 "text/html": sphx.sphinxify(wrapped_docstring, dirname),
103 "text/html": sphx.sphinxify(wrapped_docstring, dirname),
104 "text/plain": docstring,
104 "text/plain": docstring,
105 }
105 }
106
106
107 return sphinxify_docstring
107 return sphinxify_docstring
108 except ImportError:
108 except ImportError:
109 sphinxify = None
109 sphinxify = None
110
110
111
111
112 class ProvisionalWarning(DeprecationWarning):
112 class ProvisionalWarning(DeprecationWarning):
113 """
113 """
114 Warning class for unstable features
114 Warning class for unstable features
115 """
115 """
116 pass
116 pass
117
117
118 if sys.version_info > (3,8):
118 if sys.version_info > (3,8):
119 from ast import Module
119 from ast import Module
120 else :
120 else :
121 # mock the new API, ignore second argument
121 # mock the new API, ignore second argument
122 # see https://github.com/ipython/ipython/issues/11590
122 # see https://github.com/ipython/ipython/issues/11590
123 from ast import Module as OriginalModule
123 from ast import Module as OriginalModule
124 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
124 Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
125
125
126 if sys.version_info > (3,6):
126 if sys.version_info > (3,6):
127 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
127 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
128 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
128 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
129 else:
129 else:
130 _assign_nodes = (ast.AugAssign, ast.Assign )
130 _assign_nodes = (ast.AugAssign, ast.Assign )
131 _single_targets_nodes = (ast.AugAssign, )
131 _single_targets_nodes = (ast.AugAssign, )
132
132
133 #-----------------------------------------------------------------------------
133 #-----------------------------------------------------------------------------
134 # Await Helpers
134 # Await Helpers
135 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
136
136
137 def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType:
137 def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType:
138 """Return a function that do not create a new local scope.
138 """Return a function that do not create a new local scope.
139
139
140 Given a function, create a clone of this function where the co_newlocal flag
140 Given a function, create a clone of this function where the co_newlocal flag
141 has been removed, making this function code actually run in the sourounding
141 has been removed, making this function code actually run in the sourounding
142 scope.
142 scope.
143
143
144 We need this in order to run asynchronous code in user level namespace.
144 We need this in order to run asynchronous code in user level namespace.
145 """
145 """
146 from types import CodeType, FunctionType
146 from types import CodeType, FunctionType
147 CO_NEWLOCALS = 0x0002
147 CO_NEWLOCALS = 0x0002
148 code = function.__code__
148 code = function.__code__
149 new_co_flags = code.co_flags & ~CO_NEWLOCALS
149 new_co_flags = code.co_flags & ~CO_NEWLOCALS
150 if sys.version_info > (3, 8, 0, 'alpha', 3):
150 if sys.version_info > (3, 8, 0, 'alpha', 3):
151 new_code = code.replace(co_flags=new_co_flags)
151 new_code = code.replace(co_flags=new_co_flags)
152 else:
152 else:
153 new_code = CodeType(
153 new_code = CodeType(
154 code.co_argcount,
154 code.co_argcount,
155 code.co_kwonlyargcount,
155 code.co_kwonlyargcount,
156 code.co_nlocals,
156 code.co_nlocals,
157 code.co_stacksize,
157 code.co_stacksize,
158 new_co_flags,
158 new_co_flags,
159 code.co_code,
159 code.co_code,
160 code.co_consts,
160 code.co_consts,
161 code.co_names,
161 code.co_names,
162 code.co_varnames,
162 code.co_varnames,
163 code.co_filename,
163 code.co_filename,
164 code.co_name,
164 code.co_name,
165 code.co_firstlineno,
165 code.co_firstlineno,
166 code.co_lnotab,
166 code.co_lnotab,
167 code.co_freevars,
167 code.co_freevars,
168 code.co_cellvars
168 code.co_cellvars
169 )
169 )
170 return FunctionType(new_code, globals(), function.__name__, function.__defaults__)
170 return FunctionType(new_code, globals(), function.__name__, function.__defaults__)
171
171
172
172
173 # we still need to run things using the asyncio eventloop, but there is no
173 # we still need to run things using the asyncio eventloop, but there is no
174 # async integration
174 # async integration
175 from .async_helpers import (_asyncio_runner, _asyncify, _pseudo_sync_runner)
175 from .async_helpers import (_asyncio_runner, _asyncify, _pseudo_sync_runner)
176 from .async_helpers import _curio_runner, _trio_runner, _should_be_async
176 from .async_helpers import _curio_runner, _trio_runner, _should_be_async
177
177
178
178
179 def _ast_asyncify(cell:str, wrapper_name:str) -> ast.Module:
179 def _ast_asyncify(cell:str, wrapper_name:str) -> ast.Module:
180 """
180 """
181 Parse a cell with top-level await and modify the AST to be able to run it later.
181 Parse a cell with top-level await and modify the AST to be able to run it later.
182
182
183 Parameter
183 Parameter
184 ---------
184 ---------
185
185
186 cell: str
186 cell: str
187 The code cell to asyncronify
187 The code cell to asyncronify
188 wrapper_name: str
188 wrapper_name: str
189 The name of the function to be used to wrap the passed `cell`. It is
189 The name of the function to be used to wrap the passed `cell`. It is
190 advised to **not** use a python identifier in order to not pollute the
190 advised to **not** use a python identifier in order to not pollute the
191 global namespace in which the function will be ran.
191 global namespace in which the function will be ran.
192
192
193 Return
193 Return
194 ------
194 ------
195
195
196 A module object AST containing **one** function named `wrapper_name`.
196 A module object AST containing **one** function named `wrapper_name`.
197
197
198 The given code is wrapped in a async-def function, parsed into an AST, and
198 The given code is wrapped in a async-def function, parsed into an AST, and
199 the resulting function definition AST is modified to return the last
199 the resulting function definition AST is modified to return the last
200 expression.
200 expression.
201
201
202 The last expression or await node is moved into a return statement at the
202 The last expression or await node is moved into a return statement at the
203 end of the function, and removed from its original location. If the last
203 end of the function, and removed from its original location. If the last
204 node is not Expr or Await nothing is done.
204 node is not Expr or Await nothing is done.
205
205
206 The function `__code__` will need to be later modified (by
206 The function `__code__` will need to be later modified (by
207 ``removed_co_newlocals``) in a subsequent step to not create new `locals()`
207 ``removed_co_newlocals``) in a subsequent step to not create new `locals()`
208 meaning that the local and global scope are the same, ie as if the body of
208 meaning that the local and global scope are the same, ie as if the body of
209 the function was at module level.
209 the function was at module level.
210
210
211 Lastly a call to `locals()` is made just before the last expression of the
211 Lastly a call to `locals()` is made just before the last expression of the
212 function, or just after the last assignment or statement to make sure the
212 function, or just after the last assignment or statement to make sure the
213 global dict is updated as python function work with a local fast cache which
213 global dict is updated as python function work with a local fast cache which
214 is updated only on `local()` calls.
214 is updated only on `local()` calls.
215 """
215 """
216
216
217 from ast import Expr, Await, Return
217 from ast import Expr, Await, Return
218 if sys.version_info >= (3,8):
218 if sys.version_info >= (3,8):
219 return ast.parse(cell)
219 return ast.parse(cell)
220 tree = ast.parse(_asyncify(cell))
220 tree = ast.parse(_asyncify(cell))
221
221
222 function_def = tree.body[0]
222 function_def = tree.body[0]
223 function_def.name = wrapper_name
223 function_def.name = wrapper_name
224 try_block = function_def.body[0]
224 try_block = function_def.body[0]
225 lastexpr = try_block.body[-1]
225 lastexpr = try_block.body[-1]
226 if isinstance(lastexpr, (Expr, Await)):
226 if isinstance(lastexpr, (Expr, Await)):
227 try_block.body[-1] = Return(lastexpr.value)
227 try_block.body[-1] = Return(lastexpr.value)
228 ast.fix_missing_locations(tree)
228 ast.fix_missing_locations(tree)
229 return tree
229 return tree
230 #-----------------------------------------------------------------------------
230 #-----------------------------------------------------------------------------
231 # Globals
231 # Globals
232 #-----------------------------------------------------------------------------
232 #-----------------------------------------------------------------------------
233
233
234 # compiled regexps for autoindent management
234 # compiled regexps for autoindent management
235 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
235 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
236
236
237 #-----------------------------------------------------------------------------
237 #-----------------------------------------------------------------------------
238 # Utilities
238 # Utilities
239 #-----------------------------------------------------------------------------
239 #-----------------------------------------------------------------------------
240
240
241 @undoc
241 @undoc
242 def softspace(file, newvalue):
242 def softspace(file, newvalue):
243 """Copied from code.py, to remove the dependency"""
243 """Copied from code.py, to remove the dependency"""
244
244
245 oldvalue = 0
245 oldvalue = 0
246 try:
246 try:
247 oldvalue = file.softspace
247 oldvalue = file.softspace
248 except AttributeError:
248 except AttributeError:
249 pass
249 pass
250 try:
250 try:
251 file.softspace = newvalue
251 file.softspace = newvalue
252 except (AttributeError, TypeError):
252 except (AttributeError, TypeError):
253 # "attribute-less object" or "read-only attributes"
253 # "attribute-less object" or "read-only attributes"
254 pass
254 pass
255 return oldvalue
255 return oldvalue
256
256
257 @undoc
257 @undoc
258 def no_op(*a, **kw):
258 def no_op(*a, **kw):
259 pass
259 pass
260
260
261
261
262 class SpaceInInput(Exception): pass
262 class SpaceInInput(Exception): pass
263
263
264
264
265 def get_default_colors():
265 def get_default_colors():
266 "DEPRECATED"
266 "DEPRECATED"
267 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
267 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
268 DeprecationWarning, stacklevel=2)
268 DeprecationWarning, stacklevel=2)
269 return 'Neutral'
269 return 'Neutral'
270
270
271
271
272 class SeparateUnicode(Unicode):
272 class SeparateUnicode(Unicode):
273 r"""A Unicode subclass to validate separate_in, separate_out, etc.
273 r"""A Unicode subclass to validate separate_in, separate_out, etc.
274
274
275 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
275 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
276 """
276 """
277
277
278 def validate(self, obj, value):
278 def validate(self, obj, value):
279 if value == '0': value = ''
279 if value == '0': value = ''
280 value = value.replace('\\n','\n')
280 value = value.replace('\\n','\n')
281 return super(SeparateUnicode, self).validate(obj, value)
281 return super(SeparateUnicode, self).validate(obj, value)
282
282
283
283
284 @undoc
284 @undoc
285 class DummyMod(object):
285 class DummyMod(object):
286 """A dummy module used for IPython's interactive module when
286 """A dummy module used for IPython's interactive module when
287 a namespace must be assigned to the module's __dict__."""
287 a namespace must be assigned to the module's __dict__."""
288 __spec__ = None
288 __spec__ = None
289
289
290
290
291 class ExecutionInfo(object):
291 class ExecutionInfo(object):
292 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
292 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
293
293
294 Stores information about what is going to happen.
294 Stores information about what is going to happen.
295 """
295 """
296 raw_cell = None
296 raw_cell = None
297 store_history = False
297 store_history = False
298 silent = False
298 silent = False
299 shell_futures = True
299 shell_futures = True
300 cell_id = None
300
301
301 def __init__(self, raw_cell, store_history, silent, shell_futures):
302 def __init__(self, raw_cell, store_history, silent, shell_futures, cell_id):
302 self.raw_cell = raw_cell
303 self.raw_cell = raw_cell
303 self.store_history = store_history
304 self.store_history = store_history
304 self.silent = silent
305 self.silent = silent
305 self.shell_futures = shell_futures
306 self.shell_futures = shell_futures
307 self.cell_id = cell_id
306
308
307 def __repr__(self):
309 def __repr__(self):
308 name = self.__class__.__qualname__
310 name = self.__class__.__qualname__
309 raw_cell = ((self.raw_cell[:50] + '..')
311 raw_cell = (
310 if len(self.raw_cell) > 50 else self.raw_cell)
312 (self.raw_cell[:50] + "..") if len(self.raw_cell) > 50 else self.raw_cell
311 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
313 )
312 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
314 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s cell_id=%s>' % (
315 name,
316 id(self),
317 raw_cell,
318 self.store_history,
319 self.silent,
320 self.shell_futures,
321 self.cell_id,
322 )
313
323
314
324
315 class ExecutionResult(object):
325 class ExecutionResult(object):
316 """The result of a call to :meth:`InteractiveShell.run_cell`
326 """The result of a call to :meth:`InteractiveShell.run_cell`
317
327
318 Stores information about what took place.
328 Stores information about what took place.
319 """
329 """
320 execution_count = None
330 execution_count = None
321 error_before_exec = None
331 error_before_exec = None
322 error_in_exec = None
332 error_in_exec = None
323 info = None
333 info = None
324 result = None
334 result = None
325
335
326 def __init__(self, info):
336 def __init__(self, info):
327 self.info = info
337 self.info = info
328
338
329 @property
339 @property
330 def success(self):
340 def success(self):
331 return (self.error_before_exec is None) and (self.error_in_exec is None)
341 return (self.error_before_exec is None) and (self.error_in_exec is None)
332
342
333 def raise_error(self):
343 def raise_error(self):
334 """Reraises error if `success` is `False`, otherwise does nothing"""
344 """Reraises error if `success` is `False`, otherwise does nothing"""
335 if self.error_before_exec is not None:
345 if self.error_before_exec is not None:
336 raise self.error_before_exec
346 raise self.error_before_exec
337 if self.error_in_exec is not None:
347 if self.error_in_exec is not None:
338 raise self.error_in_exec
348 raise self.error_in_exec
339
349
340 def __repr__(self):
350 def __repr__(self):
341 name = self.__class__.__qualname__
351 name = self.__class__.__qualname__
342 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
352 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
343 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
353 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
344
354
345
355
346 class InteractiveShell(SingletonConfigurable):
356 class InteractiveShell(SingletonConfigurable):
347 """An enhanced, interactive shell for Python."""
357 """An enhanced, interactive shell for Python."""
348
358
349 _instance = None
359 _instance = None
350
360
351 ast_transformers = List([], help=
361 ast_transformers = List([], help=
352 """
362 """
353 A list of ast.NodeTransformer subclass instances, which will be applied
363 A list of ast.NodeTransformer subclass instances, which will be applied
354 to user input before code is run.
364 to user input before code is run.
355 """
365 """
356 ).tag(config=True)
366 ).tag(config=True)
357
367
358 autocall = Enum((0,1,2), default_value=0, help=
368 autocall = Enum((0,1,2), default_value=0, help=
359 """
369 """
360 Make IPython automatically call any callable object even if you didn't
370 Make IPython automatically call any callable object even if you didn't
361 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
371 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
362 automatically. The value can be '0' to disable the feature, '1' for
372 automatically. The value can be '0' to disable the feature, '1' for
363 'smart' autocall, where it is not applied if there are no more
373 'smart' autocall, where it is not applied if there are no more
364 arguments on the line, and '2' for 'full' autocall, where all callable
374 arguments on the line, and '2' for 'full' autocall, where all callable
365 objects are automatically called (even if no arguments are present).
375 objects are automatically called (even if no arguments are present).
366 """
376 """
367 ).tag(config=True)
377 ).tag(config=True)
368
378
369 autoindent = Bool(True, help=
379 autoindent = Bool(True, help=
370 """
380 """
371 Autoindent IPython code entered interactively.
381 Autoindent IPython code entered interactively.
372 """
382 """
373 ).tag(config=True)
383 ).tag(config=True)
374
384
375 autoawait = Bool(True, help=
385 autoawait = Bool(True, help=
376 """
386 """
377 Automatically run await statement in the top level repl.
387 Automatically run await statement in the top level repl.
378 """
388 """
379 ).tag(config=True)
389 ).tag(config=True)
380
390
381 loop_runner_map ={
391 loop_runner_map ={
382 'asyncio':(_asyncio_runner, True),
392 'asyncio':(_asyncio_runner, True),
383 'curio':(_curio_runner, True),
393 'curio':(_curio_runner, True),
384 'trio':(_trio_runner, True),
394 'trio':(_trio_runner, True),
385 'sync': (_pseudo_sync_runner, False)
395 'sync': (_pseudo_sync_runner, False)
386 }
396 }
387
397
388 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
398 loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
389 allow_none=True,
399 allow_none=True,
390 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
400 help="""Select the loop runner that will be used to execute top-level asynchronous code"""
391 ).tag(config=True)
401 ).tag(config=True)
392
402
393 @default('loop_runner')
403 @default('loop_runner')
394 def _default_loop_runner(self):
404 def _default_loop_runner(self):
395 return import_item("IPython.core.interactiveshell._asyncio_runner")
405 return import_item("IPython.core.interactiveshell._asyncio_runner")
396
406
397 @validate('loop_runner')
407 @validate('loop_runner')
398 def _import_runner(self, proposal):
408 def _import_runner(self, proposal):
399 if isinstance(proposal.value, str):
409 if isinstance(proposal.value, str):
400 if proposal.value in self.loop_runner_map:
410 if proposal.value in self.loop_runner_map:
401 runner, autoawait = self.loop_runner_map[proposal.value]
411 runner, autoawait = self.loop_runner_map[proposal.value]
402 self.autoawait = autoawait
412 self.autoawait = autoawait
403 return runner
413 return runner
404 runner = import_item(proposal.value)
414 runner = import_item(proposal.value)
405 if not callable(runner):
415 if not callable(runner):
406 raise ValueError('loop_runner must be callable')
416 raise ValueError('loop_runner must be callable')
407 return runner
417 return runner
408 if not callable(proposal.value):
418 if not callable(proposal.value):
409 raise ValueError('loop_runner must be callable')
419 raise ValueError('loop_runner must be callable')
410 return proposal.value
420 return proposal.value
411
421
412 automagic = Bool(True, help=
422 automagic = Bool(True, help=
413 """
423 """
414 Enable magic commands to be called without the leading %.
424 Enable magic commands to be called without the leading %.
415 """
425 """
416 ).tag(config=True)
426 ).tag(config=True)
417
427
418 banner1 = Unicode(default_banner,
428 banner1 = Unicode(default_banner,
419 help="""The part of the banner to be printed before the profile"""
429 help="""The part of the banner to be printed before the profile"""
420 ).tag(config=True)
430 ).tag(config=True)
421 banner2 = Unicode('',
431 banner2 = Unicode('',
422 help="""The part of the banner to be printed after the profile"""
432 help="""The part of the banner to be printed after the profile"""
423 ).tag(config=True)
433 ).tag(config=True)
424
434
425 cache_size = Integer(1000, help=
435 cache_size = Integer(1000, help=
426 """
436 """
427 Set the size of the output cache. The default is 1000, you can
437 Set the size of the output cache. The default is 1000, you can
428 change it permanently in your config file. Setting it to 0 completely
438 change it permanently in your config file. Setting it to 0 completely
429 disables the caching system, and the minimum value accepted is 3 (if
439 disables the caching system, and the minimum value accepted is 3 (if
430 you provide a value less than 3, it is reset to 0 and a warning is
440 you provide a value less than 3, it is reset to 0 and a warning is
431 issued). This limit is defined because otherwise you'll spend more
441 issued). This limit is defined because otherwise you'll spend more
432 time re-flushing a too small cache than working
442 time re-flushing a too small cache than working
433 """
443 """
434 ).tag(config=True)
444 ).tag(config=True)
435 color_info = Bool(True, help=
445 color_info = Bool(True, help=
436 """
446 """
437 Use colors for displaying information about objects. Because this
447 Use colors for displaying information about objects. Because this
438 information is passed through a pager (like 'less'), and some pagers
448 information is passed through a pager (like 'less'), and some pagers
439 get confused with color codes, this capability can be turned off.
449 get confused with color codes, this capability can be turned off.
440 """
450 """
441 ).tag(config=True)
451 ).tag(config=True)
442 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
452 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
443 default_value='Neutral',
453 default_value='Neutral',
444 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
454 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
445 ).tag(config=True)
455 ).tag(config=True)
446 debug = Bool(False).tag(config=True)
456 debug = Bool(False).tag(config=True)
447 disable_failing_post_execute = Bool(False,
457 disable_failing_post_execute = Bool(False,
448 help="Don't call post-execute functions that have failed in the past."
458 help="Don't call post-execute functions that have failed in the past."
449 ).tag(config=True)
459 ).tag(config=True)
450 display_formatter = Instance(DisplayFormatter, allow_none=True)
460 display_formatter = Instance(DisplayFormatter, allow_none=True)
451 displayhook_class = Type(DisplayHook)
461 displayhook_class = Type(DisplayHook)
452 display_pub_class = Type(DisplayPublisher)
462 display_pub_class = Type(DisplayPublisher)
453 compiler_class = Type(CachingCompiler)
463 compiler_class = Type(CachingCompiler)
454
464
455 sphinxify_docstring = Bool(False, help=
465 sphinxify_docstring = Bool(False, help=
456 """
466 """
457 Enables rich html representation of docstrings. (This requires the
467 Enables rich html representation of docstrings. (This requires the
458 docrepr module).
468 docrepr module).
459 """).tag(config=True)
469 """).tag(config=True)
460
470
461 @observe("sphinxify_docstring")
471 @observe("sphinxify_docstring")
462 def _sphinxify_docstring_changed(self, change):
472 def _sphinxify_docstring_changed(self, change):
463 if change['new']:
473 if change['new']:
464 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
474 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
465
475
466 enable_html_pager = Bool(False, help=
476 enable_html_pager = Bool(False, help=
467 """
477 """
468 (Provisional API) enables html representation in mime bundles sent
478 (Provisional API) enables html representation in mime bundles sent
469 to pagers.
479 to pagers.
470 """).tag(config=True)
480 """).tag(config=True)
471
481
472 @observe("enable_html_pager")
482 @observe("enable_html_pager")
473 def _enable_html_pager_changed(self, change):
483 def _enable_html_pager_changed(self, change):
474 if change['new']:
484 if change['new']:
475 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
485 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
476
486
477 data_pub_class = None
487 data_pub_class = None
478
488
479 exit_now = Bool(False)
489 exit_now = Bool(False)
480 exiter = Instance(ExitAutocall)
490 exiter = Instance(ExitAutocall)
481 @default('exiter')
491 @default('exiter')
482 def _exiter_default(self):
492 def _exiter_default(self):
483 return ExitAutocall(self)
493 return ExitAutocall(self)
484 # Monotonically increasing execution counter
494 # Monotonically increasing execution counter
485 execution_count = Integer(1)
495 execution_count = Integer(1)
486 filename = Unicode("<ipython console>")
496 filename = Unicode("<ipython console>")
487 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
497 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
488
498
489 # Used to transform cells before running them, and check whether code is complete
499 # Used to transform cells before running them, and check whether code is complete
490 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
500 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
491 ())
501 ())
492
502
493 @property
503 @property
494 def input_transformers_cleanup(self):
504 def input_transformers_cleanup(self):
495 return self.input_transformer_manager.cleanup_transforms
505 return self.input_transformer_manager.cleanup_transforms
496
506
497 input_transformers_post = List([],
507 input_transformers_post = List([],
498 help="A list of string input transformers, to be applied after IPython's "
508 help="A list of string input transformers, to be applied after IPython's "
499 "own input transformations."
509 "own input transformations."
500 )
510 )
501
511
502 @property
512 @property
503 def input_splitter(self):
513 def input_splitter(self):
504 """Make this available for backward compatibility (pre-7.0 release) with existing code.
514 """Make this available for backward compatibility (pre-7.0 release) with existing code.
505
515
506 For example, ipykernel ipykernel currently uses
516 For example, ipykernel ipykernel currently uses
507 `shell.input_splitter.check_complete`
517 `shell.input_splitter.check_complete`
508 """
518 """
509 from warnings import warn
519 from warnings import warn
510 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
520 warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
511 DeprecationWarning, stacklevel=2
521 DeprecationWarning, stacklevel=2
512 )
522 )
513 return self.input_transformer_manager
523 return self.input_transformer_manager
514
524
515 logstart = Bool(False, help=
525 logstart = Bool(False, help=
516 """
526 """
517 Start logging to the default log file in overwrite mode.
527 Start logging to the default log file in overwrite mode.
518 Use `logappend` to specify a log file to **append** logs to.
528 Use `logappend` to specify a log file to **append** logs to.
519 """
529 """
520 ).tag(config=True)
530 ).tag(config=True)
521 logfile = Unicode('', help=
531 logfile = Unicode('', help=
522 """
532 """
523 The name of the logfile to use.
533 The name of the logfile to use.
524 """
534 """
525 ).tag(config=True)
535 ).tag(config=True)
526 logappend = Unicode('', help=
536 logappend = Unicode('', help=
527 """
537 """
528 Start logging to the given file in append mode.
538 Start logging to the given file in append mode.
529 Use `logfile` to specify a log file to **overwrite** logs to.
539 Use `logfile` to specify a log file to **overwrite** logs to.
530 """
540 """
531 ).tag(config=True)
541 ).tag(config=True)
532 object_info_string_level = Enum((0,1,2), default_value=0,
542 object_info_string_level = Enum((0,1,2), default_value=0,
533 ).tag(config=True)
543 ).tag(config=True)
534 pdb = Bool(False, help=
544 pdb = Bool(False, help=
535 """
545 """
536 Automatically call the pdb debugger after every exception.
546 Automatically call the pdb debugger after every exception.
537 """
547 """
538 ).tag(config=True)
548 ).tag(config=True)
539 display_page = Bool(False,
549 display_page = Bool(False,
540 help="""If True, anything that would be passed to the pager
550 help="""If True, anything that would be passed to the pager
541 will be displayed as regular output instead."""
551 will be displayed as regular output instead."""
542 ).tag(config=True)
552 ).tag(config=True)
543
553
544 # deprecated prompt traits:
554 # deprecated prompt traits:
545
555
546 prompt_in1 = Unicode('In [\\#]: ',
556 prompt_in1 = Unicode('In [\\#]: ',
547 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
557 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
548 ).tag(config=True)
558 ).tag(config=True)
549 prompt_in2 = Unicode(' .\\D.: ',
559 prompt_in2 = Unicode(' .\\D.: ',
550 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
560 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
551 ).tag(config=True)
561 ).tag(config=True)
552 prompt_out = Unicode('Out[\\#]: ',
562 prompt_out = Unicode('Out[\\#]: ',
553 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
563 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
554 ).tag(config=True)
564 ).tag(config=True)
555 prompts_pad_left = Bool(True,
565 prompts_pad_left = Bool(True,
556 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
566 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
557 ).tag(config=True)
567 ).tag(config=True)
558
568
559 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
569 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
560 def _prompt_trait_changed(self, change):
570 def _prompt_trait_changed(self, change):
561 name = change['name']
571 name = change['name']
562 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
572 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
563 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
573 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
564 " object directly.".format(name=name))
574 " object directly.".format(name=name))
565
575
566 # protect against weird cases where self.config may not exist:
576 # protect against weird cases where self.config may not exist:
567
577
568 show_rewritten_input = Bool(True,
578 show_rewritten_input = Bool(True,
569 help="Show rewritten input, e.g. for autocall."
579 help="Show rewritten input, e.g. for autocall."
570 ).tag(config=True)
580 ).tag(config=True)
571
581
572 quiet = Bool(False).tag(config=True)
582 quiet = Bool(False).tag(config=True)
573
583
574 history_length = Integer(10000,
584 history_length = Integer(10000,
575 help='Total length of command history'
585 help='Total length of command history'
576 ).tag(config=True)
586 ).tag(config=True)
577
587
578 history_load_length = Integer(1000, help=
588 history_load_length = Integer(1000, help=
579 """
589 """
580 The number of saved history entries to be loaded
590 The number of saved history entries to be loaded
581 into the history buffer at startup.
591 into the history buffer at startup.
582 """
592 """
583 ).tag(config=True)
593 ).tag(config=True)
584
594
585 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
595 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
586 default_value='last_expr',
596 default_value='last_expr',
587 help="""
597 help="""
588 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
598 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
589 which nodes should be run interactively (displaying output from expressions).
599 which nodes should be run interactively (displaying output from expressions).
590 """
600 """
591 ).tag(config=True)
601 ).tag(config=True)
592
602
593 # TODO: this part of prompt management should be moved to the frontends.
603 # TODO: this part of prompt management should be moved to the frontends.
594 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
604 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
595 separate_in = SeparateUnicode('\n').tag(config=True)
605 separate_in = SeparateUnicode('\n').tag(config=True)
596 separate_out = SeparateUnicode('').tag(config=True)
606 separate_out = SeparateUnicode('').tag(config=True)
597 separate_out2 = SeparateUnicode('').tag(config=True)
607 separate_out2 = SeparateUnicode('').tag(config=True)
598 wildcards_case_sensitive = Bool(True).tag(config=True)
608 wildcards_case_sensitive = Bool(True).tag(config=True)
599 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
609 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
600 default_value='Context',
610 default_value='Context',
601 help="Switch modes for the IPython exception handlers."
611 help="Switch modes for the IPython exception handlers."
602 ).tag(config=True)
612 ).tag(config=True)
603
613
604 # Subcomponents of InteractiveShell
614 # Subcomponents of InteractiveShell
605 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
615 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
606 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
616 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
607 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
617 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
608 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
618 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
609 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
619 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
610 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
620 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
611 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
621 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
612 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
622 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
613
623
614 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
624 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
615 @property
625 @property
616 def profile(self):
626 def profile(self):
617 if self.profile_dir is not None:
627 if self.profile_dir is not None:
618 name = os.path.basename(self.profile_dir.location)
628 name = os.path.basename(self.profile_dir.location)
619 return name.replace('profile_','')
629 return name.replace('profile_','')
620
630
621
631
622 # Private interface
632 # Private interface
623 _post_execute = Dict()
633 _post_execute = Dict()
624
634
625 # Tracks any GUI loop loaded for pylab
635 # Tracks any GUI loop loaded for pylab
626 pylab_gui_select = None
636 pylab_gui_select = None
627
637
628 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
638 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
629
639
630 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
640 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
631
641
632 def __init__(self, ipython_dir=None, profile_dir=None,
642 def __init__(self, ipython_dir=None, profile_dir=None,
633 user_module=None, user_ns=None,
643 user_module=None, user_ns=None,
634 custom_exceptions=((), None), **kwargs):
644 custom_exceptions=((), None), **kwargs):
635 # This is where traits with a config_key argument are updated
645 # This is where traits with a config_key argument are updated
636 # from the values on config.
646 # from the values on config.
637 super(InteractiveShell, self).__init__(**kwargs)
647 super(InteractiveShell, self).__init__(**kwargs)
638 if 'PromptManager' in self.config:
648 if 'PromptManager' in self.config:
639 warn('As of IPython 5.0 `PromptManager` config will have no effect'
649 warn('As of IPython 5.0 `PromptManager` config will have no effect'
640 ' and has been replaced by TerminalInteractiveShell.prompts_class')
650 ' and has been replaced by TerminalInteractiveShell.prompts_class')
641 self.configurables = [self]
651 self.configurables = [self]
642
652
643 # These are relatively independent and stateless
653 # These are relatively independent and stateless
644 self.init_ipython_dir(ipython_dir)
654 self.init_ipython_dir(ipython_dir)
645 self.init_profile_dir(profile_dir)
655 self.init_profile_dir(profile_dir)
646 self.init_instance_attrs()
656 self.init_instance_attrs()
647 self.init_environment()
657 self.init_environment()
648
658
649 # Check if we're in a virtualenv, and set up sys.path.
659 # Check if we're in a virtualenv, and set up sys.path.
650 self.init_virtualenv()
660 self.init_virtualenv()
651
661
652 # Create namespaces (user_ns, user_global_ns, etc.)
662 # Create namespaces (user_ns, user_global_ns, etc.)
653 self.init_create_namespaces(user_module, user_ns)
663 self.init_create_namespaces(user_module, user_ns)
654 # This has to be done after init_create_namespaces because it uses
664 # This has to be done after init_create_namespaces because it uses
655 # something in self.user_ns, but before init_sys_modules, which
665 # something in self.user_ns, but before init_sys_modules, which
656 # is the first thing to modify sys.
666 # is the first thing to modify sys.
657 # TODO: When we override sys.stdout and sys.stderr before this class
667 # TODO: When we override sys.stdout and sys.stderr before this class
658 # is created, we are saving the overridden ones here. Not sure if this
668 # is created, we are saving the overridden ones here. Not sure if this
659 # is what we want to do.
669 # is what we want to do.
660 self.save_sys_module_state()
670 self.save_sys_module_state()
661 self.init_sys_modules()
671 self.init_sys_modules()
662
672
663 # While we're trying to have each part of the code directly access what
673 # While we're trying to have each part of the code directly access what
664 # it needs without keeping redundant references to objects, we have too
674 # it needs without keeping redundant references to objects, we have too
665 # much legacy code that expects ip.db to exist.
675 # much legacy code that expects ip.db to exist.
666 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
676 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
667
677
668 self.init_history()
678 self.init_history()
669 self.init_encoding()
679 self.init_encoding()
670 self.init_prefilter()
680 self.init_prefilter()
671
681
672 self.init_syntax_highlighting()
682 self.init_syntax_highlighting()
673 self.init_hooks()
683 self.init_hooks()
674 self.init_events()
684 self.init_events()
675 self.init_pushd_popd_magic()
685 self.init_pushd_popd_magic()
676 self.init_user_ns()
686 self.init_user_ns()
677 self.init_logger()
687 self.init_logger()
678 self.init_builtins()
688 self.init_builtins()
679
689
680 # The following was in post_config_initialization
690 # The following was in post_config_initialization
681 self.init_inspector()
691 self.init_inspector()
682 self.raw_input_original = input
692 self.raw_input_original = input
683 self.init_completer()
693 self.init_completer()
684 # TODO: init_io() needs to happen before init_traceback handlers
694 # TODO: init_io() needs to happen before init_traceback handlers
685 # because the traceback handlers hardcode the stdout/stderr streams.
695 # because the traceback handlers hardcode the stdout/stderr streams.
686 # This logic in in debugger.Pdb and should eventually be changed.
696 # This logic in in debugger.Pdb and should eventually be changed.
687 self.init_io()
697 self.init_io()
688 self.init_traceback_handlers(custom_exceptions)
698 self.init_traceback_handlers(custom_exceptions)
689 self.init_prompts()
699 self.init_prompts()
690 self.init_display_formatter()
700 self.init_display_formatter()
691 self.init_display_pub()
701 self.init_display_pub()
692 self.init_data_pub()
702 self.init_data_pub()
693 self.init_displayhook()
703 self.init_displayhook()
694 self.init_magics()
704 self.init_magics()
695 self.init_alias()
705 self.init_alias()
696 self.init_logstart()
706 self.init_logstart()
697 self.init_pdb()
707 self.init_pdb()
698 self.init_extension_manager()
708 self.init_extension_manager()
699 self.init_payload()
709 self.init_payload()
700 self.init_deprecation_warnings()
710 self.init_deprecation_warnings()
701 self.hooks.late_startup_hook()
711 self.hooks.late_startup_hook()
702 self.events.trigger('shell_initialized', self)
712 self.events.trigger('shell_initialized', self)
703 atexit.register(self.atexit_operations)
713 atexit.register(self.atexit_operations)
704
714
705 # The trio runner is used for running Trio in the foreground thread. It
715 # The trio runner is used for running Trio in the foreground thread. It
706 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
716 # is different from `_trio_runner(async_fn)` in `async_helpers.py`
707 # which calls `trio.run()` for every cell. This runner runs all cells
717 # which calls `trio.run()` for every cell. This runner runs all cells
708 # inside a single Trio event loop. If used, it is set from
718 # inside a single Trio event loop. If used, it is set from
709 # `ipykernel.kernelapp`.
719 # `ipykernel.kernelapp`.
710 self.trio_runner = None
720 self.trio_runner = None
711
721
712 def get_ipython(self):
722 def get_ipython(self):
713 """Return the currently running IPython instance."""
723 """Return the currently running IPython instance."""
714 return self
724 return self
715
725
716 #-------------------------------------------------------------------------
726 #-------------------------------------------------------------------------
717 # Trait changed handlers
727 # Trait changed handlers
718 #-------------------------------------------------------------------------
728 #-------------------------------------------------------------------------
719 @observe('ipython_dir')
729 @observe('ipython_dir')
720 def _ipython_dir_changed(self, change):
730 def _ipython_dir_changed(self, change):
721 ensure_dir_exists(change['new'])
731 ensure_dir_exists(change['new'])
722
732
723 def set_autoindent(self,value=None):
733 def set_autoindent(self,value=None):
724 """Set the autoindent flag.
734 """Set the autoindent flag.
725
735
726 If called with no arguments, it acts as a toggle."""
736 If called with no arguments, it acts as a toggle."""
727 if value is None:
737 if value is None:
728 self.autoindent = not self.autoindent
738 self.autoindent = not self.autoindent
729 else:
739 else:
730 self.autoindent = value
740 self.autoindent = value
731
741
732 def set_trio_runner(self, tr):
742 def set_trio_runner(self, tr):
733 self.trio_runner = tr
743 self.trio_runner = tr
734
744
735 #-------------------------------------------------------------------------
745 #-------------------------------------------------------------------------
736 # init_* methods called by __init__
746 # init_* methods called by __init__
737 #-------------------------------------------------------------------------
747 #-------------------------------------------------------------------------
738
748
739 def init_ipython_dir(self, ipython_dir):
749 def init_ipython_dir(self, ipython_dir):
740 if ipython_dir is not None:
750 if ipython_dir is not None:
741 self.ipython_dir = ipython_dir
751 self.ipython_dir = ipython_dir
742 return
752 return
743
753
744 self.ipython_dir = get_ipython_dir()
754 self.ipython_dir = get_ipython_dir()
745
755
746 def init_profile_dir(self, profile_dir):
756 def init_profile_dir(self, profile_dir):
747 if profile_dir is not None:
757 if profile_dir is not None:
748 self.profile_dir = profile_dir
758 self.profile_dir = profile_dir
749 return
759 return
750 self.profile_dir = ProfileDir.create_profile_dir_by_name(
760 self.profile_dir = ProfileDir.create_profile_dir_by_name(
751 self.ipython_dir, "default"
761 self.ipython_dir, "default"
752 )
762 )
753
763
754 def init_instance_attrs(self):
764 def init_instance_attrs(self):
755 self.more = False
765 self.more = False
756
766
757 # command compiler
767 # command compiler
758 self.compile = self.compiler_class()
768 self.compile = self.compiler_class()
759
769
760 # Make an empty namespace, which extension writers can rely on both
770 # Make an empty namespace, which extension writers can rely on both
761 # existing and NEVER being used by ipython itself. This gives them a
771 # existing and NEVER being used by ipython itself. This gives them a
762 # convenient location for storing additional information and state
772 # convenient location for storing additional information and state
763 # their extensions may require, without fear of collisions with other
773 # their extensions may require, without fear of collisions with other
764 # ipython names that may develop later.
774 # ipython names that may develop later.
765 self.meta = Struct()
775 self.meta = Struct()
766
776
767 # Temporary files used for various purposes. Deleted at exit.
777 # Temporary files used for various purposes. Deleted at exit.
768 self.tempfiles = []
778 self.tempfiles = []
769 self.tempdirs = []
779 self.tempdirs = []
770
780
771 # keep track of where we started running (mainly for crash post-mortem)
781 # keep track of where we started running (mainly for crash post-mortem)
772 # This is not being used anywhere currently.
782 # This is not being used anywhere currently.
773 self.starting_dir = os.getcwd()
783 self.starting_dir = os.getcwd()
774
784
775 # Indentation management
785 # Indentation management
776 self.indent_current_nsp = 0
786 self.indent_current_nsp = 0
777
787
778 # Dict to track post-execution functions that have been registered
788 # Dict to track post-execution functions that have been registered
779 self._post_execute = {}
789 self._post_execute = {}
780
790
781 def init_environment(self):
791 def init_environment(self):
782 """Any changes we need to make to the user's environment."""
792 """Any changes we need to make to the user's environment."""
783 pass
793 pass
784
794
785 def init_encoding(self):
795 def init_encoding(self):
786 # Get system encoding at startup time. Certain terminals (like Emacs
796 # Get system encoding at startup time. Certain terminals (like Emacs
787 # under Win32 have it set to None, and we need to have a known valid
797 # under Win32 have it set to None, and we need to have a known valid
788 # encoding to use in the raw_input() method
798 # encoding to use in the raw_input() method
789 try:
799 try:
790 self.stdin_encoding = sys.stdin.encoding or 'ascii'
800 self.stdin_encoding = sys.stdin.encoding or 'ascii'
791 except AttributeError:
801 except AttributeError:
792 self.stdin_encoding = 'ascii'
802 self.stdin_encoding = 'ascii'
793
803
794
804
795 @observe('colors')
805 @observe('colors')
796 def init_syntax_highlighting(self, changes=None):
806 def init_syntax_highlighting(self, changes=None):
797 # Python source parser/formatter for syntax highlighting
807 # Python source parser/formatter for syntax highlighting
798 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
808 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
799 self.pycolorize = lambda src: pyformat(src,'str')
809 self.pycolorize = lambda src: pyformat(src,'str')
800
810
801 def refresh_style(self):
811 def refresh_style(self):
802 # No-op here, used in subclass
812 # No-op here, used in subclass
803 pass
813 pass
804
814
805 def init_pushd_popd_magic(self):
815 def init_pushd_popd_magic(self):
806 # for pushd/popd management
816 # for pushd/popd management
807 self.home_dir = get_home_dir()
817 self.home_dir = get_home_dir()
808
818
809 self.dir_stack = []
819 self.dir_stack = []
810
820
811 def init_logger(self):
821 def init_logger(self):
812 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
822 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
813 logmode='rotate')
823 logmode='rotate')
814
824
815 def init_logstart(self):
825 def init_logstart(self):
816 """Initialize logging in case it was requested at the command line.
826 """Initialize logging in case it was requested at the command line.
817 """
827 """
818 if self.logappend:
828 if self.logappend:
819 self.magic('logstart %s append' % self.logappend)
829 self.magic('logstart %s append' % self.logappend)
820 elif self.logfile:
830 elif self.logfile:
821 self.magic('logstart %s' % self.logfile)
831 self.magic('logstart %s' % self.logfile)
822 elif self.logstart:
832 elif self.logstart:
823 self.magic('logstart')
833 self.magic('logstart')
824
834
825 def init_deprecation_warnings(self):
835 def init_deprecation_warnings(self):
826 """
836 """
827 register default filter for deprecation warning.
837 register default filter for deprecation warning.
828
838
829 This will allow deprecation warning of function used interactively to show
839 This will allow deprecation warning of function used interactively to show
830 warning to users, and still hide deprecation warning from libraries import.
840 warning to users, and still hide deprecation warning from libraries import.
831 """
841 """
832 if sys.version_info < (3,7):
842 if sys.version_info < (3,7):
833 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
843 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
834
844
835
845
836 def init_builtins(self):
846 def init_builtins(self):
837 # A single, static flag that we set to True. Its presence indicates
847 # A single, static flag that we set to True. Its presence indicates
838 # that an IPython shell has been created, and we make no attempts at
848 # that an IPython shell has been created, and we make no attempts at
839 # removing on exit or representing the existence of more than one
849 # removing on exit or representing the existence of more than one
840 # IPython at a time.
850 # IPython at a time.
841 builtin_mod.__dict__['__IPYTHON__'] = True
851 builtin_mod.__dict__['__IPYTHON__'] = True
842 builtin_mod.__dict__['display'] = display
852 builtin_mod.__dict__['display'] = display
843
853
844 self.builtin_trap = BuiltinTrap(shell=self)
854 self.builtin_trap = BuiltinTrap(shell=self)
845
855
846 @observe('colors')
856 @observe('colors')
847 def init_inspector(self, changes=None):
857 def init_inspector(self, changes=None):
848 # Object inspector
858 # Object inspector
849 self.inspector = oinspect.Inspector(oinspect.InspectColors,
859 self.inspector = oinspect.Inspector(oinspect.InspectColors,
850 PyColorize.ANSICodeColors,
860 PyColorize.ANSICodeColors,
851 self.colors,
861 self.colors,
852 self.object_info_string_level)
862 self.object_info_string_level)
853
863
854 def init_io(self):
864 def init_io(self):
855 # This will just use sys.stdout and sys.stderr. If you want to
865 # This will just use sys.stdout and sys.stderr. If you want to
856 # override sys.stdout and sys.stderr themselves, you need to do that
866 # override sys.stdout and sys.stderr themselves, you need to do that
857 # *before* instantiating this class, because io holds onto
867 # *before* instantiating this class, because io holds onto
858 # references to the underlying streams.
868 # references to the underlying streams.
859 # io.std* are deprecated, but don't show our own deprecation warnings
869 # io.std* are deprecated, but don't show our own deprecation warnings
860 # during initialization of the deprecated API.
870 # during initialization of the deprecated API.
861 with warnings.catch_warnings():
871 with warnings.catch_warnings():
862 warnings.simplefilter('ignore', DeprecationWarning)
872 warnings.simplefilter('ignore', DeprecationWarning)
863 io.stdout = io.IOStream(sys.stdout)
873 io.stdout = io.IOStream(sys.stdout)
864 io.stderr = io.IOStream(sys.stderr)
874 io.stderr = io.IOStream(sys.stderr)
865
875
866 def init_prompts(self):
876 def init_prompts(self):
867 # Set system prompts, so that scripts can decide if they are running
877 # Set system prompts, so that scripts can decide if they are running
868 # interactively.
878 # interactively.
869 sys.ps1 = 'In : '
879 sys.ps1 = 'In : '
870 sys.ps2 = '...: '
880 sys.ps2 = '...: '
871 sys.ps3 = 'Out: '
881 sys.ps3 = 'Out: '
872
882
873 def init_display_formatter(self):
883 def init_display_formatter(self):
874 self.display_formatter = DisplayFormatter(parent=self)
884 self.display_formatter = DisplayFormatter(parent=self)
875 self.configurables.append(self.display_formatter)
885 self.configurables.append(self.display_formatter)
876
886
877 def init_display_pub(self):
887 def init_display_pub(self):
878 self.display_pub = self.display_pub_class(parent=self, shell=self)
888 self.display_pub = self.display_pub_class(parent=self, shell=self)
879 self.configurables.append(self.display_pub)
889 self.configurables.append(self.display_pub)
880
890
881 def init_data_pub(self):
891 def init_data_pub(self):
882 if not self.data_pub_class:
892 if not self.data_pub_class:
883 self.data_pub = None
893 self.data_pub = None
884 return
894 return
885 self.data_pub = self.data_pub_class(parent=self)
895 self.data_pub = self.data_pub_class(parent=self)
886 self.configurables.append(self.data_pub)
896 self.configurables.append(self.data_pub)
887
897
888 def init_displayhook(self):
898 def init_displayhook(self):
889 # Initialize displayhook, set in/out prompts and printing system
899 # Initialize displayhook, set in/out prompts and printing system
890 self.displayhook = self.displayhook_class(
900 self.displayhook = self.displayhook_class(
891 parent=self,
901 parent=self,
892 shell=self,
902 shell=self,
893 cache_size=self.cache_size,
903 cache_size=self.cache_size,
894 )
904 )
895 self.configurables.append(self.displayhook)
905 self.configurables.append(self.displayhook)
896 # This is a context manager that installs/revmoes the displayhook at
906 # This is a context manager that installs/revmoes the displayhook at
897 # the appropriate time.
907 # the appropriate time.
898 self.display_trap = DisplayTrap(hook=self.displayhook)
908 self.display_trap = DisplayTrap(hook=self.displayhook)
899
909
900 def init_virtualenv(self):
910 def init_virtualenv(self):
901 """Add the current virtualenv to sys.path so the user can import modules from it.
911 """Add the current virtualenv to sys.path so the user can import modules from it.
902 This isn't perfect: it doesn't use the Python interpreter with which the
912 This isn't perfect: it doesn't use the Python interpreter with which the
903 virtualenv was built, and it ignores the --no-site-packages option. A
913 virtualenv was built, and it ignores the --no-site-packages option. A
904 warning will appear suggesting the user installs IPython in the
914 warning will appear suggesting the user installs IPython in the
905 virtualenv, but for many cases, it probably works well enough.
915 virtualenv, but for many cases, it probably works well enough.
906 Adapted from code snippets online.
916 Adapted from code snippets online.
907 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
917 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
908 """
918 """
909 if 'VIRTUAL_ENV' not in os.environ:
919 if 'VIRTUAL_ENV' not in os.environ:
910 # Not in a virtualenv
920 # Not in a virtualenv
911 return
921 return
912 elif os.environ["VIRTUAL_ENV"] == "":
922 elif os.environ["VIRTUAL_ENV"] == "":
913 warn("Virtual env path set to '', please check if this is intended.")
923 warn("Virtual env path set to '', please check if this is intended.")
914 return
924 return
915
925
916 p = Path(sys.executable)
926 p = Path(sys.executable)
917 p_venv = Path(os.environ["VIRTUAL_ENV"])
927 p_venv = Path(os.environ["VIRTUAL_ENV"])
918
928
919 # fallback venv detection:
929 # fallback venv detection:
920 # stdlib venv may symlink sys.executable, so we can't use realpath.
930 # stdlib venv may symlink sys.executable, so we can't use realpath.
921 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
931 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
922 # So we just check every item in the symlink tree (generally <= 3)
932 # So we just check every item in the symlink tree (generally <= 3)
923 paths = [p]
933 paths = [p]
924 while p.is_symlink():
934 while p.is_symlink():
925 p = Path(os.readlink(p))
935 p = Path(os.readlink(p))
926 paths.append(p.resolve())
936 paths.append(p.resolve())
927
937
928 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
938 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
929 if p_venv.parts[1] == "cygdrive":
939 if p_venv.parts[1] == "cygdrive":
930 drive_name = p_venv.parts[2]
940 drive_name = p_venv.parts[2]
931 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
941 p_venv = (drive_name + ":/") / Path(*p_venv.parts[3:])
932
942
933 if any(p_venv == p.parents[1] for p in paths):
943 if any(p_venv == p.parents[1] for p in paths):
934 # Our exe is inside or has access to the virtualenv, don't need to do anything.
944 # Our exe is inside or has access to the virtualenv, don't need to do anything.
935 return
945 return
936
946
937 if sys.platform == "win32":
947 if sys.platform == "win32":
938 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
948 virtual_env = str(Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages"))
939 else:
949 else:
940 virtual_env_path = Path(
950 virtual_env_path = Path(
941 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
951 os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
942 )
952 )
943 p_ver = sys.version_info[:2]
953 p_ver = sys.version_info[:2]
944
954
945 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
955 # Predict version from py[thon]-x.x in the $VIRTUAL_ENV
946 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
956 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
947 if re_m:
957 if re_m:
948 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
958 predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
949 if predicted_path.exists():
959 if predicted_path.exists():
950 p_ver = re_m.groups()
960 p_ver = re_m.groups()
951
961
952 virtual_env = str(virtual_env_path).format(*p_ver)
962 virtual_env = str(virtual_env_path).format(*p_ver)
953
963
954 warn(
964 warn(
955 "Attempting to work in a virtualenv. If you encounter problems, "
965 "Attempting to work in a virtualenv. If you encounter problems, "
956 "please install IPython inside the virtualenv."
966 "please install IPython inside the virtualenv."
957 )
967 )
958 import site
968 import site
959 sys.path.insert(0, virtual_env)
969 sys.path.insert(0, virtual_env)
960 site.addsitedir(virtual_env)
970 site.addsitedir(virtual_env)
961
971
962 #-------------------------------------------------------------------------
972 #-------------------------------------------------------------------------
963 # Things related to injections into the sys module
973 # Things related to injections into the sys module
964 #-------------------------------------------------------------------------
974 #-------------------------------------------------------------------------
965
975
966 def save_sys_module_state(self):
976 def save_sys_module_state(self):
967 """Save the state of hooks in the sys module.
977 """Save the state of hooks in the sys module.
968
978
969 This has to be called after self.user_module is created.
979 This has to be called after self.user_module is created.
970 """
980 """
971 self._orig_sys_module_state = {'stdin': sys.stdin,
981 self._orig_sys_module_state = {'stdin': sys.stdin,
972 'stdout': sys.stdout,
982 'stdout': sys.stdout,
973 'stderr': sys.stderr,
983 'stderr': sys.stderr,
974 'excepthook': sys.excepthook}
984 'excepthook': sys.excepthook}
975 self._orig_sys_modules_main_name = self.user_module.__name__
985 self._orig_sys_modules_main_name = self.user_module.__name__
976 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
986 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
977
987
978 def restore_sys_module_state(self):
988 def restore_sys_module_state(self):
979 """Restore the state of the sys module."""
989 """Restore the state of the sys module."""
980 try:
990 try:
981 for k, v in self._orig_sys_module_state.items():
991 for k, v in self._orig_sys_module_state.items():
982 setattr(sys, k, v)
992 setattr(sys, k, v)
983 except AttributeError:
993 except AttributeError:
984 pass
994 pass
985 # Reset what what done in self.init_sys_modules
995 # Reset what what done in self.init_sys_modules
986 if self._orig_sys_modules_main_mod is not None:
996 if self._orig_sys_modules_main_mod is not None:
987 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
997 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
988
998
989 #-------------------------------------------------------------------------
999 #-------------------------------------------------------------------------
990 # Things related to the banner
1000 # Things related to the banner
991 #-------------------------------------------------------------------------
1001 #-------------------------------------------------------------------------
992
1002
993 @property
1003 @property
994 def banner(self):
1004 def banner(self):
995 banner = self.banner1
1005 banner = self.banner1
996 if self.profile and self.profile != 'default':
1006 if self.profile and self.profile != 'default':
997 banner += '\nIPython profile: %s\n' % self.profile
1007 banner += '\nIPython profile: %s\n' % self.profile
998 if self.banner2:
1008 if self.banner2:
999 banner += '\n' + self.banner2
1009 banner += '\n' + self.banner2
1000 return banner
1010 return banner
1001
1011
1002 def show_banner(self, banner=None):
1012 def show_banner(self, banner=None):
1003 if banner is None:
1013 if banner is None:
1004 banner = self.banner
1014 banner = self.banner
1005 sys.stdout.write(banner)
1015 sys.stdout.write(banner)
1006
1016
1007 #-------------------------------------------------------------------------
1017 #-------------------------------------------------------------------------
1008 # Things related to hooks
1018 # Things related to hooks
1009 #-------------------------------------------------------------------------
1019 #-------------------------------------------------------------------------
1010
1020
1011 def init_hooks(self):
1021 def init_hooks(self):
1012 # hooks holds pointers used for user-side customizations
1022 # hooks holds pointers used for user-side customizations
1013 self.hooks = Struct()
1023 self.hooks = Struct()
1014
1024
1015 self.strdispatchers = {}
1025 self.strdispatchers = {}
1016
1026
1017 # Set all default hooks, defined in the IPython.hooks module.
1027 # Set all default hooks, defined in the IPython.hooks module.
1018 hooks = IPython.core.hooks
1028 hooks = IPython.core.hooks
1019 for hook_name in hooks.__all__:
1029 for hook_name in hooks.__all__:
1020 # default hooks have priority 100, i.e. low; user hooks should have
1030 # default hooks have priority 100, i.e. low; user hooks should have
1021 # 0-100 priority
1031 # 0-100 priority
1022 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
1032 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
1023
1033
1024 if self.display_page:
1034 if self.display_page:
1025 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
1035 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
1026
1036
1027 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
1037 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
1028 _warn_deprecated=True):
1038 _warn_deprecated=True):
1029 """set_hook(name,hook) -> sets an internal IPython hook.
1039 """set_hook(name,hook) -> sets an internal IPython hook.
1030
1040
1031 IPython exposes some of its internal API as user-modifiable hooks. By
1041 IPython exposes some of its internal API as user-modifiable hooks. By
1032 adding your function to one of these hooks, you can modify IPython's
1042 adding your function to one of these hooks, you can modify IPython's
1033 behavior to call at runtime your own routines."""
1043 behavior to call at runtime your own routines."""
1034
1044
1035 # At some point in the future, this should validate the hook before it
1045 # At some point in the future, this should validate the hook before it
1036 # accepts it. Probably at least check that the hook takes the number
1046 # accepts it. Probably at least check that the hook takes the number
1037 # of args it's supposed to.
1047 # of args it's supposed to.
1038
1048
1039 f = types.MethodType(hook,self)
1049 f = types.MethodType(hook,self)
1040
1050
1041 # check if the hook is for strdispatcher first
1051 # check if the hook is for strdispatcher first
1042 if str_key is not None:
1052 if str_key is not None:
1043 sdp = self.strdispatchers.get(name, StrDispatch())
1053 sdp = self.strdispatchers.get(name, StrDispatch())
1044 sdp.add_s(str_key, f, priority )
1054 sdp.add_s(str_key, f, priority )
1045 self.strdispatchers[name] = sdp
1055 self.strdispatchers[name] = sdp
1046 return
1056 return
1047 if re_key is not None:
1057 if re_key is not None:
1048 sdp = self.strdispatchers.get(name, StrDispatch())
1058 sdp = self.strdispatchers.get(name, StrDispatch())
1049 sdp.add_re(re.compile(re_key), f, priority )
1059 sdp.add_re(re.compile(re_key), f, priority )
1050 self.strdispatchers[name] = sdp
1060 self.strdispatchers[name] = sdp
1051 return
1061 return
1052
1062
1053 dp = getattr(self.hooks, name, None)
1063 dp = getattr(self.hooks, name, None)
1054 if name not in IPython.core.hooks.__all__:
1064 if name not in IPython.core.hooks.__all__:
1055 print("Warning! Hook '%s' is not one of %s" % \
1065 print("Warning! Hook '%s' is not one of %s" % \
1056 (name, IPython.core.hooks.__all__ ))
1066 (name, IPython.core.hooks.__all__ ))
1057
1067
1058 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
1068 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
1059 alternative = IPython.core.hooks.deprecated[name]
1069 alternative = IPython.core.hooks.deprecated[name]
1060 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
1070 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
1061
1071
1062 if not dp:
1072 if not dp:
1063 dp = IPython.core.hooks.CommandChainDispatcher()
1073 dp = IPython.core.hooks.CommandChainDispatcher()
1064
1074
1065 try:
1075 try:
1066 dp.add(f,priority)
1076 dp.add(f,priority)
1067 except AttributeError:
1077 except AttributeError:
1068 # it was not commandchain, plain old func - replace
1078 # it was not commandchain, plain old func - replace
1069 dp = f
1079 dp = f
1070
1080
1071 setattr(self.hooks,name, dp)
1081 setattr(self.hooks,name, dp)
1072
1082
1073 #-------------------------------------------------------------------------
1083 #-------------------------------------------------------------------------
1074 # Things related to events
1084 # Things related to events
1075 #-------------------------------------------------------------------------
1085 #-------------------------------------------------------------------------
1076
1086
1077 def init_events(self):
1087 def init_events(self):
1078 self.events = EventManager(self, available_events)
1088 self.events = EventManager(self, available_events)
1079
1089
1080 self.events.register("pre_execute", self._clear_warning_registry)
1090 self.events.register("pre_execute", self._clear_warning_registry)
1081
1091
1082 def register_post_execute(self, func):
1092 def register_post_execute(self, func):
1083 """DEPRECATED: Use ip.events.register('post_run_cell', func)
1093 """DEPRECATED: Use ip.events.register('post_run_cell', func)
1084
1094
1085 Register a function for calling after code execution.
1095 Register a function for calling after code execution.
1086 """
1096 """
1087 warn("ip.register_post_execute is deprecated, use "
1097 warn("ip.register_post_execute is deprecated, use "
1088 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
1098 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
1089 self.events.register('post_run_cell', func)
1099 self.events.register('post_run_cell', func)
1090
1100
1091 def _clear_warning_registry(self):
1101 def _clear_warning_registry(self):
1092 # clear the warning registry, so that different code blocks with
1102 # clear the warning registry, so that different code blocks with
1093 # overlapping line number ranges don't cause spurious suppression of
1103 # overlapping line number ranges don't cause spurious suppression of
1094 # warnings (see gh-6611 for details)
1104 # warnings (see gh-6611 for details)
1095 if "__warningregistry__" in self.user_global_ns:
1105 if "__warningregistry__" in self.user_global_ns:
1096 del self.user_global_ns["__warningregistry__"]
1106 del self.user_global_ns["__warningregistry__"]
1097
1107
1098 #-------------------------------------------------------------------------
1108 #-------------------------------------------------------------------------
1099 # Things related to the "main" module
1109 # Things related to the "main" module
1100 #-------------------------------------------------------------------------
1110 #-------------------------------------------------------------------------
1101
1111
1102 def new_main_mod(self, filename, modname):
1112 def new_main_mod(self, filename, modname):
1103 """Return a new 'main' module object for user code execution.
1113 """Return a new 'main' module object for user code execution.
1104
1114
1105 ``filename`` should be the path of the script which will be run in the
1115 ``filename`` should be the path of the script which will be run in the
1106 module. Requests with the same filename will get the same module, with
1116 module. Requests with the same filename will get the same module, with
1107 its namespace cleared.
1117 its namespace cleared.
1108
1118
1109 ``modname`` should be the module name - normally either '__main__' or
1119 ``modname`` should be the module name - normally either '__main__' or
1110 the basename of the file without the extension.
1120 the basename of the file without the extension.
1111
1121
1112 When scripts are executed via %run, we must keep a reference to their
1122 When scripts are executed via %run, we must keep a reference to their
1113 __main__ module around so that Python doesn't
1123 __main__ module around so that Python doesn't
1114 clear it, rendering references to module globals useless.
1124 clear it, rendering references to module globals useless.
1115
1125
1116 This method keeps said reference in a private dict, keyed by the
1126 This method keeps said reference in a private dict, keyed by the
1117 absolute path of the script. This way, for multiple executions of the
1127 absolute path of the script. This way, for multiple executions of the
1118 same script we only keep one copy of the namespace (the last one),
1128 same script we only keep one copy of the namespace (the last one),
1119 thus preventing memory leaks from old references while allowing the
1129 thus preventing memory leaks from old references while allowing the
1120 objects from the last execution to be accessible.
1130 objects from the last execution to be accessible.
1121 """
1131 """
1122 filename = os.path.abspath(filename)
1132 filename = os.path.abspath(filename)
1123 try:
1133 try:
1124 main_mod = self._main_mod_cache[filename]
1134 main_mod = self._main_mod_cache[filename]
1125 except KeyError:
1135 except KeyError:
1126 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1136 main_mod = self._main_mod_cache[filename] = types.ModuleType(
1127 modname,
1137 modname,
1128 doc="Module created for script run in IPython")
1138 doc="Module created for script run in IPython")
1129 else:
1139 else:
1130 main_mod.__dict__.clear()
1140 main_mod.__dict__.clear()
1131 main_mod.__name__ = modname
1141 main_mod.__name__ = modname
1132
1142
1133 main_mod.__file__ = filename
1143 main_mod.__file__ = filename
1134 # It seems pydoc (and perhaps others) needs any module instance to
1144 # It seems pydoc (and perhaps others) needs any module instance to
1135 # implement a __nonzero__ method
1145 # implement a __nonzero__ method
1136 main_mod.__nonzero__ = lambda : True
1146 main_mod.__nonzero__ = lambda : True
1137
1147
1138 return main_mod
1148 return main_mod
1139
1149
1140 def clear_main_mod_cache(self):
1150 def clear_main_mod_cache(self):
1141 """Clear the cache of main modules.
1151 """Clear the cache of main modules.
1142
1152
1143 Mainly for use by utilities like %reset.
1153 Mainly for use by utilities like %reset.
1144
1154
1145 Examples
1155 Examples
1146 --------
1156 --------
1147
1157
1148 In [15]: import IPython
1158 In [15]: import IPython
1149
1159
1150 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1160 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
1151
1161
1152 In [17]: len(_ip._main_mod_cache) > 0
1162 In [17]: len(_ip._main_mod_cache) > 0
1153 Out[17]: True
1163 Out[17]: True
1154
1164
1155 In [18]: _ip.clear_main_mod_cache()
1165 In [18]: _ip.clear_main_mod_cache()
1156
1166
1157 In [19]: len(_ip._main_mod_cache) == 0
1167 In [19]: len(_ip._main_mod_cache) == 0
1158 Out[19]: True
1168 Out[19]: True
1159 """
1169 """
1160 self._main_mod_cache.clear()
1170 self._main_mod_cache.clear()
1161
1171
1162 #-------------------------------------------------------------------------
1172 #-------------------------------------------------------------------------
1163 # Things related to debugging
1173 # Things related to debugging
1164 #-------------------------------------------------------------------------
1174 #-------------------------------------------------------------------------
1165
1175
1166 def init_pdb(self):
1176 def init_pdb(self):
1167 # Set calling of pdb on exceptions
1177 # Set calling of pdb on exceptions
1168 # self.call_pdb is a property
1178 # self.call_pdb is a property
1169 self.call_pdb = self.pdb
1179 self.call_pdb = self.pdb
1170
1180
1171 def _get_call_pdb(self):
1181 def _get_call_pdb(self):
1172 return self._call_pdb
1182 return self._call_pdb
1173
1183
1174 def _set_call_pdb(self,val):
1184 def _set_call_pdb(self,val):
1175
1185
1176 if val not in (0,1,False,True):
1186 if val not in (0,1,False,True):
1177 raise ValueError('new call_pdb value must be boolean')
1187 raise ValueError('new call_pdb value must be boolean')
1178
1188
1179 # store value in instance
1189 # store value in instance
1180 self._call_pdb = val
1190 self._call_pdb = val
1181
1191
1182 # notify the actual exception handlers
1192 # notify the actual exception handlers
1183 self.InteractiveTB.call_pdb = val
1193 self.InteractiveTB.call_pdb = val
1184
1194
1185 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1195 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1186 'Control auto-activation of pdb at exceptions')
1196 'Control auto-activation of pdb at exceptions')
1187
1197
1188 def debugger(self,force=False):
1198 def debugger(self,force=False):
1189 """Call the pdb debugger.
1199 """Call the pdb debugger.
1190
1200
1191 Keywords:
1201 Keywords:
1192
1202
1193 - force(False): by default, this routine checks the instance call_pdb
1203 - force(False): by default, this routine checks the instance call_pdb
1194 flag and does not actually invoke the debugger if the flag is false.
1204 flag and does not actually invoke the debugger if the flag is false.
1195 The 'force' option forces the debugger to activate even if the flag
1205 The 'force' option forces the debugger to activate even if the flag
1196 is false.
1206 is false.
1197 """
1207 """
1198
1208
1199 if not (force or self.call_pdb):
1209 if not (force or self.call_pdb):
1200 return
1210 return
1201
1211
1202 if not hasattr(sys,'last_traceback'):
1212 if not hasattr(sys,'last_traceback'):
1203 error('No traceback has been produced, nothing to debug.')
1213 error('No traceback has been produced, nothing to debug.')
1204 return
1214 return
1205
1215
1206 self.InteractiveTB.debugger(force=True)
1216 self.InteractiveTB.debugger(force=True)
1207
1217
1208 #-------------------------------------------------------------------------
1218 #-------------------------------------------------------------------------
1209 # Things related to IPython's various namespaces
1219 # Things related to IPython's various namespaces
1210 #-------------------------------------------------------------------------
1220 #-------------------------------------------------------------------------
1211 default_user_namespaces = True
1221 default_user_namespaces = True
1212
1222
1213 def init_create_namespaces(self, user_module=None, user_ns=None):
1223 def init_create_namespaces(self, user_module=None, user_ns=None):
1214 # Create the namespace where the user will operate. user_ns is
1224 # Create the namespace where the user will operate. user_ns is
1215 # normally the only one used, and it is passed to the exec calls as
1225 # normally the only one used, and it is passed to the exec calls as
1216 # the locals argument. But we do carry a user_global_ns namespace
1226 # the locals argument. But we do carry a user_global_ns namespace
1217 # given as the exec 'globals' argument, This is useful in embedding
1227 # given as the exec 'globals' argument, This is useful in embedding
1218 # situations where the ipython shell opens in a context where the
1228 # situations where the ipython shell opens in a context where the
1219 # distinction between locals and globals is meaningful. For
1229 # distinction between locals and globals is meaningful. For
1220 # non-embedded contexts, it is just the same object as the user_ns dict.
1230 # non-embedded contexts, it is just the same object as the user_ns dict.
1221
1231
1222 # FIXME. For some strange reason, __builtins__ is showing up at user
1232 # FIXME. For some strange reason, __builtins__ is showing up at user
1223 # level as a dict instead of a module. This is a manual fix, but I
1233 # level as a dict instead of a module. This is a manual fix, but I
1224 # should really track down where the problem is coming from. Alex
1234 # should really track down where the problem is coming from. Alex
1225 # Schmolck reported this problem first.
1235 # Schmolck reported this problem first.
1226
1236
1227 # A useful post by Alex Martelli on this topic:
1237 # A useful post by Alex Martelli on this topic:
1228 # Re: inconsistent value from __builtins__
1238 # Re: inconsistent value from __builtins__
1229 # Von: Alex Martelli <aleaxit@yahoo.com>
1239 # Von: Alex Martelli <aleaxit@yahoo.com>
1230 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1240 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1231 # Gruppen: comp.lang.python
1241 # Gruppen: comp.lang.python
1232
1242
1233 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1243 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1234 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1244 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1235 # > <type 'dict'>
1245 # > <type 'dict'>
1236 # > >>> print type(__builtins__)
1246 # > >>> print type(__builtins__)
1237 # > <type 'module'>
1247 # > <type 'module'>
1238 # > Is this difference in return value intentional?
1248 # > Is this difference in return value intentional?
1239
1249
1240 # Well, it's documented that '__builtins__' can be either a dictionary
1250 # Well, it's documented that '__builtins__' can be either a dictionary
1241 # or a module, and it's been that way for a long time. Whether it's
1251 # or a module, and it's been that way for a long time. Whether it's
1242 # intentional (or sensible), I don't know. In any case, the idea is
1252 # intentional (or sensible), I don't know. In any case, the idea is
1243 # that if you need to access the built-in namespace directly, you
1253 # that if you need to access the built-in namespace directly, you
1244 # should start with "import __builtin__" (note, no 's') which will
1254 # should start with "import __builtin__" (note, no 's') which will
1245 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1255 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1246
1256
1247 # These routines return a properly built module and dict as needed by
1257 # These routines return a properly built module and dict as needed by
1248 # the rest of the code, and can also be used by extension writers to
1258 # the rest of the code, and can also be used by extension writers to
1249 # generate properly initialized namespaces.
1259 # generate properly initialized namespaces.
1250 if (user_ns is not None) or (user_module is not None):
1260 if (user_ns is not None) or (user_module is not None):
1251 self.default_user_namespaces = False
1261 self.default_user_namespaces = False
1252 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1262 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1253
1263
1254 # A record of hidden variables we have added to the user namespace, so
1264 # A record of hidden variables we have added to the user namespace, so
1255 # we can list later only variables defined in actual interactive use.
1265 # we can list later only variables defined in actual interactive use.
1256 self.user_ns_hidden = {}
1266 self.user_ns_hidden = {}
1257
1267
1258 # Now that FakeModule produces a real module, we've run into a nasty
1268 # Now that FakeModule produces a real module, we've run into a nasty
1259 # problem: after script execution (via %run), the module where the user
1269 # problem: after script execution (via %run), the module where the user
1260 # code ran is deleted. Now that this object is a true module (needed
1270 # code ran is deleted. Now that this object is a true module (needed
1261 # so doctest and other tools work correctly), the Python module
1271 # so doctest and other tools work correctly), the Python module
1262 # teardown mechanism runs over it, and sets to None every variable
1272 # teardown mechanism runs over it, and sets to None every variable
1263 # present in that module. Top-level references to objects from the
1273 # present in that module. Top-level references to objects from the
1264 # script survive, because the user_ns is updated with them. However,
1274 # script survive, because the user_ns is updated with them. However,
1265 # calling functions defined in the script that use other things from
1275 # calling functions defined in the script that use other things from
1266 # the script will fail, because the function's closure had references
1276 # the script will fail, because the function's closure had references
1267 # to the original objects, which are now all None. So we must protect
1277 # to the original objects, which are now all None. So we must protect
1268 # these modules from deletion by keeping a cache.
1278 # these modules from deletion by keeping a cache.
1269 #
1279 #
1270 # To avoid keeping stale modules around (we only need the one from the
1280 # To avoid keeping stale modules around (we only need the one from the
1271 # last run), we use a dict keyed with the full path to the script, so
1281 # last run), we use a dict keyed with the full path to the script, so
1272 # only the last version of the module is held in the cache. Note,
1282 # only the last version of the module is held in the cache. Note,
1273 # however, that we must cache the module *namespace contents* (their
1283 # however, that we must cache the module *namespace contents* (their
1274 # __dict__). Because if we try to cache the actual modules, old ones
1284 # __dict__). Because if we try to cache the actual modules, old ones
1275 # (uncached) could be destroyed while still holding references (such as
1285 # (uncached) could be destroyed while still holding references (such as
1276 # those held by GUI objects that tend to be long-lived)>
1286 # those held by GUI objects that tend to be long-lived)>
1277 #
1287 #
1278 # The %reset command will flush this cache. See the cache_main_mod()
1288 # The %reset command will flush this cache. See the cache_main_mod()
1279 # and clear_main_mod_cache() methods for details on use.
1289 # and clear_main_mod_cache() methods for details on use.
1280
1290
1281 # This is the cache used for 'main' namespaces
1291 # This is the cache used for 'main' namespaces
1282 self._main_mod_cache = {}
1292 self._main_mod_cache = {}
1283
1293
1284 # A table holding all the namespaces IPython deals with, so that
1294 # A table holding all the namespaces IPython deals with, so that
1285 # introspection facilities can search easily.
1295 # introspection facilities can search easily.
1286 self.ns_table = {'user_global':self.user_module.__dict__,
1296 self.ns_table = {'user_global':self.user_module.__dict__,
1287 'user_local':self.user_ns,
1297 'user_local':self.user_ns,
1288 'builtin':builtin_mod.__dict__
1298 'builtin':builtin_mod.__dict__
1289 }
1299 }
1290
1300
1291 @property
1301 @property
1292 def user_global_ns(self):
1302 def user_global_ns(self):
1293 return self.user_module.__dict__
1303 return self.user_module.__dict__
1294
1304
1295 def prepare_user_module(self, user_module=None, user_ns=None):
1305 def prepare_user_module(self, user_module=None, user_ns=None):
1296 """Prepare the module and namespace in which user code will be run.
1306 """Prepare the module and namespace in which user code will be run.
1297
1307
1298 When IPython is started normally, both parameters are None: a new module
1308 When IPython is started normally, both parameters are None: a new module
1299 is created automatically, and its __dict__ used as the namespace.
1309 is created automatically, and its __dict__ used as the namespace.
1300
1310
1301 If only user_module is provided, its __dict__ is used as the namespace.
1311 If only user_module is provided, its __dict__ is used as the namespace.
1302 If only user_ns is provided, a dummy module is created, and user_ns
1312 If only user_ns is provided, a dummy module is created, and user_ns
1303 becomes the global namespace. If both are provided (as they may be
1313 becomes the global namespace. If both are provided (as they may be
1304 when embedding), user_ns is the local namespace, and user_module
1314 when embedding), user_ns is the local namespace, and user_module
1305 provides the global namespace.
1315 provides the global namespace.
1306
1316
1307 Parameters
1317 Parameters
1308 ----------
1318 ----------
1309 user_module : module, optional
1319 user_module : module, optional
1310 The current user module in which IPython is being run. If None,
1320 The current user module in which IPython is being run. If None,
1311 a clean module will be created.
1321 a clean module will be created.
1312 user_ns : dict, optional
1322 user_ns : dict, optional
1313 A namespace in which to run interactive commands.
1323 A namespace in which to run interactive commands.
1314
1324
1315 Returns
1325 Returns
1316 -------
1326 -------
1317 A tuple of user_module and user_ns, each properly initialised.
1327 A tuple of user_module and user_ns, each properly initialised.
1318 """
1328 """
1319 if user_module is None and user_ns is not None:
1329 if user_module is None and user_ns is not None:
1320 user_ns.setdefault("__name__", "__main__")
1330 user_ns.setdefault("__name__", "__main__")
1321 user_module = DummyMod()
1331 user_module = DummyMod()
1322 user_module.__dict__ = user_ns
1332 user_module.__dict__ = user_ns
1323
1333
1324 if user_module is None:
1334 if user_module is None:
1325 user_module = types.ModuleType("__main__",
1335 user_module = types.ModuleType("__main__",
1326 doc="Automatically created module for IPython interactive environment")
1336 doc="Automatically created module for IPython interactive environment")
1327
1337
1328 # We must ensure that __builtin__ (without the final 's') is always
1338 # We must ensure that __builtin__ (without the final 's') is always
1329 # available and pointing to the __builtin__ *module*. For more details:
1339 # available and pointing to the __builtin__ *module*. For more details:
1330 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1340 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1331 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1341 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1332 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1342 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1333
1343
1334 if user_ns is None:
1344 if user_ns is None:
1335 user_ns = user_module.__dict__
1345 user_ns = user_module.__dict__
1336
1346
1337 return user_module, user_ns
1347 return user_module, user_ns
1338
1348
1339 def init_sys_modules(self):
1349 def init_sys_modules(self):
1340 # We need to insert into sys.modules something that looks like a
1350 # We need to insert into sys.modules something that looks like a
1341 # module but which accesses the IPython namespace, for shelve and
1351 # module but which accesses the IPython namespace, for shelve and
1342 # pickle to work interactively. Normally they rely on getting
1352 # pickle to work interactively. Normally they rely on getting
1343 # everything out of __main__, but for embedding purposes each IPython
1353 # everything out of __main__, but for embedding purposes each IPython
1344 # instance has its own private namespace, so we can't go shoving
1354 # instance has its own private namespace, so we can't go shoving
1345 # everything into __main__.
1355 # everything into __main__.
1346
1356
1347 # note, however, that we should only do this for non-embedded
1357 # note, however, that we should only do this for non-embedded
1348 # ipythons, which really mimic the __main__.__dict__ with their own
1358 # ipythons, which really mimic the __main__.__dict__ with their own
1349 # namespace. Embedded instances, on the other hand, should not do
1359 # namespace. Embedded instances, on the other hand, should not do
1350 # this because they need to manage the user local/global namespaces
1360 # this because they need to manage the user local/global namespaces
1351 # only, but they live within a 'normal' __main__ (meaning, they
1361 # only, but they live within a 'normal' __main__ (meaning, they
1352 # shouldn't overtake the execution environment of the script they're
1362 # shouldn't overtake the execution environment of the script they're
1353 # embedded in).
1363 # embedded in).
1354
1364
1355 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1365 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1356 main_name = self.user_module.__name__
1366 main_name = self.user_module.__name__
1357 sys.modules[main_name] = self.user_module
1367 sys.modules[main_name] = self.user_module
1358
1368
1359 def init_user_ns(self):
1369 def init_user_ns(self):
1360 """Initialize all user-visible namespaces to their minimum defaults.
1370 """Initialize all user-visible namespaces to their minimum defaults.
1361
1371
1362 Certain history lists are also initialized here, as they effectively
1372 Certain history lists are also initialized here, as they effectively
1363 act as user namespaces.
1373 act as user namespaces.
1364
1374
1365 Notes
1375 Notes
1366 -----
1376 -----
1367 All data structures here are only filled in, they are NOT reset by this
1377 All data structures here are only filled in, they are NOT reset by this
1368 method. If they were not empty before, data will simply be added to
1378 method. If they were not empty before, data will simply be added to
1369 them.
1379 them.
1370 """
1380 """
1371 # This function works in two parts: first we put a few things in
1381 # This function works in two parts: first we put a few things in
1372 # user_ns, and we sync that contents into user_ns_hidden so that these
1382 # user_ns, and we sync that contents into user_ns_hidden so that these
1373 # initial variables aren't shown by %who. After the sync, we add the
1383 # initial variables aren't shown by %who. After the sync, we add the
1374 # rest of what we *do* want the user to see with %who even on a new
1384 # rest of what we *do* want the user to see with %who even on a new
1375 # session (probably nothing, so they really only see their own stuff)
1385 # session (probably nothing, so they really only see their own stuff)
1376
1386
1377 # The user dict must *always* have a __builtin__ reference to the
1387 # The user dict must *always* have a __builtin__ reference to the
1378 # Python standard __builtin__ namespace, which must be imported.
1388 # Python standard __builtin__ namespace, which must be imported.
1379 # This is so that certain operations in prompt evaluation can be
1389 # This is so that certain operations in prompt evaluation can be
1380 # reliably executed with builtins. Note that we can NOT use
1390 # reliably executed with builtins. Note that we can NOT use
1381 # __builtins__ (note the 's'), because that can either be a dict or a
1391 # __builtins__ (note the 's'), because that can either be a dict or a
1382 # module, and can even mutate at runtime, depending on the context
1392 # module, and can even mutate at runtime, depending on the context
1383 # (Python makes no guarantees on it). In contrast, __builtin__ is
1393 # (Python makes no guarantees on it). In contrast, __builtin__ is
1384 # always a module object, though it must be explicitly imported.
1394 # always a module object, though it must be explicitly imported.
1385
1395
1386 # For more details:
1396 # For more details:
1387 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1397 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1388 ns = {}
1398 ns = {}
1389
1399
1390 # make global variables for user access to the histories
1400 # make global variables for user access to the histories
1391 ns['_ih'] = self.history_manager.input_hist_parsed
1401 ns['_ih'] = self.history_manager.input_hist_parsed
1392 ns['_oh'] = self.history_manager.output_hist
1402 ns['_oh'] = self.history_manager.output_hist
1393 ns['_dh'] = self.history_manager.dir_hist
1403 ns['_dh'] = self.history_manager.dir_hist
1394
1404
1395 # user aliases to input and output histories. These shouldn't show up
1405 # user aliases to input and output histories. These shouldn't show up
1396 # in %who, as they can have very large reprs.
1406 # in %who, as they can have very large reprs.
1397 ns['In'] = self.history_manager.input_hist_parsed
1407 ns['In'] = self.history_manager.input_hist_parsed
1398 ns['Out'] = self.history_manager.output_hist
1408 ns['Out'] = self.history_manager.output_hist
1399
1409
1400 # Store myself as the public api!!!
1410 # Store myself as the public api!!!
1401 ns['get_ipython'] = self.get_ipython
1411 ns['get_ipython'] = self.get_ipython
1402
1412
1403 ns['exit'] = self.exiter
1413 ns['exit'] = self.exiter
1404 ns['quit'] = self.exiter
1414 ns['quit'] = self.exiter
1405
1415
1406 # Sync what we've added so far to user_ns_hidden so these aren't seen
1416 # Sync what we've added so far to user_ns_hidden so these aren't seen
1407 # by %who
1417 # by %who
1408 self.user_ns_hidden.update(ns)
1418 self.user_ns_hidden.update(ns)
1409
1419
1410 # Anything put into ns now would show up in %who. Think twice before
1420 # Anything put into ns now would show up in %who. Think twice before
1411 # putting anything here, as we really want %who to show the user their
1421 # putting anything here, as we really want %who to show the user their
1412 # stuff, not our variables.
1422 # stuff, not our variables.
1413
1423
1414 # Finally, update the real user's namespace
1424 # Finally, update the real user's namespace
1415 self.user_ns.update(ns)
1425 self.user_ns.update(ns)
1416
1426
1417 @property
1427 @property
1418 def all_ns_refs(self):
1428 def all_ns_refs(self):
1419 """Get a list of references to all the namespace dictionaries in which
1429 """Get a list of references to all the namespace dictionaries in which
1420 IPython might store a user-created object.
1430 IPython might store a user-created object.
1421
1431
1422 Note that this does not include the displayhook, which also caches
1432 Note that this does not include the displayhook, which also caches
1423 objects from the output."""
1433 objects from the output."""
1424 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1434 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1425 [m.__dict__ for m in self._main_mod_cache.values()]
1435 [m.__dict__ for m in self._main_mod_cache.values()]
1426
1436
1427 def reset(self, new_session=True, aggressive=False):
1437 def reset(self, new_session=True, aggressive=False):
1428 """Clear all internal namespaces, and attempt to release references to
1438 """Clear all internal namespaces, and attempt to release references to
1429 user objects.
1439 user objects.
1430
1440
1431 If new_session is True, a new history session will be opened.
1441 If new_session is True, a new history session will be opened.
1432 """
1442 """
1433 # Clear histories
1443 # Clear histories
1434 self.history_manager.reset(new_session)
1444 self.history_manager.reset(new_session)
1435 # Reset counter used to index all histories
1445 # Reset counter used to index all histories
1436 if new_session:
1446 if new_session:
1437 self.execution_count = 1
1447 self.execution_count = 1
1438
1448
1439 # Reset last execution result
1449 # Reset last execution result
1440 self.last_execution_succeeded = True
1450 self.last_execution_succeeded = True
1441 self.last_execution_result = None
1451 self.last_execution_result = None
1442
1452
1443 # Flush cached output items
1453 # Flush cached output items
1444 if self.displayhook.do_full_cache:
1454 if self.displayhook.do_full_cache:
1445 self.displayhook.flush()
1455 self.displayhook.flush()
1446
1456
1447 # The main execution namespaces must be cleared very carefully,
1457 # The main execution namespaces must be cleared very carefully,
1448 # skipping the deletion of the builtin-related keys, because doing so
1458 # skipping the deletion of the builtin-related keys, because doing so
1449 # would cause errors in many object's __del__ methods.
1459 # would cause errors in many object's __del__ methods.
1450 if self.user_ns is not self.user_global_ns:
1460 if self.user_ns is not self.user_global_ns:
1451 self.user_ns.clear()
1461 self.user_ns.clear()
1452 ns = self.user_global_ns
1462 ns = self.user_global_ns
1453 drop_keys = set(ns.keys())
1463 drop_keys = set(ns.keys())
1454 drop_keys.discard('__builtin__')
1464 drop_keys.discard('__builtin__')
1455 drop_keys.discard('__builtins__')
1465 drop_keys.discard('__builtins__')
1456 drop_keys.discard('__name__')
1466 drop_keys.discard('__name__')
1457 for k in drop_keys:
1467 for k in drop_keys:
1458 del ns[k]
1468 del ns[k]
1459
1469
1460 self.user_ns_hidden.clear()
1470 self.user_ns_hidden.clear()
1461
1471
1462 # Restore the user namespaces to minimal usability
1472 # Restore the user namespaces to minimal usability
1463 self.init_user_ns()
1473 self.init_user_ns()
1464 if aggressive and not hasattr(self, "_sys_modules_keys"):
1474 if aggressive and not hasattr(self, "_sys_modules_keys"):
1465 print("Cannot restore sys.module, no snapshot")
1475 print("Cannot restore sys.module, no snapshot")
1466 elif aggressive:
1476 elif aggressive:
1467 print("culling sys module...")
1477 print("culling sys module...")
1468 current_keys = set(sys.modules.keys())
1478 current_keys = set(sys.modules.keys())
1469 for k in current_keys - self._sys_modules_keys:
1479 for k in current_keys - self._sys_modules_keys:
1470 if k.startswith("multiprocessing"):
1480 if k.startswith("multiprocessing"):
1471 continue
1481 continue
1472 del sys.modules[k]
1482 del sys.modules[k]
1473
1483
1474 # Restore the default and user aliases
1484 # Restore the default and user aliases
1475 self.alias_manager.clear_aliases()
1485 self.alias_manager.clear_aliases()
1476 self.alias_manager.init_aliases()
1486 self.alias_manager.init_aliases()
1477
1487
1478 # Now define aliases that only make sense on the terminal, because they
1488 # Now define aliases that only make sense on the terminal, because they
1479 # need direct access to the console in a way that we can't emulate in
1489 # need direct access to the console in a way that we can't emulate in
1480 # GUI or web frontend
1490 # GUI or web frontend
1481 if os.name == 'posix':
1491 if os.name == 'posix':
1482 for cmd in ('clear', 'more', 'less', 'man'):
1492 for cmd in ('clear', 'more', 'less', 'man'):
1483 if cmd not in self.magics_manager.magics['line']:
1493 if cmd not in self.magics_manager.magics['line']:
1484 self.alias_manager.soft_define_alias(cmd, cmd)
1494 self.alias_manager.soft_define_alias(cmd, cmd)
1485
1495
1486 # Flush the private list of module references kept for script
1496 # Flush the private list of module references kept for script
1487 # execution protection
1497 # execution protection
1488 self.clear_main_mod_cache()
1498 self.clear_main_mod_cache()
1489
1499
1490 def del_var(self, varname, by_name=False):
1500 def del_var(self, varname, by_name=False):
1491 """Delete a variable from the various namespaces, so that, as
1501 """Delete a variable from the various namespaces, so that, as
1492 far as possible, we're not keeping any hidden references to it.
1502 far as possible, we're not keeping any hidden references to it.
1493
1503
1494 Parameters
1504 Parameters
1495 ----------
1505 ----------
1496 varname : str
1506 varname : str
1497 The name of the variable to delete.
1507 The name of the variable to delete.
1498 by_name : bool
1508 by_name : bool
1499 If True, delete variables with the given name in each
1509 If True, delete variables with the given name in each
1500 namespace. If False (default), find the variable in the user
1510 namespace. If False (default), find the variable in the user
1501 namespace, and delete references to it.
1511 namespace, and delete references to it.
1502 """
1512 """
1503 if varname in ('__builtin__', '__builtins__'):
1513 if varname in ('__builtin__', '__builtins__'):
1504 raise ValueError("Refusing to delete %s" % varname)
1514 raise ValueError("Refusing to delete %s" % varname)
1505
1515
1506 ns_refs = self.all_ns_refs
1516 ns_refs = self.all_ns_refs
1507
1517
1508 if by_name: # Delete by name
1518 if by_name: # Delete by name
1509 for ns in ns_refs:
1519 for ns in ns_refs:
1510 try:
1520 try:
1511 del ns[varname]
1521 del ns[varname]
1512 except KeyError:
1522 except KeyError:
1513 pass
1523 pass
1514 else: # Delete by object
1524 else: # Delete by object
1515 try:
1525 try:
1516 obj = self.user_ns[varname]
1526 obj = self.user_ns[varname]
1517 except KeyError:
1527 except KeyError:
1518 raise NameError("name '%s' is not defined" % varname)
1528 raise NameError("name '%s' is not defined" % varname)
1519 # Also check in output history
1529 # Also check in output history
1520 ns_refs.append(self.history_manager.output_hist)
1530 ns_refs.append(self.history_manager.output_hist)
1521 for ns in ns_refs:
1531 for ns in ns_refs:
1522 to_delete = [n for n, o in ns.items() if o is obj]
1532 to_delete = [n for n, o in ns.items() if o is obj]
1523 for name in to_delete:
1533 for name in to_delete:
1524 del ns[name]
1534 del ns[name]
1525
1535
1526 # Ensure it is removed from the last execution result
1536 # Ensure it is removed from the last execution result
1527 if self.last_execution_result.result is obj:
1537 if self.last_execution_result.result is obj:
1528 self.last_execution_result = None
1538 self.last_execution_result = None
1529
1539
1530 # displayhook keeps extra references, but not in a dictionary
1540 # displayhook keeps extra references, but not in a dictionary
1531 for name in ('_', '__', '___'):
1541 for name in ('_', '__', '___'):
1532 if getattr(self.displayhook, name) is obj:
1542 if getattr(self.displayhook, name) is obj:
1533 setattr(self.displayhook, name, None)
1543 setattr(self.displayhook, name, None)
1534
1544
1535 def reset_selective(self, regex=None):
1545 def reset_selective(self, regex=None):
1536 """Clear selective variables from internal namespaces based on a
1546 """Clear selective variables from internal namespaces based on a
1537 specified regular expression.
1547 specified regular expression.
1538
1548
1539 Parameters
1549 Parameters
1540 ----------
1550 ----------
1541 regex : string or compiled pattern, optional
1551 regex : string or compiled pattern, optional
1542 A regular expression pattern that will be used in searching
1552 A regular expression pattern that will be used in searching
1543 variable names in the users namespaces.
1553 variable names in the users namespaces.
1544 """
1554 """
1545 if regex is not None:
1555 if regex is not None:
1546 try:
1556 try:
1547 m = re.compile(regex)
1557 m = re.compile(regex)
1548 except TypeError:
1558 except TypeError:
1549 raise TypeError('regex must be a string or compiled pattern')
1559 raise TypeError('regex must be a string or compiled pattern')
1550 # Search for keys in each namespace that match the given regex
1560 # Search for keys in each namespace that match the given regex
1551 # If a match is found, delete the key/value pair.
1561 # If a match is found, delete the key/value pair.
1552 for ns in self.all_ns_refs:
1562 for ns in self.all_ns_refs:
1553 for var in ns:
1563 for var in ns:
1554 if m.search(var):
1564 if m.search(var):
1555 del ns[var]
1565 del ns[var]
1556
1566
1557 def push(self, variables, interactive=True):
1567 def push(self, variables, interactive=True):
1558 """Inject a group of variables into the IPython user namespace.
1568 """Inject a group of variables into the IPython user namespace.
1559
1569
1560 Parameters
1570 Parameters
1561 ----------
1571 ----------
1562 variables : dict, str or list/tuple of str
1572 variables : dict, str or list/tuple of str
1563 The variables to inject into the user's namespace. If a dict, a
1573 The variables to inject into the user's namespace. If a dict, a
1564 simple update is done. If a str, the string is assumed to have
1574 simple update is done. If a str, the string is assumed to have
1565 variable names separated by spaces. A list/tuple of str can also
1575 variable names separated by spaces. A list/tuple of str can also
1566 be used to give the variable names. If just the variable names are
1576 be used to give the variable names. If just the variable names are
1567 give (list/tuple/str) then the variable values looked up in the
1577 give (list/tuple/str) then the variable values looked up in the
1568 callers frame.
1578 callers frame.
1569 interactive : bool
1579 interactive : bool
1570 If True (default), the variables will be listed with the ``who``
1580 If True (default), the variables will be listed with the ``who``
1571 magic.
1581 magic.
1572 """
1582 """
1573 vdict = None
1583 vdict = None
1574
1584
1575 # We need a dict of name/value pairs to do namespace updates.
1585 # We need a dict of name/value pairs to do namespace updates.
1576 if isinstance(variables, dict):
1586 if isinstance(variables, dict):
1577 vdict = variables
1587 vdict = variables
1578 elif isinstance(variables, (str, list, tuple)):
1588 elif isinstance(variables, (str, list, tuple)):
1579 if isinstance(variables, str):
1589 if isinstance(variables, str):
1580 vlist = variables.split()
1590 vlist = variables.split()
1581 else:
1591 else:
1582 vlist = variables
1592 vlist = variables
1583 vdict = {}
1593 vdict = {}
1584 cf = sys._getframe(1)
1594 cf = sys._getframe(1)
1585 for name in vlist:
1595 for name in vlist:
1586 try:
1596 try:
1587 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1597 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1588 except:
1598 except:
1589 print('Could not get variable %s from %s' %
1599 print('Could not get variable %s from %s' %
1590 (name,cf.f_code.co_name))
1600 (name,cf.f_code.co_name))
1591 else:
1601 else:
1592 raise ValueError('variables must be a dict/str/list/tuple')
1602 raise ValueError('variables must be a dict/str/list/tuple')
1593
1603
1594 # Propagate variables to user namespace
1604 # Propagate variables to user namespace
1595 self.user_ns.update(vdict)
1605 self.user_ns.update(vdict)
1596
1606
1597 # And configure interactive visibility
1607 # And configure interactive visibility
1598 user_ns_hidden = self.user_ns_hidden
1608 user_ns_hidden = self.user_ns_hidden
1599 if interactive:
1609 if interactive:
1600 for name in vdict:
1610 for name in vdict:
1601 user_ns_hidden.pop(name, None)
1611 user_ns_hidden.pop(name, None)
1602 else:
1612 else:
1603 user_ns_hidden.update(vdict)
1613 user_ns_hidden.update(vdict)
1604
1614
1605 def drop_by_id(self, variables):
1615 def drop_by_id(self, variables):
1606 """Remove a dict of variables from the user namespace, if they are the
1616 """Remove a dict of variables from the user namespace, if they are the
1607 same as the values in the dictionary.
1617 same as the values in the dictionary.
1608
1618
1609 This is intended for use by extensions: variables that they've added can
1619 This is intended for use by extensions: variables that they've added can
1610 be taken back out if they are unloaded, without removing any that the
1620 be taken back out if they are unloaded, without removing any that the
1611 user has overwritten.
1621 user has overwritten.
1612
1622
1613 Parameters
1623 Parameters
1614 ----------
1624 ----------
1615 variables : dict
1625 variables : dict
1616 A dictionary mapping object names (as strings) to the objects.
1626 A dictionary mapping object names (as strings) to the objects.
1617 """
1627 """
1618 for name, obj in variables.items():
1628 for name, obj in variables.items():
1619 if name in self.user_ns and self.user_ns[name] is obj:
1629 if name in self.user_ns and self.user_ns[name] is obj:
1620 del self.user_ns[name]
1630 del self.user_ns[name]
1621 self.user_ns_hidden.pop(name, None)
1631 self.user_ns_hidden.pop(name, None)
1622
1632
1623 #-------------------------------------------------------------------------
1633 #-------------------------------------------------------------------------
1624 # Things related to object introspection
1634 # Things related to object introspection
1625 #-------------------------------------------------------------------------
1635 #-------------------------------------------------------------------------
1626
1636
1627 def _ofind(self, oname, namespaces=None):
1637 def _ofind(self, oname, namespaces=None):
1628 """Find an object in the available namespaces.
1638 """Find an object in the available namespaces.
1629
1639
1630 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1640 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1631
1641
1632 Has special code to detect magic functions.
1642 Has special code to detect magic functions.
1633 """
1643 """
1634 oname = oname.strip()
1644 oname = oname.strip()
1635 if not oname.startswith(ESC_MAGIC) and \
1645 if not oname.startswith(ESC_MAGIC) and \
1636 not oname.startswith(ESC_MAGIC2) and \
1646 not oname.startswith(ESC_MAGIC2) and \
1637 not all(a.isidentifier() for a in oname.split(".")):
1647 not all(a.isidentifier() for a in oname.split(".")):
1638 return {'found': False}
1648 return {'found': False}
1639
1649
1640 if namespaces is None:
1650 if namespaces is None:
1641 # Namespaces to search in:
1651 # Namespaces to search in:
1642 # Put them in a list. The order is important so that we
1652 # Put them in a list. The order is important so that we
1643 # find things in the same order that Python finds them.
1653 # find things in the same order that Python finds them.
1644 namespaces = [ ('Interactive', self.user_ns),
1654 namespaces = [ ('Interactive', self.user_ns),
1645 ('Interactive (global)', self.user_global_ns),
1655 ('Interactive (global)', self.user_global_ns),
1646 ('Python builtin', builtin_mod.__dict__),
1656 ('Python builtin', builtin_mod.__dict__),
1647 ]
1657 ]
1648
1658
1649 ismagic = False
1659 ismagic = False
1650 isalias = False
1660 isalias = False
1651 found = False
1661 found = False
1652 ospace = None
1662 ospace = None
1653 parent = None
1663 parent = None
1654 obj = None
1664 obj = None
1655
1665
1656
1666
1657 # Look for the given name by splitting it in parts. If the head is
1667 # Look for the given name by splitting it in parts. If the head is
1658 # found, then we look for all the remaining parts as members, and only
1668 # found, then we look for all the remaining parts as members, and only
1659 # declare success if we can find them all.
1669 # declare success if we can find them all.
1660 oname_parts = oname.split('.')
1670 oname_parts = oname.split('.')
1661 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1671 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1662 for nsname,ns in namespaces:
1672 for nsname,ns in namespaces:
1663 try:
1673 try:
1664 obj = ns[oname_head]
1674 obj = ns[oname_head]
1665 except KeyError:
1675 except KeyError:
1666 continue
1676 continue
1667 else:
1677 else:
1668 for idx, part in enumerate(oname_rest):
1678 for idx, part in enumerate(oname_rest):
1669 try:
1679 try:
1670 parent = obj
1680 parent = obj
1671 # The last part is looked up in a special way to avoid
1681 # The last part is looked up in a special way to avoid
1672 # descriptor invocation as it may raise or have side
1682 # descriptor invocation as it may raise or have side
1673 # effects.
1683 # effects.
1674 if idx == len(oname_rest) - 1:
1684 if idx == len(oname_rest) - 1:
1675 obj = self._getattr_property(obj, part)
1685 obj = self._getattr_property(obj, part)
1676 else:
1686 else:
1677 obj = getattr(obj, part)
1687 obj = getattr(obj, part)
1678 except:
1688 except:
1679 # Blanket except b/c some badly implemented objects
1689 # Blanket except b/c some badly implemented objects
1680 # allow __getattr__ to raise exceptions other than
1690 # allow __getattr__ to raise exceptions other than
1681 # AttributeError, which then crashes IPython.
1691 # AttributeError, which then crashes IPython.
1682 break
1692 break
1683 else:
1693 else:
1684 # If we finish the for loop (no break), we got all members
1694 # If we finish the for loop (no break), we got all members
1685 found = True
1695 found = True
1686 ospace = nsname
1696 ospace = nsname
1687 break # namespace loop
1697 break # namespace loop
1688
1698
1689 # Try to see if it's magic
1699 # Try to see if it's magic
1690 if not found:
1700 if not found:
1691 obj = None
1701 obj = None
1692 if oname.startswith(ESC_MAGIC2):
1702 if oname.startswith(ESC_MAGIC2):
1693 oname = oname.lstrip(ESC_MAGIC2)
1703 oname = oname.lstrip(ESC_MAGIC2)
1694 obj = self.find_cell_magic(oname)
1704 obj = self.find_cell_magic(oname)
1695 elif oname.startswith(ESC_MAGIC):
1705 elif oname.startswith(ESC_MAGIC):
1696 oname = oname.lstrip(ESC_MAGIC)
1706 oname = oname.lstrip(ESC_MAGIC)
1697 obj = self.find_line_magic(oname)
1707 obj = self.find_line_magic(oname)
1698 else:
1708 else:
1699 # search without prefix, so run? will find %run?
1709 # search without prefix, so run? will find %run?
1700 obj = self.find_line_magic(oname)
1710 obj = self.find_line_magic(oname)
1701 if obj is None:
1711 if obj is None:
1702 obj = self.find_cell_magic(oname)
1712 obj = self.find_cell_magic(oname)
1703 if obj is not None:
1713 if obj is not None:
1704 found = True
1714 found = True
1705 ospace = 'IPython internal'
1715 ospace = 'IPython internal'
1706 ismagic = True
1716 ismagic = True
1707 isalias = isinstance(obj, Alias)
1717 isalias = isinstance(obj, Alias)
1708
1718
1709 # Last try: special-case some literals like '', [], {}, etc:
1719 # Last try: special-case some literals like '', [], {}, etc:
1710 if not found and oname_head in ["''",'""','[]','{}','()']:
1720 if not found and oname_head in ["''",'""','[]','{}','()']:
1711 obj = eval(oname_head)
1721 obj = eval(oname_head)
1712 found = True
1722 found = True
1713 ospace = 'Interactive'
1723 ospace = 'Interactive'
1714
1724
1715 return {
1725 return {
1716 'obj':obj,
1726 'obj':obj,
1717 'found':found,
1727 'found':found,
1718 'parent':parent,
1728 'parent':parent,
1719 'ismagic':ismagic,
1729 'ismagic':ismagic,
1720 'isalias':isalias,
1730 'isalias':isalias,
1721 'namespace':ospace
1731 'namespace':ospace
1722 }
1732 }
1723
1733
1724 @staticmethod
1734 @staticmethod
1725 def _getattr_property(obj, attrname):
1735 def _getattr_property(obj, attrname):
1726 """Property-aware getattr to use in object finding.
1736 """Property-aware getattr to use in object finding.
1727
1737
1728 If attrname represents a property, return it unevaluated (in case it has
1738 If attrname represents a property, return it unevaluated (in case it has
1729 side effects or raises an error.
1739 side effects or raises an error.
1730
1740
1731 """
1741 """
1732 if not isinstance(obj, type):
1742 if not isinstance(obj, type):
1733 try:
1743 try:
1734 # `getattr(type(obj), attrname)` is not guaranteed to return
1744 # `getattr(type(obj), attrname)` is not guaranteed to return
1735 # `obj`, but does so for property:
1745 # `obj`, but does so for property:
1736 #
1746 #
1737 # property.__get__(self, None, cls) -> self
1747 # property.__get__(self, None, cls) -> self
1738 #
1748 #
1739 # The universal alternative is to traverse the mro manually
1749 # The universal alternative is to traverse the mro manually
1740 # searching for attrname in class dicts.
1750 # searching for attrname in class dicts.
1741 attr = getattr(type(obj), attrname)
1751 attr = getattr(type(obj), attrname)
1742 except AttributeError:
1752 except AttributeError:
1743 pass
1753 pass
1744 else:
1754 else:
1745 # This relies on the fact that data descriptors (with both
1755 # This relies on the fact that data descriptors (with both
1746 # __get__ & __set__ magic methods) take precedence over
1756 # __get__ & __set__ magic methods) take precedence over
1747 # instance-level attributes:
1757 # instance-level attributes:
1748 #
1758 #
1749 # class A(object):
1759 # class A(object):
1750 # @property
1760 # @property
1751 # def foobar(self): return 123
1761 # def foobar(self): return 123
1752 # a = A()
1762 # a = A()
1753 # a.__dict__['foobar'] = 345
1763 # a.__dict__['foobar'] = 345
1754 # a.foobar # == 123
1764 # a.foobar # == 123
1755 #
1765 #
1756 # So, a property may be returned right away.
1766 # So, a property may be returned right away.
1757 if isinstance(attr, property):
1767 if isinstance(attr, property):
1758 return attr
1768 return attr
1759
1769
1760 # Nothing helped, fall back.
1770 # Nothing helped, fall back.
1761 return getattr(obj, attrname)
1771 return getattr(obj, attrname)
1762
1772
1763 def _object_find(self, oname, namespaces=None):
1773 def _object_find(self, oname, namespaces=None):
1764 """Find an object and return a struct with info about it."""
1774 """Find an object and return a struct with info about it."""
1765 return Struct(self._ofind(oname, namespaces))
1775 return Struct(self._ofind(oname, namespaces))
1766
1776
1767 def _inspect(self, meth, oname, namespaces=None, **kw):
1777 def _inspect(self, meth, oname, namespaces=None, **kw):
1768 """Generic interface to the inspector system.
1778 """Generic interface to the inspector system.
1769
1779
1770 This function is meant to be called by pdef, pdoc & friends.
1780 This function is meant to be called by pdef, pdoc & friends.
1771 """
1781 """
1772 info = self._object_find(oname, namespaces)
1782 info = self._object_find(oname, namespaces)
1773 docformat = (
1783 docformat = (
1774 sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None
1784 sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None
1775 )
1785 )
1776 if info.found:
1786 if info.found:
1777 pmethod = getattr(self.inspector, meth)
1787 pmethod = getattr(self.inspector, meth)
1778 # TODO: only apply format_screen to the plain/text repr of the mime
1788 # TODO: only apply format_screen to the plain/text repr of the mime
1779 # bundle.
1789 # bundle.
1780 formatter = format_screen if info.ismagic else docformat
1790 formatter = format_screen if info.ismagic else docformat
1781 if meth == 'pdoc':
1791 if meth == 'pdoc':
1782 pmethod(info.obj, oname, formatter)
1792 pmethod(info.obj, oname, formatter)
1783 elif meth == 'pinfo':
1793 elif meth == 'pinfo':
1784 pmethod(
1794 pmethod(
1785 info.obj,
1795 info.obj,
1786 oname,
1796 oname,
1787 formatter,
1797 formatter,
1788 info,
1798 info,
1789 enable_html_pager=self.enable_html_pager,
1799 enable_html_pager=self.enable_html_pager,
1790 **kw,
1800 **kw,
1791 )
1801 )
1792 else:
1802 else:
1793 pmethod(info.obj, oname)
1803 pmethod(info.obj, oname)
1794 else:
1804 else:
1795 print('Object `%s` not found.' % oname)
1805 print('Object `%s` not found.' % oname)
1796 return 'not found' # so callers can take other action
1806 return 'not found' # so callers can take other action
1797
1807
1798 def object_inspect(self, oname, detail_level=0):
1808 def object_inspect(self, oname, detail_level=0):
1799 """Get object info about oname"""
1809 """Get object info about oname"""
1800 with self.builtin_trap:
1810 with self.builtin_trap:
1801 info = self._object_find(oname)
1811 info = self._object_find(oname)
1802 if info.found:
1812 if info.found:
1803 return self.inspector.info(info.obj, oname, info=info,
1813 return self.inspector.info(info.obj, oname, info=info,
1804 detail_level=detail_level
1814 detail_level=detail_level
1805 )
1815 )
1806 else:
1816 else:
1807 return oinspect.object_info(name=oname, found=False)
1817 return oinspect.object_info(name=oname, found=False)
1808
1818
1809 def object_inspect_text(self, oname, detail_level=0):
1819 def object_inspect_text(self, oname, detail_level=0):
1810 """Get object info as formatted text"""
1820 """Get object info as formatted text"""
1811 return self.object_inspect_mime(oname, detail_level)['text/plain']
1821 return self.object_inspect_mime(oname, detail_level)['text/plain']
1812
1822
1813 def object_inspect_mime(self, oname, detail_level=0):
1823 def object_inspect_mime(self, oname, detail_level=0):
1814 """Get object info as a mimebundle of formatted representations.
1824 """Get object info as a mimebundle of formatted representations.
1815
1825
1816 A mimebundle is a dictionary, keyed by mime-type.
1826 A mimebundle is a dictionary, keyed by mime-type.
1817 It must always have the key `'text/plain'`.
1827 It must always have the key `'text/plain'`.
1818 """
1828 """
1819 with self.builtin_trap:
1829 with self.builtin_trap:
1820 info = self._object_find(oname)
1830 info = self._object_find(oname)
1821 if info.found:
1831 if info.found:
1822 docformat = (
1832 docformat = (
1823 sphinxify(self.object_inspect(oname))
1833 sphinxify(self.object_inspect(oname))
1824 if self.sphinxify_docstring
1834 if self.sphinxify_docstring
1825 else None
1835 else None
1826 )
1836 )
1827 return self.inspector._get_info(
1837 return self.inspector._get_info(
1828 info.obj,
1838 info.obj,
1829 oname,
1839 oname,
1830 info=info,
1840 info=info,
1831 detail_level=detail_level,
1841 detail_level=detail_level,
1832 formatter=docformat,
1842 formatter=docformat,
1833 )
1843 )
1834 else:
1844 else:
1835 raise KeyError(oname)
1845 raise KeyError(oname)
1836
1846
1837 #-------------------------------------------------------------------------
1847 #-------------------------------------------------------------------------
1838 # Things related to history management
1848 # Things related to history management
1839 #-------------------------------------------------------------------------
1849 #-------------------------------------------------------------------------
1840
1850
1841 def init_history(self):
1851 def init_history(self):
1842 """Sets up the command history, and starts regular autosaves."""
1852 """Sets up the command history, and starts regular autosaves."""
1843 self.history_manager = HistoryManager(shell=self, parent=self)
1853 self.history_manager = HistoryManager(shell=self, parent=self)
1844 self.configurables.append(self.history_manager)
1854 self.configurables.append(self.history_manager)
1845
1855
1846 #-------------------------------------------------------------------------
1856 #-------------------------------------------------------------------------
1847 # Things related to exception handling and tracebacks (not debugging)
1857 # Things related to exception handling and tracebacks (not debugging)
1848 #-------------------------------------------------------------------------
1858 #-------------------------------------------------------------------------
1849
1859
1850 debugger_cls = InterruptiblePdb
1860 debugger_cls = InterruptiblePdb
1851
1861
1852 def init_traceback_handlers(self, custom_exceptions):
1862 def init_traceback_handlers(self, custom_exceptions):
1853 # Syntax error handler.
1863 # Syntax error handler.
1854 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1864 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1855
1865
1856 # The interactive one is initialized with an offset, meaning we always
1866 # The interactive one is initialized with an offset, meaning we always
1857 # want to remove the topmost item in the traceback, which is our own
1867 # want to remove the topmost item in the traceback, which is our own
1858 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1868 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
1859 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1869 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1860 color_scheme='NoColor',
1870 color_scheme='NoColor',
1861 tb_offset = 1,
1871 tb_offset = 1,
1862 check_cache=check_linecache_ipython,
1872 check_cache=check_linecache_ipython,
1863 debugger_cls=self.debugger_cls, parent=self)
1873 debugger_cls=self.debugger_cls, parent=self)
1864
1874
1865 # The instance will store a pointer to the system-wide exception hook,
1875 # The instance will store a pointer to the system-wide exception hook,
1866 # so that runtime code (such as magics) can access it. This is because
1876 # so that runtime code (such as magics) can access it. This is because
1867 # during the read-eval loop, it may get temporarily overwritten.
1877 # during the read-eval loop, it may get temporarily overwritten.
1868 self.sys_excepthook = sys.excepthook
1878 self.sys_excepthook = sys.excepthook
1869
1879
1870 # and add any custom exception handlers the user may have specified
1880 # and add any custom exception handlers the user may have specified
1871 self.set_custom_exc(*custom_exceptions)
1881 self.set_custom_exc(*custom_exceptions)
1872
1882
1873 # Set the exception mode
1883 # Set the exception mode
1874 self.InteractiveTB.set_mode(mode=self.xmode)
1884 self.InteractiveTB.set_mode(mode=self.xmode)
1875
1885
1876 def set_custom_exc(self, exc_tuple, handler):
1886 def set_custom_exc(self, exc_tuple, handler):
1877 """set_custom_exc(exc_tuple, handler)
1887 """set_custom_exc(exc_tuple, handler)
1878
1888
1879 Set a custom exception handler, which will be called if any of the
1889 Set a custom exception handler, which will be called if any of the
1880 exceptions in exc_tuple occur in the mainloop (specifically, in the
1890 exceptions in exc_tuple occur in the mainloop (specifically, in the
1881 run_code() method).
1891 run_code() method).
1882
1892
1883 Parameters
1893 Parameters
1884 ----------
1894 ----------
1885
1895
1886 exc_tuple : tuple of exception classes
1896 exc_tuple : tuple of exception classes
1887 A *tuple* of exception classes, for which to call the defined
1897 A *tuple* of exception classes, for which to call the defined
1888 handler. It is very important that you use a tuple, and NOT A
1898 handler. It is very important that you use a tuple, and NOT A
1889 LIST here, because of the way Python's except statement works. If
1899 LIST here, because of the way Python's except statement works. If
1890 you only want to trap a single exception, use a singleton tuple::
1900 you only want to trap a single exception, use a singleton tuple::
1891
1901
1892 exc_tuple == (MyCustomException,)
1902 exc_tuple == (MyCustomException,)
1893
1903
1894 handler : callable
1904 handler : callable
1895 handler must have the following signature::
1905 handler must have the following signature::
1896
1906
1897 def my_handler(self, etype, value, tb, tb_offset=None):
1907 def my_handler(self, etype, value, tb, tb_offset=None):
1898 ...
1908 ...
1899 return structured_traceback
1909 return structured_traceback
1900
1910
1901 Your handler must return a structured traceback (a list of strings),
1911 Your handler must return a structured traceback (a list of strings),
1902 or None.
1912 or None.
1903
1913
1904 This will be made into an instance method (via types.MethodType)
1914 This will be made into an instance method (via types.MethodType)
1905 of IPython itself, and it will be called if any of the exceptions
1915 of IPython itself, and it will be called if any of the exceptions
1906 listed in the exc_tuple are caught. If the handler is None, an
1916 listed in the exc_tuple are caught. If the handler is None, an
1907 internal basic one is used, which just prints basic info.
1917 internal basic one is used, which just prints basic info.
1908
1918
1909 To protect IPython from crashes, if your handler ever raises an
1919 To protect IPython from crashes, if your handler ever raises an
1910 exception or returns an invalid result, it will be immediately
1920 exception or returns an invalid result, it will be immediately
1911 disabled.
1921 disabled.
1912
1922
1913 Notes
1923 Notes
1914 -----
1924 -----
1915
1925
1916 WARNING: by putting in your own exception handler into IPython's main
1926 WARNING: by putting in your own exception handler into IPython's main
1917 execution loop, you run a very good chance of nasty crashes. This
1927 execution loop, you run a very good chance of nasty crashes. This
1918 facility should only be used if you really know what you are doing."""
1928 facility should only be used if you really know what you are doing."""
1919 if not isinstance(exc_tuple, tuple):
1929 if not isinstance(exc_tuple, tuple):
1920 raise TypeError("The custom exceptions must be given as a tuple.")
1930 raise TypeError("The custom exceptions must be given as a tuple.")
1921
1931
1922 def dummy_handler(self, etype, value, tb, tb_offset=None):
1932 def dummy_handler(self, etype, value, tb, tb_offset=None):
1923 print('*** Simple custom exception handler ***')
1933 print('*** Simple custom exception handler ***')
1924 print('Exception type :', etype)
1934 print('Exception type :', etype)
1925 print('Exception value:', value)
1935 print('Exception value:', value)
1926 print('Traceback :', tb)
1936 print('Traceback :', tb)
1927
1937
1928 def validate_stb(stb):
1938 def validate_stb(stb):
1929 """validate structured traceback return type
1939 """validate structured traceback return type
1930
1940
1931 return type of CustomTB *should* be a list of strings, but allow
1941 return type of CustomTB *should* be a list of strings, but allow
1932 single strings or None, which are harmless.
1942 single strings or None, which are harmless.
1933
1943
1934 This function will *always* return a list of strings,
1944 This function will *always* return a list of strings,
1935 and will raise a TypeError if stb is inappropriate.
1945 and will raise a TypeError if stb is inappropriate.
1936 """
1946 """
1937 msg = "CustomTB must return list of strings, not %r" % stb
1947 msg = "CustomTB must return list of strings, not %r" % stb
1938 if stb is None:
1948 if stb is None:
1939 return []
1949 return []
1940 elif isinstance(stb, str):
1950 elif isinstance(stb, str):
1941 return [stb]
1951 return [stb]
1942 elif not isinstance(stb, list):
1952 elif not isinstance(stb, list):
1943 raise TypeError(msg)
1953 raise TypeError(msg)
1944 # it's a list
1954 # it's a list
1945 for line in stb:
1955 for line in stb:
1946 # check every element
1956 # check every element
1947 if not isinstance(line, str):
1957 if not isinstance(line, str):
1948 raise TypeError(msg)
1958 raise TypeError(msg)
1949 return stb
1959 return stb
1950
1960
1951 if handler is None:
1961 if handler is None:
1952 wrapped = dummy_handler
1962 wrapped = dummy_handler
1953 else:
1963 else:
1954 def wrapped(self,etype,value,tb,tb_offset=None):
1964 def wrapped(self,etype,value,tb,tb_offset=None):
1955 """wrap CustomTB handler, to protect IPython from user code
1965 """wrap CustomTB handler, to protect IPython from user code
1956
1966
1957 This makes it harder (but not impossible) for custom exception
1967 This makes it harder (but not impossible) for custom exception
1958 handlers to crash IPython.
1968 handlers to crash IPython.
1959 """
1969 """
1960 try:
1970 try:
1961 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1971 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1962 return validate_stb(stb)
1972 return validate_stb(stb)
1963 except:
1973 except:
1964 # clear custom handler immediately
1974 # clear custom handler immediately
1965 self.set_custom_exc((), None)
1975 self.set_custom_exc((), None)
1966 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1976 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1967 # show the exception in handler first
1977 # show the exception in handler first
1968 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1978 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1969 print(self.InteractiveTB.stb2text(stb))
1979 print(self.InteractiveTB.stb2text(stb))
1970 print("The original exception:")
1980 print("The original exception:")
1971 stb = self.InteractiveTB.structured_traceback(
1981 stb = self.InteractiveTB.structured_traceback(
1972 (etype,value,tb), tb_offset=tb_offset
1982 (etype,value,tb), tb_offset=tb_offset
1973 )
1983 )
1974 return stb
1984 return stb
1975
1985
1976 self.CustomTB = types.MethodType(wrapped,self)
1986 self.CustomTB = types.MethodType(wrapped,self)
1977 self.custom_exceptions = exc_tuple
1987 self.custom_exceptions = exc_tuple
1978
1988
1979 def excepthook(self, etype, value, tb):
1989 def excepthook(self, etype, value, tb):
1980 """One more defense for GUI apps that call sys.excepthook.
1990 """One more defense for GUI apps that call sys.excepthook.
1981
1991
1982 GUI frameworks like wxPython trap exceptions and call
1992 GUI frameworks like wxPython trap exceptions and call
1983 sys.excepthook themselves. I guess this is a feature that
1993 sys.excepthook themselves. I guess this is a feature that
1984 enables them to keep running after exceptions that would
1994 enables them to keep running after exceptions that would
1985 otherwise kill their mainloop. This is a bother for IPython
1995 otherwise kill their mainloop. This is a bother for IPython
1986 which expects to catch all of the program exceptions with a try:
1996 which expects to catch all of the program exceptions with a try:
1987 except: statement.
1997 except: statement.
1988
1998
1989 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1999 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1990 any app directly invokes sys.excepthook, it will look to the user like
2000 any app directly invokes sys.excepthook, it will look to the user like
1991 IPython crashed. In order to work around this, we can disable the
2001 IPython crashed. In order to work around this, we can disable the
1992 CrashHandler and replace it with this excepthook instead, which prints a
2002 CrashHandler and replace it with this excepthook instead, which prints a
1993 regular traceback using our InteractiveTB. In this fashion, apps which
2003 regular traceback using our InteractiveTB. In this fashion, apps which
1994 call sys.excepthook will generate a regular-looking exception from
2004 call sys.excepthook will generate a regular-looking exception from
1995 IPython, and the CrashHandler will only be triggered by real IPython
2005 IPython, and the CrashHandler will only be triggered by real IPython
1996 crashes.
2006 crashes.
1997
2007
1998 This hook should be used sparingly, only in places which are not likely
2008 This hook should be used sparingly, only in places which are not likely
1999 to be true IPython errors.
2009 to be true IPython errors.
2000 """
2010 """
2001 self.showtraceback((etype, value, tb), tb_offset=0)
2011 self.showtraceback((etype, value, tb), tb_offset=0)
2002
2012
2003 def _get_exc_info(self, exc_tuple=None):
2013 def _get_exc_info(self, exc_tuple=None):
2004 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
2014 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
2005
2015
2006 Ensures sys.last_type,value,traceback hold the exc_info we found,
2016 Ensures sys.last_type,value,traceback hold the exc_info we found,
2007 from whichever source.
2017 from whichever source.
2008
2018
2009 raises ValueError if none of these contain any information
2019 raises ValueError if none of these contain any information
2010 """
2020 """
2011 if exc_tuple is None:
2021 if exc_tuple is None:
2012 etype, value, tb = sys.exc_info()
2022 etype, value, tb = sys.exc_info()
2013 else:
2023 else:
2014 etype, value, tb = exc_tuple
2024 etype, value, tb = exc_tuple
2015
2025
2016 if etype is None:
2026 if etype is None:
2017 if hasattr(sys, 'last_type'):
2027 if hasattr(sys, 'last_type'):
2018 etype, value, tb = sys.last_type, sys.last_value, \
2028 etype, value, tb = sys.last_type, sys.last_value, \
2019 sys.last_traceback
2029 sys.last_traceback
2020
2030
2021 if etype is None:
2031 if etype is None:
2022 raise ValueError("No exception to find")
2032 raise ValueError("No exception to find")
2023
2033
2024 # Now store the exception info in sys.last_type etc.
2034 # Now store the exception info in sys.last_type etc.
2025 # WARNING: these variables are somewhat deprecated and not
2035 # WARNING: these variables are somewhat deprecated and not
2026 # necessarily safe to use in a threaded environment, but tools
2036 # necessarily safe to use in a threaded environment, but tools
2027 # like pdb depend on their existence, so let's set them. If we
2037 # like pdb depend on their existence, so let's set them. If we
2028 # find problems in the field, we'll need to revisit their use.
2038 # find problems in the field, we'll need to revisit their use.
2029 sys.last_type = etype
2039 sys.last_type = etype
2030 sys.last_value = value
2040 sys.last_value = value
2031 sys.last_traceback = tb
2041 sys.last_traceback = tb
2032
2042
2033 return etype, value, tb
2043 return etype, value, tb
2034
2044
2035 def show_usage_error(self, exc):
2045 def show_usage_error(self, exc):
2036 """Show a short message for UsageErrors
2046 """Show a short message for UsageErrors
2037
2047
2038 These are special exceptions that shouldn't show a traceback.
2048 These are special exceptions that shouldn't show a traceback.
2039 """
2049 """
2040 print("UsageError: %s" % exc, file=sys.stderr)
2050 print("UsageError: %s" % exc, file=sys.stderr)
2041
2051
2042 def get_exception_only(self, exc_tuple=None):
2052 def get_exception_only(self, exc_tuple=None):
2043 """
2053 """
2044 Return as a string (ending with a newline) the exception that
2054 Return as a string (ending with a newline) the exception that
2045 just occurred, without any traceback.
2055 just occurred, without any traceback.
2046 """
2056 """
2047 etype, value, tb = self._get_exc_info(exc_tuple)
2057 etype, value, tb = self._get_exc_info(exc_tuple)
2048 msg = traceback.format_exception_only(etype, value)
2058 msg = traceback.format_exception_only(etype, value)
2049 return ''.join(msg)
2059 return ''.join(msg)
2050
2060
2051 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
2061 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
2052 exception_only=False, running_compiled_code=False):
2062 exception_only=False, running_compiled_code=False):
2053 """Display the exception that just occurred.
2063 """Display the exception that just occurred.
2054
2064
2055 If nothing is known about the exception, this is the method which
2065 If nothing is known about the exception, this is the method which
2056 should be used throughout the code for presenting user tracebacks,
2066 should be used throughout the code for presenting user tracebacks,
2057 rather than directly invoking the InteractiveTB object.
2067 rather than directly invoking the InteractiveTB object.
2058
2068
2059 A specific showsyntaxerror() also exists, but this method can take
2069 A specific showsyntaxerror() also exists, but this method can take
2060 care of calling it if needed, so unless you are explicitly catching a
2070 care of calling it if needed, so unless you are explicitly catching a
2061 SyntaxError exception, don't try to analyze the stack manually and
2071 SyntaxError exception, don't try to analyze the stack manually and
2062 simply call this method."""
2072 simply call this method."""
2063
2073
2064 try:
2074 try:
2065 try:
2075 try:
2066 etype, value, tb = self._get_exc_info(exc_tuple)
2076 etype, value, tb = self._get_exc_info(exc_tuple)
2067 except ValueError:
2077 except ValueError:
2068 print('No traceback available to show.', file=sys.stderr)
2078 print('No traceback available to show.', file=sys.stderr)
2069 return
2079 return
2070
2080
2071 if issubclass(etype, SyntaxError):
2081 if issubclass(etype, SyntaxError):
2072 # Though this won't be called by syntax errors in the input
2082 # Though this won't be called by syntax errors in the input
2073 # line, there may be SyntaxError cases with imported code.
2083 # line, there may be SyntaxError cases with imported code.
2074 self.showsyntaxerror(filename, running_compiled_code)
2084 self.showsyntaxerror(filename, running_compiled_code)
2075 elif etype is UsageError:
2085 elif etype is UsageError:
2076 self.show_usage_error(value)
2086 self.show_usage_error(value)
2077 else:
2087 else:
2078 if exception_only:
2088 if exception_only:
2079 stb = ['An exception has occurred, use %tb to see '
2089 stb = ['An exception has occurred, use %tb to see '
2080 'the full traceback.\n']
2090 'the full traceback.\n']
2081 stb.extend(self.InteractiveTB.get_exception_only(etype,
2091 stb.extend(self.InteractiveTB.get_exception_only(etype,
2082 value))
2092 value))
2083 else:
2093 else:
2084 try:
2094 try:
2085 # Exception classes can customise their traceback - we
2095 # Exception classes can customise their traceback - we
2086 # use this in IPython.parallel for exceptions occurring
2096 # use this in IPython.parallel for exceptions occurring
2087 # in the engines. This should return a list of strings.
2097 # in the engines. This should return a list of strings.
2088 stb = value._render_traceback_()
2098 stb = value._render_traceback_()
2089 except Exception:
2099 except Exception:
2090 stb = self.InteractiveTB.structured_traceback(etype,
2100 stb = self.InteractiveTB.structured_traceback(etype,
2091 value, tb, tb_offset=tb_offset)
2101 value, tb, tb_offset=tb_offset)
2092
2102
2093 self._showtraceback(etype, value, stb)
2103 self._showtraceback(etype, value, stb)
2094 if self.call_pdb:
2104 if self.call_pdb:
2095 # drop into debugger
2105 # drop into debugger
2096 self.debugger(force=True)
2106 self.debugger(force=True)
2097 return
2107 return
2098
2108
2099 # Actually show the traceback
2109 # Actually show the traceback
2100 self._showtraceback(etype, value, stb)
2110 self._showtraceback(etype, value, stb)
2101
2111
2102 except KeyboardInterrupt:
2112 except KeyboardInterrupt:
2103 print('\n' + self.get_exception_only(), file=sys.stderr)
2113 print('\n' + self.get_exception_only(), file=sys.stderr)
2104
2114
2105 def _showtraceback(self, etype, evalue, stb: str):
2115 def _showtraceback(self, etype, evalue, stb: str):
2106 """Actually show a traceback.
2116 """Actually show a traceback.
2107
2117
2108 Subclasses may override this method to put the traceback on a different
2118 Subclasses may override this method to put the traceback on a different
2109 place, like a side channel.
2119 place, like a side channel.
2110 """
2120 """
2111 val = self.InteractiveTB.stb2text(stb)
2121 val = self.InteractiveTB.stb2text(stb)
2112 try:
2122 try:
2113 print(val)
2123 print(val)
2114 except UnicodeEncodeError:
2124 except UnicodeEncodeError:
2115 print(val.encode("utf-8", "backslashreplace").decode())
2125 print(val.encode("utf-8", "backslashreplace").decode())
2116
2126
2117 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2127 def showsyntaxerror(self, filename=None, running_compiled_code=False):
2118 """Display the syntax error that just occurred.
2128 """Display the syntax error that just occurred.
2119
2129
2120 This doesn't display a stack trace because there isn't one.
2130 This doesn't display a stack trace because there isn't one.
2121
2131
2122 If a filename is given, it is stuffed in the exception instead
2132 If a filename is given, it is stuffed in the exception instead
2123 of what was there before (because Python's parser always uses
2133 of what was there before (because Python's parser always uses
2124 "<string>" when reading from a string).
2134 "<string>" when reading from a string).
2125
2135
2126 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2136 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
2127 longer stack trace will be displayed.
2137 longer stack trace will be displayed.
2128 """
2138 """
2129 etype, value, last_traceback = self._get_exc_info()
2139 etype, value, last_traceback = self._get_exc_info()
2130
2140
2131 if filename and issubclass(etype, SyntaxError):
2141 if filename and issubclass(etype, SyntaxError):
2132 try:
2142 try:
2133 value.filename = filename
2143 value.filename = filename
2134 except:
2144 except:
2135 # Not the format we expect; leave it alone
2145 # Not the format we expect; leave it alone
2136 pass
2146 pass
2137
2147
2138 # If the error occurred when executing compiled code, we should provide full stacktrace.
2148 # If the error occurred when executing compiled code, we should provide full stacktrace.
2139 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2149 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
2140 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2150 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
2141 self._showtraceback(etype, value, stb)
2151 self._showtraceback(etype, value, stb)
2142
2152
2143 # This is overridden in TerminalInteractiveShell to show a message about
2153 # This is overridden in TerminalInteractiveShell to show a message about
2144 # the %paste magic.
2154 # the %paste magic.
2145 def showindentationerror(self):
2155 def showindentationerror(self):
2146 """Called by _run_cell when there's an IndentationError in code entered
2156 """Called by _run_cell when there's an IndentationError in code entered
2147 at the prompt.
2157 at the prompt.
2148
2158
2149 This is overridden in TerminalInteractiveShell to show a message about
2159 This is overridden in TerminalInteractiveShell to show a message about
2150 the %paste magic."""
2160 the %paste magic."""
2151 self.showsyntaxerror()
2161 self.showsyntaxerror()
2152
2162
2153 #-------------------------------------------------------------------------
2163 #-------------------------------------------------------------------------
2154 # Things related to readline
2164 # Things related to readline
2155 #-------------------------------------------------------------------------
2165 #-------------------------------------------------------------------------
2156
2166
2157 def init_readline(self):
2167 def init_readline(self):
2158 """DEPRECATED
2168 """DEPRECATED
2159
2169
2160 Moved to terminal subclass, here only to simplify the init logic."""
2170 Moved to terminal subclass, here only to simplify the init logic."""
2161 # Set a number of methods that depend on readline to be no-op
2171 # Set a number of methods that depend on readline to be no-op
2162 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
2172 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
2163 DeprecationWarning, stacklevel=2)
2173 DeprecationWarning, stacklevel=2)
2164 self.set_custom_completer = no_op
2174 self.set_custom_completer = no_op
2165
2175
2166 @skip_doctest
2176 @skip_doctest
2167 def set_next_input(self, s, replace=False):
2177 def set_next_input(self, s, replace=False):
2168 """ Sets the 'default' input string for the next command line.
2178 """ Sets the 'default' input string for the next command line.
2169
2179
2170 Example::
2180 Example::
2171
2181
2172 In [1]: _ip.set_next_input("Hello Word")
2182 In [1]: _ip.set_next_input("Hello Word")
2173 In [2]: Hello Word_ # cursor is here
2183 In [2]: Hello Word_ # cursor is here
2174 """
2184 """
2175 self.rl_next_input = s
2185 self.rl_next_input = s
2176
2186
2177 def _indent_current_str(self):
2187 def _indent_current_str(self):
2178 """return the current level of indentation as a string"""
2188 """return the current level of indentation as a string"""
2179 return self.input_splitter.get_indent_spaces() * ' '
2189 return self.input_splitter.get_indent_spaces() * ' '
2180
2190
2181 #-------------------------------------------------------------------------
2191 #-------------------------------------------------------------------------
2182 # Things related to text completion
2192 # Things related to text completion
2183 #-------------------------------------------------------------------------
2193 #-------------------------------------------------------------------------
2184
2194
2185 def init_completer(self):
2195 def init_completer(self):
2186 """Initialize the completion machinery.
2196 """Initialize the completion machinery.
2187
2197
2188 This creates completion machinery that can be used by client code,
2198 This creates completion machinery that can be used by client code,
2189 either interactively in-process (typically triggered by the readline
2199 either interactively in-process (typically triggered by the readline
2190 library), programmatically (such as in test suites) or out-of-process
2200 library), programmatically (such as in test suites) or out-of-process
2191 (typically over the network by remote frontends).
2201 (typically over the network by remote frontends).
2192 """
2202 """
2193 from IPython.core.completer import IPCompleter
2203 from IPython.core.completer import IPCompleter
2194 from IPython.core.completerlib import (module_completer,
2204 from IPython.core.completerlib import (module_completer,
2195 magic_run_completer, cd_completer, reset_completer)
2205 magic_run_completer, cd_completer, reset_completer)
2196
2206
2197 self.Completer = IPCompleter(shell=self,
2207 self.Completer = IPCompleter(shell=self,
2198 namespace=self.user_ns,
2208 namespace=self.user_ns,
2199 global_namespace=self.user_global_ns,
2209 global_namespace=self.user_global_ns,
2200 parent=self,
2210 parent=self,
2201 )
2211 )
2202 self.configurables.append(self.Completer)
2212 self.configurables.append(self.Completer)
2203
2213
2204 # Add custom completers to the basic ones built into IPCompleter
2214 # Add custom completers to the basic ones built into IPCompleter
2205 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2215 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
2206 self.strdispatchers['complete_command'] = sdisp
2216 self.strdispatchers['complete_command'] = sdisp
2207 self.Completer.custom_completers = sdisp
2217 self.Completer.custom_completers = sdisp
2208
2218
2209 self.set_hook('complete_command', module_completer, str_key = 'import')
2219 self.set_hook('complete_command', module_completer, str_key = 'import')
2210 self.set_hook('complete_command', module_completer, str_key = 'from')
2220 self.set_hook('complete_command', module_completer, str_key = 'from')
2211 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2221 self.set_hook('complete_command', module_completer, str_key = '%aimport')
2212 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2222 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
2213 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2223 self.set_hook('complete_command', cd_completer, str_key = '%cd')
2214 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2224 self.set_hook('complete_command', reset_completer, str_key = '%reset')
2215
2225
2216 @skip_doctest
2226 @skip_doctest
2217 def complete(self, text, line=None, cursor_pos=None):
2227 def complete(self, text, line=None, cursor_pos=None):
2218 """Return the completed text and a list of completions.
2228 """Return the completed text and a list of completions.
2219
2229
2220 Parameters
2230 Parameters
2221 ----------
2231 ----------
2222
2232
2223 text : string
2233 text : string
2224 A string of text to be completed on. It can be given as empty and
2234 A string of text to be completed on. It can be given as empty and
2225 instead a line/position pair are given. In this case, the
2235 instead a line/position pair are given. In this case, the
2226 completer itself will split the line like readline does.
2236 completer itself will split the line like readline does.
2227
2237
2228 line : string, optional
2238 line : string, optional
2229 The complete line that text is part of.
2239 The complete line that text is part of.
2230
2240
2231 cursor_pos : int, optional
2241 cursor_pos : int, optional
2232 The position of the cursor on the input line.
2242 The position of the cursor on the input line.
2233
2243
2234 Returns
2244 Returns
2235 -------
2245 -------
2236 text : string
2246 text : string
2237 The actual text that was completed.
2247 The actual text that was completed.
2238
2248
2239 matches : list
2249 matches : list
2240 A sorted list with all possible completions.
2250 A sorted list with all possible completions.
2241
2251
2242 The optional arguments allow the completion to take more context into
2252 The optional arguments allow the completion to take more context into
2243 account, and are part of the low-level completion API.
2253 account, and are part of the low-level completion API.
2244
2254
2245 This is a wrapper around the completion mechanism, similar to what
2255 This is a wrapper around the completion mechanism, similar to what
2246 readline does at the command line when the TAB key is hit. By
2256 readline does at the command line when the TAB key is hit. By
2247 exposing it as a method, it can be used by other non-readline
2257 exposing it as a method, it can be used by other non-readline
2248 environments (such as GUIs) for text completion.
2258 environments (such as GUIs) for text completion.
2249
2259
2250 Simple usage example:
2260 Simple usage example:
2251
2261
2252 In [1]: x = 'hello'
2262 In [1]: x = 'hello'
2253
2263
2254 In [2]: _ip.complete('x.l')
2264 In [2]: _ip.complete('x.l')
2255 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2265 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2256 """
2266 """
2257
2267
2258 # Inject names into __builtin__ so we can complete on the added names.
2268 # Inject names into __builtin__ so we can complete on the added names.
2259 with self.builtin_trap:
2269 with self.builtin_trap:
2260 return self.Completer.complete(text, line, cursor_pos)
2270 return self.Completer.complete(text, line, cursor_pos)
2261
2271
2262 def set_custom_completer(self, completer, pos=0) -> None:
2272 def set_custom_completer(self, completer, pos=0) -> None:
2263 """Adds a new custom completer function.
2273 """Adds a new custom completer function.
2264
2274
2265 The position argument (defaults to 0) is the index in the completers
2275 The position argument (defaults to 0) is the index in the completers
2266 list where you want the completer to be inserted.
2276 list where you want the completer to be inserted.
2267
2277
2268 `completer` should have the following signature::
2278 `completer` should have the following signature::
2269
2279
2270 def completion(self: Completer, text: string) -> List[str]:
2280 def completion(self: Completer, text: string) -> List[str]:
2271 raise NotImplementedError
2281 raise NotImplementedError
2272
2282
2273 It will be bound to the current Completer instance and pass some text
2283 It will be bound to the current Completer instance and pass some text
2274 and return a list with current completions to suggest to the user.
2284 and return a list with current completions to suggest to the user.
2275 """
2285 """
2276
2286
2277 newcomp = types.MethodType(completer, self.Completer)
2287 newcomp = types.MethodType(completer, self.Completer)
2278 self.Completer.custom_matchers.insert(pos,newcomp)
2288 self.Completer.custom_matchers.insert(pos,newcomp)
2279
2289
2280 def set_completer_frame(self, frame=None):
2290 def set_completer_frame(self, frame=None):
2281 """Set the frame of the completer."""
2291 """Set the frame of the completer."""
2282 if frame:
2292 if frame:
2283 self.Completer.namespace = frame.f_locals
2293 self.Completer.namespace = frame.f_locals
2284 self.Completer.global_namespace = frame.f_globals
2294 self.Completer.global_namespace = frame.f_globals
2285 else:
2295 else:
2286 self.Completer.namespace = self.user_ns
2296 self.Completer.namespace = self.user_ns
2287 self.Completer.global_namespace = self.user_global_ns
2297 self.Completer.global_namespace = self.user_global_ns
2288
2298
2289 #-------------------------------------------------------------------------
2299 #-------------------------------------------------------------------------
2290 # Things related to magics
2300 # Things related to magics
2291 #-------------------------------------------------------------------------
2301 #-------------------------------------------------------------------------
2292
2302
2293 def init_magics(self):
2303 def init_magics(self):
2294 from IPython.core import magics as m
2304 from IPython.core import magics as m
2295 self.magics_manager = magic.MagicsManager(shell=self,
2305 self.magics_manager = magic.MagicsManager(shell=self,
2296 parent=self,
2306 parent=self,
2297 user_magics=m.UserMagics(self))
2307 user_magics=m.UserMagics(self))
2298 self.configurables.append(self.magics_manager)
2308 self.configurables.append(self.magics_manager)
2299
2309
2300 # Expose as public API from the magics manager
2310 # Expose as public API from the magics manager
2301 self.register_magics = self.magics_manager.register
2311 self.register_magics = self.magics_manager.register
2302
2312
2303 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2313 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2304 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2314 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2305 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2315 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2306 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2316 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
2307 m.PylabMagics, m.ScriptMagics,
2317 m.PylabMagics, m.ScriptMagics,
2308 )
2318 )
2309 self.register_magics(m.AsyncMagics)
2319 self.register_magics(m.AsyncMagics)
2310
2320
2311 # Register Magic Aliases
2321 # Register Magic Aliases
2312 mman = self.magics_manager
2322 mman = self.magics_manager
2313 # FIXME: magic aliases should be defined by the Magics classes
2323 # FIXME: magic aliases should be defined by the Magics classes
2314 # or in MagicsManager, not here
2324 # or in MagicsManager, not here
2315 mman.register_alias('ed', 'edit')
2325 mman.register_alias('ed', 'edit')
2316 mman.register_alias('hist', 'history')
2326 mman.register_alias('hist', 'history')
2317 mman.register_alias('rep', 'recall')
2327 mman.register_alias('rep', 'recall')
2318 mman.register_alias('SVG', 'svg', 'cell')
2328 mman.register_alias('SVG', 'svg', 'cell')
2319 mman.register_alias('HTML', 'html', 'cell')
2329 mman.register_alias('HTML', 'html', 'cell')
2320 mman.register_alias('file', 'writefile', 'cell')
2330 mman.register_alias('file', 'writefile', 'cell')
2321
2331
2322 # FIXME: Move the color initialization to the DisplayHook, which
2332 # FIXME: Move the color initialization to the DisplayHook, which
2323 # should be split into a prompt manager and displayhook. We probably
2333 # should be split into a prompt manager and displayhook. We probably
2324 # even need a centralize colors management object.
2334 # even need a centralize colors management object.
2325 self.run_line_magic('colors', self.colors)
2335 self.run_line_magic('colors', self.colors)
2326
2336
2327 # Defined here so that it's included in the documentation
2337 # Defined here so that it's included in the documentation
2328 @functools.wraps(magic.MagicsManager.register_function)
2338 @functools.wraps(magic.MagicsManager.register_function)
2329 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2339 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2330 self.magics_manager.register_function(
2340 self.magics_manager.register_function(
2331 func, magic_kind=magic_kind, magic_name=magic_name
2341 func, magic_kind=magic_kind, magic_name=magic_name
2332 )
2342 )
2333
2343
2334 def _find_with_lazy_load(self, type_, magic_name: str):
2344 def _find_with_lazy_load(self, type_, magic_name: str):
2335 """
2345 """
2336 Try to find a magic potentially lazy-loading it.
2346 Try to find a magic potentially lazy-loading it.
2337
2347
2338 Parameters
2348 Parameters
2339 ----------
2349 ----------
2340
2350
2341 type_: "line"|"cell"
2351 type_: "line"|"cell"
2342 the type of magics we are trying to find/lazy load.
2352 the type of magics we are trying to find/lazy load.
2343 magic_name: str
2353 magic_name: str
2344 The name of the magic we are trying to find/lazy load
2354 The name of the magic we are trying to find/lazy load
2345
2355
2346
2356
2347 Note that this may have any side effects
2357 Note that this may have any side effects
2348 """
2358 """
2349 finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_]
2359 finder = {"line": self.find_line_magic, "cell": self.find_cell_magic}[type_]
2350 fn = finder(magic_name)
2360 fn = finder(magic_name)
2351 if fn is not None:
2361 if fn is not None:
2352 return fn
2362 return fn
2353 lazy = self.magics_manager.lazy_magics.get(magic_name)
2363 lazy = self.magics_manager.lazy_magics.get(magic_name)
2354 if lazy is None:
2364 if lazy is None:
2355 return None
2365 return None
2356
2366
2357 self.run_line_magic("load_ext", lazy)
2367 self.run_line_magic("load_ext", lazy)
2358 res = finder(magic_name)
2368 res = finder(magic_name)
2359 return res
2369 return res
2360
2370
2361 def run_line_magic(self, magic_name: str, line, _stack_depth=1):
2371 def run_line_magic(self, magic_name: str, line, _stack_depth=1):
2362 """Execute the given line magic.
2372 """Execute the given line magic.
2363
2373
2364 Parameters
2374 Parameters
2365 ----------
2375 ----------
2366 magic_name : str
2376 magic_name : str
2367 Name of the desired magic function, without '%' prefix.
2377 Name of the desired magic function, without '%' prefix.
2368
2378
2369 line : str
2379 line : str
2370 The rest of the input line as a single string.
2380 The rest of the input line as a single string.
2371
2381
2372 _stack_depth : int
2382 _stack_depth : int
2373 If run_line_magic() is called from magic() then _stack_depth=2.
2383 If run_line_magic() is called from magic() then _stack_depth=2.
2374 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2384 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2375 """
2385 """
2376 fn = self._find_with_lazy_load("line", magic_name)
2386 fn = self._find_with_lazy_load("line", magic_name)
2377 if fn is None:
2387 if fn is None:
2378 lazy = self.magics_manager.lazy_magics.get(magic_name)
2388 lazy = self.magics_manager.lazy_magics.get(magic_name)
2379 if lazy:
2389 if lazy:
2380 self.run_line_magic("load_ext", lazy)
2390 self.run_line_magic("load_ext", lazy)
2381 fn = self.find_line_magic(magic_name)
2391 fn = self.find_line_magic(magic_name)
2382 if fn is None:
2392 if fn is None:
2383 cm = self.find_cell_magic(magic_name)
2393 cm = self.find_cell_magic(magic_name)
2384 etpl = "Line magic function `%%%s` not found%s."
2394 etpl = "Line magic function `%%%s` not found%s."
2385 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2395 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2386 'did you mean that instead?)' % magic_name )
2396 'did you mean that instead?)' % magic_name )
2387 raise UsageError(etpl % (magic_name, extra))
2397 raise UsageError(etpl % (magic_name, extra))
2388 else:
2398 else:
2389 # Note: this is the distance in the stack to the user's frame.
2399 # Note: this is the distance in the stack to the user's frame.
2390 # This will need to be updated if the internal calling logic gets
2400 # This will need to be updated if the internal calling logic gets
2391 # refactored, or else we'll be expanding the wrong variables.
2401 # refactored, or else we'll be expanding the wrong variables.
2392
2402
2393 # Determine stack_depth depending on where run_line_magic() has been called
2403 # Determine stack_depth depending on where run_line_magic() has been called
2394 stack_depth = _stack_depth
2404 stack_depth = _stack_depth
2395 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2405 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2396 # magic has opted out of var_expand
2406 # magic has opted out of var_expand
2397 magic_arg_s = line
2407 magic_arg_s = line
2398 else:
2408 else:
2399 magic_arg_s = self.var_expand(line, stack_depth)
2409 magic_arg_s = self.var_expand(line, stack_depth)
2400 # Put magic args in a list so we can call with f(*a) syntax
2410 # Put magic args in a list so we can call with f(*a) syntax
2401 args = [magic_arg_s]
2411 args = [magic_arg_s]
2402 kwargs = {}
2412 kwargs = {}
2403 # Grab local namespace if we need it:
2413 # Grab local namespace if we need it:
2404 if getattr(fn, "needs_local_scope", False):
2414 if getattr(fn, "needs_local_scope", False):
2405 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2415 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2406 with self.builtin_trap:
2416 with self.builtin_trap:
2407 result = fn(*args, **kwargs)
2417 result = fn(*args, **kwargs)
2408 return result
2418 return result
2409
2419
2410 def get_local_scope(self, stack_depth):
2420 def get_local_scope(self, stack_depth):
2411 """Get local scope at given stack depth.
2421 """Get local scope at given stack depth.
2412
2422
2413 Parameters
2423 Parameters
2414 ----------
2424 ----------
2415 stack_depth : int
2425 stack_depth : int
2416 Depth relative to calling frame
2426 Depth relative to calling frame
2417 """
2427 """
2418 return sys._getframe(stack_depth + 1).f_locals
2428 return sys._getframe(stack_depth + 1).f_locals
2419
2429
2420 def run_cell_magic(self, magic_name, line, cell):
2430 def run_cell_magic(self, magic_name, line, cell):
2421 """Execute the given cell magic.
2431 """Execute the given cell magic.
2422
2432
2423 Parameters
2433 Parameters
2424 ----------
2434 ----------
2425 magic_name : str
2435 magic_name : str
2426 Name of the desired magic function, without '%' prefix.
2436 Name of the desired magic function, without '%' prefix.
2427
2437
2428 line : str
2438 line : str
2429 The rest of the first input line as a single string.
2439 The rest of the first input line as a single string.
2430
2440
2431 cell : str
2441 cell : str
2432 The body of the cell as a (possibly multiline) string.
2442 The body of the cell as a (possibly multiline) string.
2433 """
2443 """
2434 fn = self._find_with_lazy_load("cell", magic_name)
2444 fn = self._find_with_lazy_load("cell", magic_name)
2435 if fn is None:
2445 if fn is None:
2436 lm = self.find_line_magic(magic_name)
2446 lm = self.find_line_magic(magic_name)
2437 etpl = "Cell magic `%%{0}` not found{1}."
2447 etpl = "Cell magic `%%{0}` not found{1}."
2438 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2448 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2439 'did you mean that instead?)'.format(magic_name))
2449 'did you mean that instead?)'.format(magic_name))
2440 raise UsageError(etpl.format(magic_name, extra))
2450 raise UsageError(etpl.format(magic_name, extra))
2441 elif cell == '':
2451 elif cell == '':
2442 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2452 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2443 if self.find_line_magic(magic_name) is not None:
2453 if self.find_line_magic(magic_name) is not None:
2444 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2454 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2445 raise UsageError(message)
2455 raise UsageError(message)
2446 else:
2456 else:
2447 # Note: this is the distance in the stack to the user's frame.
2457 # Note: this is the distance in the stack to the user's frame.
2448 # This will need to be updated if the internal calling logic gets
2458 # This will need to be updated if the internal calling logic gets
2449 # refactored, or else we'll be expanding the wrong variables.
2459 # refactored, or else we'll be expanding the wrong variables.
2450 stack_depth = 2
2460 stack_depth = 2
2451 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2461 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
2452 # magic has opted out of var_expand
2462 # magic has opted out of var_expand
2453 magic_arg_s = line
2463 magic_arg_s = line
2454 else:
2464 else:
2455 magic_arg_s = self.var_expand(line, stack_depth)
2465 magic_arg_s = self.var_expand(line, stack_depth)
2456 kwargs = {}
2466 kwargs = {}
2457 if getattr(fn, "needs_local_scope", False):
2467 if getattr(fn, "needs_local_scope", False):
2458 kwargs['local_ns'] = self.user_ns
2468 kwargs['local_ns'] = self.user_ns
2459
2469
2460 with self.builtin_trap:
2470 with self.builtin_trap:
2461 args = (magic_arg_s, cell)
2471 args = (magic_arg_s, cell)
2462 result = fn(*args, **kwargs)
2472 result = fn(*args, **kwargs)
2463 return result
2473 return result
2464
2474
2465 def find_line_magic(self, magic_name):
2475 def find_line_magic(self, magic_name):
2466 """Find and return a line magic by name.
2476 """Find and return a line magic by name.
2467
2477
2468 Returns None if the magic isn't found."""
2478 Returns None if the magic isn't found."""
2469 return self.magics_manager.magics['line'].get(magic_name)
2479 return self.magics_manager.magics['line'].get(magic_name)
2470
2480
2471 def find_cell_magic(self, magic_name):
2481 def find_cell_magic(self, magic_name):
2472 """Find and return a cell magic by name.
2482 """Find and return a cell magic by name.
2473
2483
2474 Returns None if the magic isn't found."""
2484 Returns None if the magic isn't found."""
2475 return self.magics_manager.magics['cell'].get(magic_name)
2485 return self.magics_manager.magics['cell'].get(magic_name)
2476
2486
2477 def find_magic(self, magic_name, magic_kind='line'):
2487 def find_magic(self, magic_name, magic_kind='line'):
2478 """Find and return a magic of the given type by name.
2488 """Find and return a magic of the given type by name.
2479
2489
2480 Returns None if the magic isn't found."""
2490 Returns None if the magic isn't found."""
2481 return self.magics_manager.magics[magic_kind].get(magic_name)
2491 return self.magics_manager.magics[magic_kind].get(magic_name)
2482
2492
2483 def magic(self, arg_s):
2493 def magic(self, arg_s):
2484 """DEPRECATED. Use run_line_magic() instead.
2494 """DEPRECATED. Use run_line_magic() instead.
2485
2495
2486 Call a magic function by name.
2496 Call a magic function by name.
2487
2497
2488 Input: a string containing the name of the magic function to call and
2498 Input: a string containing the name of the magic function to call and
2489 any additional arguments to be passed to the magic.
2499 any additional arguments to be passed to the magic.
2490
2500
2491 magic('name -opt foo bar') is equivalent to typing at the ipython
2501 magic('name -opt foo bar') is equivalent to typing at the ipython
2492 prompt:
2502 prompt:
2493
2503
2494 In[1]: %name -opt foo bar
2504 In[1]: %name -opt foo bar
2495
2505
2496 To call a magic without arguments, simply use magic('name').
2506 To call a magic without arguments, simply use magic('name').
2497
2507
2498 This provides a proper Python function to call IPython's magics in any
2508 This provides a proper Python function to call IPython's magics in any
2499 valid Python code you can type at the interpreter, including loops and
2509 valid Python code you can type at the interpreter, including loops and
2500 compound statements.
2510 compound statements.
2501 """
2511 """
2502 # TODO: should we issue a loud deprecation warning here?
2512 # TODO: should we issue a loud deprecation warning here?
2503 magic_name, _, magic_arg_s = arg_s.partition(' ')
2513 magic_name, _, magic_arg_s = arg_s.partition(' ')
2504 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2514 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2505 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2515 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2506
2516
2507 #-------------------------------------------------------------------------
2517 #-------------------------------------------------------------------------
2508 # Things related to macros
2518 # Things related to macros
2509 #-------------------------------------------------------------------------
2519 #-------------------------------------------------------------------------
2510
2520
2511 def define_macro(self, name, themacro):
2521 def define_macro(self, name, themacro):
2512 """Define a new macro
2522 """Define a new macro
2513
2523
2514 Parameters
2524 Parameters
2515 ----------
2525 ----------
2516 name : str
2526 name : str
2517 The name of the macro.
2527 The name of the macro.
2518 themacro : str or Macro
2528 themacro : str or Macro
2519 The action to do upon invoking the macro. If a string, a new
2529 The action to do upon invoking the macro. If a string, a new
2520 Macro object is created by passing the string to it.
2530 Macro object is created by passing the string to it.
2521 """
2531 """
2522
2532
2523 from IPython.core import macro
2533 from IPython.core import macro
2524
2534
2525 if isinstance(themacro, str):
2535 if isinstance(themacro, str):
2526 themacro = macro.Macro(themacro)
2536 themacro = macro.Macro(themacro)
2527 if not isinstance(themacro, macro.Macro):
2537 if not isinstance(themacro, macro.Macro):
2528 raise ValueError('A macro must be a string or a Macro instance.')
2538 raise ValueError('A macro must be a string or a Macro instance.')
2529 self.user_ns[name] = themacro
2539 self.user_ns[name] = themacro
2530
2540
2531 #-------------------------------------------------------------------------
2541 #-------------------------------------------------------------------------
2532 # Things related to the running of system commands
2542 # Things related to the running of system commands
2533 #-------------------------------------------------------------------------
2543 #-------------------------------------------------------------------------
2534
2544
2535 def system_piped(self, cmd):
2545 def system_piped(self, cmd):
2536 """Call the given cmd in a subprocess, piping stdout/err
2546 """Call the given cmd in a subprocess, piping stdout/err
2537
2547
2538 Parameters
2548 Parameters
2539 ----------
2549 ----------
2540 cmd : str
2550 cmd : str
2541 Command to execute (can not end in '&', as background processes are
2551 Command to execute (can not end in '&', as background processes are
2542 not supported. Should not be a command that expects input
2552 not supported. Should not be a command that expects input
2543 other than simple text.
2553 other than simple text.
2544 """
2554 """
2545 if cmd.rstrip().endswith('&'):
2555 if cmd.rstrip().endswith('&'):
2546 # this is *far* from a rigorous test
2556 # this is *far* from a rigorous test
2547 # We do not support backgrounding processes because we either use
2557 # We do not support backgrounding processes because we either use
2548 # pexpect or pipes to read from. Users can always just call
2558 # pexpect or pipes to read from. Users can always just call
2549 # os.system() or use ip.system=ip.system_raw
2559 # os.system() or use ip.system=ip.system_raw
2550 # if they really want a background process.
2560 # if they really want a background process.
2551 raise OSError("Background processes not supported.")
2561 raise OSError("Background processes not supported.")
2552
2562
2553 # we explicitly do NOT return the subprocess status code, because
2563 # we explicitly do NOT return the subprocess status code, because
2554 # a non-None value would trigger :func:`sys.displayhook` calls.
2564 # a non-None value would trigger :func:`sys.displayhook` calls.
2555 # Instead, we store the exit_code in user_ns.
2565 # Instead, we store the exit_code in user_ns.
2556 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2566 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2557
2567
2558 def system_raw(self, cmd):
2568 def system_raw(self, cmd):
2559 """Call the given cmd in a subprocess using os.system on Windows or
2569 """Call the given cmd in a subprocess using os.system on Windows or
2560 subprocess.call using the system shell on other platforms.
2570 subprocess.call using the system shell on other platforms.
2561
2571
2562 Parameters
2572 Parameters
2563 ----------
2573 ----------
2564 cmd : str
2574 cmd : str
2565 Command to execute.
2575 Command to execute.
2566 """
2576 """
2567 cmd = self.var_expand(cmd, depth=1)
2577 cmd = self.var_expand(cmd, depth=1)
2568 # protect os.system from UNC paths on Windows, which it can't handle:
2578 # protect os.system from UNC paths on Windows, which it can't handle:
2569 if sys.platform == 'win32':
2579 if sys.platform == 'win32':
2570 from IPython.utils._process_win32 import AvoidUNCPath
2580 from IPython.utils._process_win32 import AvoidUNCPath
2571 with AvoidUNCPath() as path:
2581 with AvoidUNCPath() as path:
2572 if path is not None:
2582 if path is not None:
2573 cmd = '"pushd %s &&"%s' % (path, cmd)
2583 cmd = '"pushd %s &&"%s' % (path, cmd)
2574 try:
2584 try:
2575 ec = os.system(cmd)
2585 ec = os.system(cmd)
2576 except KeyboardInterrupt:
2586 except KeyboardInterrupt:
2577 print('\n' + self.get_exception_only(), file=sys.stderr)
2587 print('\n' + self.get_exception_only(), file=sys.stderr)
2578 ec = -2
2588 ec = -2
2579 else:
2589 else:
2580 # For posix the result of the subprocess.call() below is an exit
2590 # For posix the result of the subprocess.call() below is an exit
2581 # code, which by convention is zero for success, positive for
2591 # code, which by convention is zero for success, positive for
2582 # program failure. Exit codes above 128 are reserved for signals,
2592 # program failure. Exit codes above 128 are reserved for signals,
2583 # and the formula for converting a signal to an exit code is usually
2593 # and the formula for converting a signal to an exit code is usually
2584 # signal_number+128. To more easily differentiate between exit
2594 # signal_number+128. To more easily differentiate between exit
2585 # codes and signals, ipython uses negative numbers. For instance
2595 # codes and signals, ipython uses negative numbers. For instance
2586 # since control-c is signal 2 but exit code 130, ipython's
2596 # since control-c is signal 2 but exit code 130, ipython's
2587 # _exit_code variable will read -2. Note that some shells like
2597 # _exit_code variable will read -2. Note that some shells like
2588 # csh and fish don't follow sh/bash conventions for exit codes.
2598 # csh and fish don't follow sh/bash conventions for exit codes.
2589 executable = os.environ.get('SHELL', None)
2599 executable = os.environ.get('SHELL', None)
2590 try:
2600 try:
2591 # Use env shell instead of default /bin/sh
2601 # Use env shell instead of default /bin/sh
2592 ec = subprocess.call(cmd, shell=True, executable=executable)
2602 ec = subprocess.call(cmd, shell=True, executable=executable)
2593 except KeyboardInterrupt:
2603 except KeyboardInterrupt:
2594 # intercept control-C; a long traceback is not useful here
2604 # intercept control-C; a long traceback is not useful here
2595 print('\n' + self.get_exception_only(), file=sys.stderr)
2605 print('\n' + self.get_exception_only(), file=sys.stderr)
2596 ec = 130
2606 ec = 130
2597 if ec > 128:
2607 if ec > 128:
2598 ec = -(ec - 128)
2608 ec = -(ec - 128)
2599
2609
2600 # We explicitly do NOT return the subprocess status code, because
2610 # We explicitly do NOT return the subprocess status code, because
2601 # a non-None value would trigger :func:`sys.displayhook` calls.
2611 # a non-None value would trigger :func:`sys.displayhook` calls.
2602 # Instead, we store the exit_code in user_ns. Note the semantics
2612 # Instead, we store the exit_code in user_ns. Note the semantics
2603 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2613 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2604 # but raising SystemExit(_exit_code) will give status 254!
2614 # but raising SystemExit(_exit_code) will give status 254!
2605 self.user_ns['_exit_code'] = ec
2615 self.user_ns['_exit_code'] = ec
2606
2616
2607 # use piped system by default, because it is better behaved
2617 # use piped system by default, because it is better behaved
2608 system = system_piped
2618 system = system_piped
2609
2619
2610 def getoutput(self, cmd, split=True, depth=0):
2620 def getoutput(self, cmd, split=True, depth=0):
2611 """Get output (possibly including stderr) from a subprocess.
2621 """Get output (possibly including stderr) from a subprocess.
2612
2622
2613 Parameters
2623 Parameters
2614 ----------
2624 ----------
2615 cmd : str
2625 cmd : str
2616 Command to execute (can not end in '&', as background processes are
2626 Command to execute (can not end in '&', as background processes are
2617 not supported.
2627 not supported.
2618 split : bool, optional
2628 split : bool, optional
2619 If True, split the output into an IPython SList. Otherwise, an
2629 If True, split the output into an IPython SList. Otherwise, an
2620 IPython LSString is returned. These are objects similar to normal
2630 IPython LSString is returned. These are objects similar to normal
2621 lists and strings, with a few convenience attributes for easier
2631 lists and strings, with a few convenience attributes for easier
2622 manipulation of line-based output. You can use '?' on them for
2632 manipulation of line-based output. You can use '?' on them for
2623 details.
2633 details.
2624 depth : int, optional
2634 depth : int, optional
2625 How many frames above the caller are the local variables which should
2635 How many frames above the caller are the local variables which should
2626 be expanded in the command string? The default (0) assumes that the
2636 be expanded in the command string? The default (0) assumes that the
2627 expansion variables are in the stack frame calling this function.
2637 expansion variables are in the stack frame calling this function.
2628 """
2638 """
2629 if cmd.rstrip().endswith('&'):
2639 if cmd.rstrip().endswith('&'):
2630 # this is *far* from a rigorous test
2640 # this is *far* from a rigorous test
2631 raise OSError("Background processes not supported.")
2641 raise OSError("Background processes not supported.")
2632 out = getoutput(self.var_expand(cmd, depth=depth+1))
2642 out = getoutput(self.var_expand(cmd, depth=depth+1))
2633 if split:
2643 if split:
2634 out = SList(out.splitlines())
2644 out = SList(out.splitlines())
2635 else:
2645 else:
2636 out = LSString(out)
2646 out = LSString(out)
2637 return out
2647 return out
2638
2648
2639 #-------------------------------------------------------------------------
2649 #-------------------------------------------------------------------------
2640 # Things related to aliases
2650 # Things related to aliases
2641 #-------------------------------------------------------------------------
2651 #-------------------------------------------------------------------------
2642
2652
2643 def init_alias(self):
2653 def init_alias(self):
2644 self.alias_manager = AliasManager(shell=self, parent=self)
2654 self.alias_manager = AliasManager(shell=self, parent=self)
2645 self.configurables.append(self.alias_manager)
2655 self.configurables.append(self.alias_manager)
2646
2656
2647 #-------------------------------------------------------------------------
2657 #-------------------------------------------------------------------------
2648 # Things related to extensions
2658 # Things related to extensions
2649 #-------------------------------------------------------------------------
2659 #-------------------------------------------------------------------------
2650
2660
2651 def init_extension_manager(self):
2661 def init_extension_manager(self):
2652 self.extension_manager = ExtensionManager(shell=self, parent=self)
2662 self.extension_manager = ExtensionManager(shell=self, parent=self)
2653 self.configurables.append(self.extension_manager)
2663 self.configurables.append(self.extension_manager)
2654
2664
2655 #-------------------------------------------------------------------------
2665 #-------------------------------------------------------------------------
2656 # Things related to payloads
2666 # Things related to payloads
2657 #-------------------------------------------------------------------------
2667 #-------------------------------------------------------------------------
2658
2668
2659 def init_payload(self):
2669 def init_payload(self):
2660 self.payload_manager = PayloadManager(parent=self)
2670 self.payload_manager = PayloadManager(parent=self)
2661 self.configurables.append(self.payload_manager)
2671 self.configurables.append(self.payload_manager)
2662
2672
2663 #-------------------------------------------------------------------------
2673 #-------------------------------------------------------------------------
2664 # Things related to the prefilter
2674 # Things related to the prefilter
2665 #-------------------------------------------------------------------------
2675 #-------------------------------------------------------------------------
2666
2676
2667 def init_prefilter(self):
2677 def init_prefilter(self):
2668 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2678 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2669 self.configurables.append(self.prefilter_manager)
2679 self.configurables.append(self.prefilter_manager)
2670 # Ultimately this will be refactored in the new interpreter code, but
2680 # Ultimately this will be refactored in the new interpreter code, but
2671 # for now, we should expose the main prefilter method (there's legacy
2681 # for now, we should expose the main prefilter method (there's legacy
2672 # code out there that may rely on this).
2682 # code out there that may rely on this).
2673 self.prefilter = self.prefilter_manager.prefilter_lines
2683 self.prefilter = self.prefilter_manager.prefilter_lines
2674
2684
2675 def auto_rewrite_input(self, cmd):
2685 def auto_rewrite_input(self, cmd):
2676 """Print to the screen the rewritten form of the user's command.
2686 """Print to the screen the rewritten form of the user's command.
2677
2687
2678 This shows visual feedback by rewriting input lines that cause
2688 This shows visual feedback by rewriting input lines that cause
2679 automatic calling to kick in, like::
2689 automatic calling to kick in, like::
2680
2690
2681 /f x
2691 /f x
2682
2692
2683 into::
2693 into::
2684
2694
2685 ------> f(x)
2695 ------> f(x)
2686
2696
2687 after the user's input prompt. This helps the user understand that the
2697 after the user's input prompt. This helps the user understand that the
2688 input line was transformed automatically by IPython.
2698 input line was transformed automatically by IPython.
2689 """
2699 """
2690 if not self.show_rewritten_input:
2700 if not self.show_rewritten_input:
2691 return
2701 return
2692
2702
2693 # This is overridden in TerminalInteractiveShell to use fancy prompts
2703 # This is overridden in TerminalInteractiveShell to use fancy prompts
2694 print("------> " + cmd)
2704 print("------> " + cmd)
2695
2705
2696 #-------------------------------------------------------------------------
2706 #-------------------------------------------------------------------------
2697 # Things related to extracting values/expressions from kernel and user_ns
2707 # Things related to extracting values/expressions from kernel and user_ns
2698 #-------------------------------------------------------------------------
2708 #-------------------------------------------------------------------------
2699
2709
2700 def _user_obj_error(self):
2710 def _user_obj_error(self):
2701 """return simple exception dict
2711 """return simple exception dict
2702
2712
2703 for use in user_expressions
2713 for use in user_expressions
2704 """
2714 """
2705
2715
2706 etype, evalue, tb = self._get_exc_info()
2716 etype, evalue, tb = self._get_exc_info()
2707 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2717 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2708
2718
2709 exc_info = {
2719 exc_info = {
2710 u'status' : 'error',
2720 u'status' : 'error',
2711 u'traceback' : stb,
2721 u'traceback' : stb,
2712 u'ename' : etype.__name__,
2722 u'ename' : etype.__name__,
2713 u'evalue' : py3compat.safe_unicode(evalue),
2723 u'evalue' : py3compat.safe_unicode(evalue),
2714 }
2724 }
2715
2725
2716 return exc_info
2726 return exc_info
2717
2727
2718 def _format_user_obj(self, obj):
2728 def _format_user_obj(self, obj):
2719 """format a user object to display dict
2729 """format a user object to display dict
2720
2730
2721 for use in user_expressions
2731 for use in user_expressions
2722 """
2732 """
2723
2733
2724 data, md = self.display_formatter.format(obj)
2734 data, md = self.display_formatter.format(obj)
2725 value = {
2735 value = {
2726 'status' : 'ok',
2736 'status' : 'ok',
2727 'data' : data,
2737 'data' : data,
2728 'metadata' : md,
2738 'metadata' : md,
2729 }
2739 }
2730 return value
2740 return value
2731
2741
2732 def user_expressions(self, expressions):
2742 def user_expressions(self, expressions):
2733 """Evaluate a dict of expressions in the user's namespace.
2743 """Evaluate a dict of expressions in the user's namespace.
2734
2744
2735 Parameters
2745 Parameters
2736 ----------
2746 ----------
2737 expressions : dict
2747 expressions : dict
2738 A dict with string keys and string values. The expression values
2748 A dict with string keys and string values. The expression values
2739 should be valid Python expressions, each of which will be evaluated
2749 should be valid Python expressions, each of which will be evaluated
2740 in the user namespace.
2750 in the user namespace.
2741
2751
2742 Returns
2752 Returns
2743 -------
2753 -------
2744 A dict, keyed like the input expressions dict, with the rich mime-typed
2754 A dict, keyed like the input expressions dict, with the rich mime-typed
2745 display_data of each value.
2755 display_data of each value.
2746 """
2756 """
2747 out = {}
2757 out = {}
2748 user_ns = self.user_ns
2758 user_ns = self.user_ns
2749 global_ns = self.user_global_ns
2759 global_ns = self.user_global_ns
2750
2760
2751 for key, expr in expressions.items():
2761 for key, expr in expressions.items():
2752 try:
2762 try:
2753 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2763 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2754 except:
2764 except:
2755 value = self._user_obj_error()
2765 value = self._user_obj_error()
2756 out[key] = value
2766 out[key] = value
2757 return out
2767 return out
2758
2768
2759 #-------------------------------------------------------------------------
2769 #-------------------------------------------------------------------------
2760 # Things related to the running of code
2770 # Things related to the running of code
2761 #-------------------------------------------------------------------------
2771 #-------------------------------------------------------------------------
2762
2772
2763 def ex(self, cmd):
2773 def ex(self, cmd):
2764 """Execute a normal python statement in user namespace."""
2774 """Execute a normal python statement in user namespace."""
2765 with self.builtin_trap:
2775 with self.builtin_trap:
2766 exec(cmd, self.user_global_ns, self.user_ns)
2776 exec(cmd, self.user_global_ns, self.user_ns)
2767
2777
2768 def ev(self, expr):
2778 def ev(self, expr):
2769 """Evaluate python expression expr in user namespace.
2779 """Evaluate python expression expr in user namespace.
2770
2780
2771 Returns the result of evaluation
2781 Returns the result of evaluation
2772 """
2782 """
2773 with self.builtin_trap:
2783 with self.builtin_trap:
2774 return eval(expr, self.user_global_ns, self.user_ns)
2784 return eval(expr, self.user_global_ns, self.user_ns)
2775
2785
2776 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2786 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2777 """A safe version of the builtin execfile().
2787 """A safe version of the builtin execfile().
2778
2788
2779 This version will never throw an exception, but instead print
2789 This version will never throw an exception, but instead print
2780 helpful error messages to the screen. This only works on pure
2790 helpful error messages to the screen. This only works on pure
2781 Python files with the .py extension.
2791 Python files with the .py extension.
2782
2792
2783 Parameters
2793 Parameters
2784 ----------
2794 ----------
2785 fname : string
2795 fname : string
2786 The name of the file to be executed.
2796 The name of the file to be executed.
2787 where : tuple
2797 where : tuple
2788 One or two namespaces, passed to execfile() as (globals,locals).
2798 One or two namespaces, passed to execfile() as (globals,locals).
2789 If only one is given, it is passed as both.
2799 If only one is given, it is passed as both.
2790 exit_ignore : bool (False)
2800 exit_ignore : bool (False)
2791 If True, then silence SystemExit for non-zero status (it is always
2801 If True, then silence SystemExit for non-zero status (it is always
2792 silenced for zero status, as it is so common).
2802 silenced for zero status, as it is so common).
2793 raise_exceptions : bool (False)
2803 raise_exceptions : bool (False)
2794 If True raise exceptions everywhere. Meant for testing.
2804 If True raise exceptions everywhere. Meant for testing.
2795 shell_futures : bool (False)
2805 shell_futures : bool (False)
2796 If True, the code will share future statements with the interactive
2806 If True, the code will share future statements with the interactive
2797 shell. It will both be affected by previous __future__ imports, and
2807 shell. It will both be affected by previous __future__ imports, and
2798 any __future__ imports in the code will affect the shell. If False,
2808 any __future__ imports in the code will affect the shell. If False,
2799 __future__ imports are not shared in either direction.
2809 __future__ imports are not shared in either direction.
2800
2810
2801 """
2811 """
2802 fname = os.path.abspath(os.path.expanduser(fname))
2812 fname = os.path.abspath(os.path.expanduser(fname))
2803
2813
2804 # Make sure we can open the file
2814 # Make sure we can open the file
2805 try:
2815 try:
2806 with open(fname):
2816 with open(fname):
2807 pass
2817 pass
2808 except:
2818 except:
2809 warn('Could not open file <%s> for safe execution.' % fname)
2819 warn('Could not open file <%s> for safe execution.' % fname)
2810 return
2820 return
2811
2821
2812 # Find things also in current directory. This is needed to mimic the
2822 # Find things also in current directory. This is needed to mimic the
2813 # behavior of running a script from the system command line, where
2823 # behavior of running a script from the system command line, where
2814 # Python inserts the script's directory into sys.path
2824 # Python inserts the script's directory into sys.path
2815 dname = os.path.dirname(fname)
2825 dname = os.path.dirname(fname)
2816
2826
2817 with prepended_to_syspath(dname), self.builtin_trap:
2827 with prepended_to_syspath(dname), self.builtin_trap:
2818 try:
2828 try:
2819 glob, loc = (where + (None, ))[:2]
2829 glob, loc = (where + (None, ))[:2]
2820 py3compat.execfile(
2830 py3compat.execfile(
2821 fname, glob, loc,
2831 fname, glob, loc,
2822 self.compile if shell_futures else None)
2832 self.compile if shell_futures else None)
2823 except SystemExit as status:
2833 except SystemExit as status:
2824 # If the call was made with 0 or None exit status (sys.exit(0)
2834 # If the call was made with 0 or None exit status (sys.exit(0)
2825 # or sys.exit() ), don't bother showing a traceback, as both of
2835 # or sys.exit() ), don't bother showing a traceback, as both of
2826 # these are considered normal by the OS:
2836 # these are considered normal by the OS:
2827 # > python -c'import sys;sys.exit(0)'; echo $?
2837 # > python -c'import sys;sys.exit(0)'; echo $?
2828 # 0
2838 # 0
2829 # > python -c'import sys;sys.exit()'; echo $?
2839 # > python -c'import sys;sys.exit()'; echo $?
2830 # 0
2840 # 0
2831 # For other exit status, we show the exception unless
2841 # For other exit status, we show the exception unless
2832 # explicitly silenced, but only in short form.
2842 # explicitly silenced, but only in short form.
2833 if status.code:
2843 if status.code:
2834 if raise_exceptions:
2844 if raise_exceptions:
2835 raise
2845 raise
2836 if not exit_ignore:
2846 if not exit_ignore:
2837 self.showtraceback(exception_only=True)
2847 self.showtraceback(exception_only=True)
2838 except:
2848 except:
2839 if raise_exceptions:
2849 if raise_exceptions:
2840 raise
2850 raise
2841 # tb offset is 2 because we wrap execfile
2851 # tb offset is 2 because we wrap execfile
2842 self.showtraceback(tb_offset=2)
2852 self.showtraceback(tb_offset=2)
2843
2853
2844 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2854 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2845 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2855 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2846
2856
2847 Parameters
2857 Parameters
2848 ----------
2858 ----------
2849 fname : str
2859 fname : str
2850 The name of the file to execute. The filename must have a
2860 The name of the file to execute. The filename must have a
2851 .ipy or .ipynb extension.
2861 .ipy or .ipynb extension.
2852 shell_futures : bool (False)
2862 shell_futures : bool (False)
2853 If True, the code will share future statements with the interactive
2863 If True, the code will share future statements with the interactive
2854 shell. It will both be affected by previous __future__ imports, and
2864 shell. It will both be affected by previous __future__ imports, and
2855 any __future__ imports in the code will affect the shell. If False,
2865 any __future__ imports in the code will affect the shell. If False,
2856 __future__ imports are not shared in either direction.
2866 __future__ imports are not shared in either direction.
2857 raise_exceptions : bool (False)
2867 raise_exceptions : bool (False)
2858 If True raise exceptions everywhere. Meant for testing.
2868 If True raise exceptions everywhere. Meant for testing.
2859 """
2869 """
2860 fname = os.path.abspath(os.path.expanduser(fname))
2870 fname = os.path.abspath(os.path.expanduser(fname))
2861
2871
2862 # Make sure we can open the file
2872 # Make sure we can open the file
2863 try:
2873 try:
2864 with open(fname):
2874 with open(fname):
2865 pass
2875 pass
2866 except:
2876 except:
2867 warn('Could not open file <%s> for safe execution.' % fname)
2877 warn('Could not open file <%s> for safe execution.' % fname)
2868 return
2878 return
2869
2879
2870 # Find things also in current directory. This is needed to mimic the
2880 # Find things also in current directory. This is needed to mimic the
2871 # behavior of running a script from the system command line, where
2881 # behavior of running a script from the system command line, where
2872 # Python inserts the script's directory into sys.path
2882 # Python inserts the script's directory into sys.path
2873 dname = os.path.dirname(fname)
2883 dname = os.path.dirname(fname)
2874
2884
2875 def get_cells():
2885 def get_cells():
2876 """generator for sequence of code blocks to run"""
2886 """generator for sequence of code blocks to run"""
2877 if fname.endswith('.ipynb'):
2887 if fname.endswith('.ipynb'):
2878 from nbformat import read
2888 from nbformat import read
2879 nb = read(fname, as_version=4)
2889 nb = read(fname, as_version=4)
2880 if not nb.cells:
2890 if not nb.cells:
2881 return
2891 return
2882 for cell in nb.cells:
2892 for cell in nb.cells:
2883 if cell.cell_type == 'code':
2893 if cell.cell_type == 'code':
2884 yield cell.source
2894 yield cell.source
2885 else:
2895 else:
2886 with open(fname) as f:
2896 with open(fname) as f:
2887 yield f.read()
2897 yield f.read()
2888
2898
2889 with prepended_to_syspath(dname):
2899 with prepended_to_syspath(dname):
2890 try:
2900 try:
2891 for cell in get_cells():
2901 for cell in get_cells():
2892 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2902 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2893 if raise_exceptions:
2903 if raise_exceptions:
2894 result.raise_error()
2904 result.raise_error()
2895 elif not result.success:
2905 elif not result.success:
2896 break
2906 break
2897 except:
2907 except:
2898 if raise_exceptions:
2908 if raise_exceptions:
2899 raise
2909 raise
2900 self.showtraceback()
2910 self.showtraceback()
2901 warn('Unknown failure executing file: <%s>' % fname)
2911 warn('Unknown failure executing file: <%s>' % fname)
2902
2912
2903 def safe_run_module(self, mod_name, where):
2913 def safe_run_module(self, mod_name, where):
2904 """A safe version of runpy.run_module().
2914 """A safe version of runpy.run_module().
2905
2915
2906 This version will never throw an exception, but instead print
2916 This version will never throw an exception, but instead print
2907 helpful error messages to the screen.
2917 helpful error messages to the screen.
2908
2918
2909 `SystemExit` exceptions with status code 0 or None are ignored.
2919 `SystemExit` exceptions with status code 0 or None are ignored.
2910
2920
2911 Parameters
2921 Parameters
2912 ----------
2922 ----------
2913 mod_name : string
2923 mod_name : string
2914 The name of the module to be executed.
2924 The name of the module to be executed.
2915 where : dict
2925 where : dict
2916 The globals namespace.
2926 The globals namespace.
2917 """
2927 """
2918 try:
2928 try:
2919 try:
2929 try:
2920 where.update(
2930 where.update(
2921 runpy.run_module(str(mod_name), run_name="__main__",
2931 runpy.run_module(str(mod_name), run_name="__main__",
2922 alter_sys=True)
2932 alter_sys=True)
2923 )
2933 )
2924 except SystemExit as status:
2934 except SystemExit as status:
2925 if status.code:
2935 if status.code:
2926 raise
2936 raise
2927 except:
2937 except:
2928 self.showtraceback()
2938 self.showtraceback()
2929 warn('Unknown failure executing module: <%s>' % mod_name)
2939 warn('Unknown failure executing module: <%s>' % mod_name)
2930
2940
2931 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2941 def run_cell(
2942 self,
2943 raw_cell,
2944 store_history=False,
2945 silent=False,
2946 shell_futures=True,
2947 cell_id=None,
2948 ):
2932 """Run a complete IPython cell.
2949 """Run a complete IPython cell.
2933
2950
2934 Parameters
2951 Parameters
2935 ----------
2952 ----------
2936 raw_cell : str
2953 raw_cell : str
2937 The code (including IPython code such as %magic functions) to run.
2954 The code (including IPython code such as %magic functions) to run.
2938 store_history : bool
2955 store_history : bool
2939 If True, the raw and translated cell will be stored in IPython's
2956 If True, the raw and translated cell will be stored in IPython's
2940 history. For user code calling back into IPython's machinery, this
2957 history. For user code calling back into IPython's machinery, this
2941 should be set to False.
2958 should be set to False.
2942 silent : bool
2959 silent : bool
2943 If True, avoid side-effects, such as implicit displayhooks and
2960 If True, avoid side-effects, such as implicit displayhooks and
2944 and logging. silent=True forces store_history=False.
2961 and logging. silent=True forces store_history=False.
2945 shell_futures : bool
2962 shell_futures : bool
2946 If True, the code will share future statements with the interactive
2963 If True, the code will share future statements with the interactive
2947 shell. It will both be affected by previous __future__ imports, and
2964 shell. It will both be affected by previous __future__ imports, and
2948 any __future__ imports in the code will affect the shell. If False,
2965 any __future__ imports in the code will affect the shell. If False,
2949 __future__ imports are not shared in either direction.
2966 __future__ imports are not shared in either direction.
2950
2967
2951 Returns
2968 Returns
2952 -------
2969 -------
2953 result : :class:`ExecutionResult`
2970 result : :class:`ExecutionResult`
2954 """
2971 """
2955 result = None
2972 result = None
2956 try:
2973 try:
2957 result = self._run_cell(
2974 result = self._run_cell(
2958 raw_cell, store_history, silent, shell_futures)
2975 raw_cell, store_history, silent, shell_futures, cell_id
2976 )
2959 finally:
2977 finally:
2960 self.events.trigger('post_execute')
2978 self.events.trigger('post_execute')
2961 if not silent:
2979 if not silent:
2962 self.events.trigger('post_run_cell', result)
2980 self.events.trigger('post_run_cell', result)
2963 return result
2981 return result
2964
2982
2965 def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool):
2983 def _run_cell(
2984 self,
2985 raw_cell: str,
2986 store_history: bool,
2987 silent: bool,
2988 shell_futures: bool,
2989 cell_id: str,
2990 ) -> ExecutionResult:
2966 """Internal method to run a complete IPython cell."""
2991 """Internal method to run a complete IPython cell."""
2967
2992
2968 # we need to avoid calling self.transform_cell multiple time on the same thing
2993 # we need to avoid calling self.transform_cell multiple time on the same thing
2969 # so we need to store some results:
2994 # so we need to store some results:
2970 preprocessing_exc_tuple = None
2995 preprocessing_exc_tuple = None
2971 try:
2996 try:
2972 transformed_cell = self.transform_cell(raw_cell)
2997 transformed_cell = self.transform_cell(raw_cell)
2973 except Exception:
2998 except Exception:
2974 transformed_cell = raw_cell
2999 transformed_cell = raw_cell
2975 preprocessing_exc_tuple = sys.exc_info()
3000 preprocessing_exc_tuple = sys.exc_info()
2976
3001
2977 assert transformed_cell is not None
3002 assert transformed_cell is not None
2978 coro = self.run_cell_async(
3003 coro = self.run_cell_async(
2979 raw_cell,
3004 raw_cell,
2980 store_history=store_history,
3005 store_history=store_history,
2981 silent=silent,
3006 silent=silent,
2982 shell_futures=shell_futures,
3007 shell_futures=shell_futures,
2983 transformed_cell=transformed_cell,
3008 transformed_cell=transformed_cell,
2984 preprocessing_exc_tuple=preprocessing_exc_tuple,
3009 preprocessing_exc_tuple=preprocessing_exc_tuple,
3010 cell_id=cell_id,
2985 )
3011 )
2986
3012
2987 # run_cell_async is async, but may not actually need an eventloop.
3013 # run_cell_async is async, but may not actually need an eventloop.
2988 # when this is the case, we want to run it using the pseudo_sync_runner
3014 # when this is the case, we want to run it using the pseudo_sync_runner
2989 # so that code can invoke eventloops (for example via the %run , and
3015 # so that code can invoke eventloops (for example via the %run , and
2990 # `%paste` magic.
3016 # `%paste` magic.
2991 if self.trio_runner:
3017 if self.trio_runner:
2992 runner = self.trio_runner
3018 runner = self.trio_runner
2993 elif self.should_run_async(
3019 elif self.should_run_async(
2994 raw_cell,
3020 raw_cell,
2995 transformed_cell=transformed_cell,
3021 transformed_cell=transformed_cell,
2996 preprocessing_exc_tuple=preprocessing_exc_tuple,
3022 preprocessing_exc_tuple=preprocessing_exc_tuple,
2997 ):
3023 ):
2998 runner = self.loop_runner
3024 runner = self.loop_runner
2999 else:
3025 else:
3000 runner = _pseudo_sync_runner
3026 runner = _pseudo_sync_runner
3001
3027
3002 try:
3028 try:
3003 return runner(coro)
3029 return runner(coro)
3004 except BaseException as e:
3030 except BaseException as e:
3005 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
3031 info = ExecutionInfo(
3032 raw_cell, store_history, silent, shell_futures, cell_id
3033 )
3006 result = ExecutionResult(info)
3034 result = ExecutionResult(info)
3007 result.error_in_exec = e
3035 result.error_in_exec = e
3008 self.showtraceback(running_compiled_code=True)
3036 self.showtraceback(running_compiled_code=True)
3009 return result
3037 return result
3010 return
3038 return
3011
3039
3012 def should_run_async(
3040 def should_run_async(
3013 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
3041 self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
3014 ) -> bool:
3042 ) -> bool:
3015 """Return whether a cell should be run asynchronously via a coroutine runner
3043 """Return whether a cell should be run asynchronously via a coroutine runner
3016
3044
3017 Parameters
3045 Parameters
3018 ----------
3046 ----------
3019 raw_cell: str
3047 raw_cell: str
3020 The code to be executed
3048 The code to be executed
3021
3049
3022 Returns
3050 Returns
3023 -------
3051 -------
3024 result: bool
3052 result: bool
3025 Whether the code needs to be run with a coroutine runner or not
3053 Whether the code needs to be run with a coroutine runner or not
3026
3054
3027 .. versionadded:: 7.0
3055 .. versionadded:: 7.0
3028 """
3056 """
3029 if not self.autoawait:
3057 if not self.autoawait:
3030 return False
3058 return False
3031 if preprocessing_exc_tuple is not None:
3059 if preprocessing_exc_tuple is not None:
3032 return False
3060 return False
3033 assert preprocessing_exc_tuple is None
3061 assert preprocessing_exc_tuple is None
3034 if transformed_cell is None:
3062 if transformed_cell is None:
3035 warnings.warn(
3063 warnings.warn(
3036 "`should_run_async` will not call `transform_cell`"
3064 "`should_run_async` will not call `transform_cell`"
3037 " automatically in the future. Please pass the result to"
3065 " automatically in the future. Please pass the result to"
3038 " `transformed_cell` argument and any exception that happen"
3066 " `transformed_cell` argument and any exception that happen"
3039 " during the"
3067 " during the"
3040 "transform in `preprocessing_exc_tuple` in"
3068 "transform in `preprocessing_exc_tuple` in"
3041 " IPython 7.17 and above.",
3069 " IPython 7.17 and above.",
3042 DeprecationWarning,
3070 DeprecationWarning,
3043 stacklevel=2,
3071 stacklevel=2,
3044 )
3072 )
3045 try:
3073 try:
3046 cell = self.transform_cell(raw_cell)
3074 cell = self.transform_cell(raw_cell)
3047 except Exception:
3075 except Exception:
3048 # any exception during transform will be raised
3076 # any exception during transform will be raised
3049 # prior to execution
3077 # prior to execution
3050 return False
3078 return False
3051 else:
3079 else:
3052 cell = transformed_cell
3080 cell = transformed_cell
3053 return _should_be_async(cell)
3081 return _should_be_async(cell)
3054
3082
3055 async def run_cell_async(
3083 async def run_cell_async(
3056 self,
3084 self,
3057 raw_cell: str,
3085 raw_cell: str,
3058 store_history=False,
3086 store_history=False,
3059 silent=False,
3087 silent=False,
3060 shell_futures=True,
3088 shell_futures=True,
3061 *,
3089 *,
3062 transformed_cell: Optional[str] = None,
3090 transformed_cell: Optional[str] = None,
3063 preprocessing_exc_tuple: Optional[Any] = None
3091 preprocessing_exc_tuple: Optional[Any] = None,
3092 cell_id=None,
3064 ) -> ExecutionResult:
3093 ) -> ExecutionResult:
3065 """Run a complete IPython cell asynchronously.
3094 """Run a complete IPython cell asynchronously.
3066
3095
3067 Parameters
3096 Parameters
3068 ----------
3097 ----------
3069 raw_cell : str
3098 raw_cell : str
3070 The code (including IPython code such as %magic functions) to run.
3099 The code (including IPython code such as %magic functions) to run.
3071 store_history : bool
3100 store_history : bool
3072 If True, the raw and translated cell will be stored in IPython's
3101 If True, the raw and translated cell will be stored in IPython's
3073 history. For user code calling back into IPython's machinery, this
3102 history. For user code calling back into IPython's machinery, this
3074 should be set to False.
3103 should be set to False.
3075 silent : bool
3104 silent : bool
3076 If True, avoid side-effects, such as implicit displayhooks and
3105 If True, avoid side-effects, such as implicit displayhooks and
3077 and logging. silent=True forces store_history=False.
3106 and logging. silent=True forces store_history=False.
3078 shell_futures : bool
3107 shell_futures : bool
3079 If True, the code will share future statements with the interactive
3108 If True, the code will share future statements with the interactive
3080 shell. It will both be affected by previous __future__ imports, and
3109 shell. It will both be affected by previous __future__ imports, and
3081 any __future__ imports in the code will affect the shell. If False,
3110 any __future__ imports in the code will affect the shell. If False,
3082 __future__ imports are not shared in either direction.
3111 __future__ imports are not shared in either direction.
3083 transformed_cell: str
3112 transformed_cell: str
3084 cell that was passed through transformers
3113 cell that was passed through transformers
3085 preprocessing_exc_tuple:
3114 preprocessing_exc_tuple:
3086 trace if the transformation failed.
3115 trace if the transformation failed.
3087
3116
3088 Returns
3117 Returns
3089 -------
3118 -------
3090 result : :class:`ExecutionResult`
3119 result : :class:`ExecutionResult`
3091
3120
3092 .. versionadded:: 7.0
3121 .. versionadded:: 7.0
3093 """
3122 """
3094 info = ExecutionInfo(
3123 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures, cell_id)
3095 raw_cell, store_history, silent, shell_futures)
3096 result = ExecutionResult(info)
3124 result = ExecutionResult(info)
3097
3125
3098 if (not raw_cell) or raw_cell.isspace():
3126 if (not raw_cell) or raw_cell.isspace():
3099 self.last_execution_succeeded = True
3127 self.last_execution_succeeded = True
3100 self.last_execution_result = result
3128 self.last_execution_result = result
3101 return result
3129 return result
3102
3130
3103 if silent:
3131 if silent:
3104 store_history = False
3132 store_history = False
3105
3133
3106 if store_history:
3134 if store_history:
3107 result.execution_count = self.execution_count
3135 result.execution_count = self.execution_count
3108
3136
3109 def error_before_exec(value):
3137 def error_before_exec(value):
3110 if store_history:
3138 if store_history:
3111 self.execution_count += 1
3139 self.execution_count += 1
3112 result.error_before_exec = value
3140 result.error_before_exec = value
3113 self.last_execution_succeeded = False
3141 self.last_execution_succeeded = False
3114 self.last_execution_result = result
3142 self.last_execution_result = result
3115 return result
3143 return result
3116
3144
3117 self.events.trigger('pre_execute')
3145 self.events.trigger('pre_execute')
3118 if not silent:
3146 if not silent:
3119 self.events.trigger('pre_run_cell', info)
3147 self.events.trigger('pre_run_cell', info)
3120
3148
3121 if transformed_cell is None:
3149 if transformed_cell is None:
3122 warnings.warn(
3150 warnings.warn(
3123 "`run_cell_async` will not call `transform_cell`"
3151 "`run_cell_async` will not call `transform_cell`"
3124 " automatically in the future. Please pass the result to"
3152 " automatically in the future. Please pass the result to"
3125 " `transformed_cell` argument and any exception that happen"
3153 " `transformed_cell` argument and any exception that happen"
3126 " during the"
3154 " during the"
3127 "transform in `preprocessing_exc_tuple` in"
3155 "transform in `preprocessing_exc_tuple` in"
3128 " IPython 7.17 and above.",
3156 " IPython 7.17 and above.",
3129 DeprecationWarning,
3157 DeprecationWarning,
3130 stacklevel=2,
3158 stacklevel=2,
3131 )
3159 )
3132 # If any of our input transformation (input_transformer_manager or
3160 # If any of our input transformation (input_transformer_manager or
3133 # prefilter_manager) raises an exception, we store it in this variable
3161 # prefilter_manager) raises an exception, we store it in this variable
3134 # so that we can display the error after logging the input and storing
3162 # so that we can display the error after logging the input and storing
3135 # it in the history.
3163 # it in the history.
3136 try:
3164 try:
3137 cell = self.transform_cell(raw_cell)
3165 cell = self.transform_cell(raw_cell)
3138 except Exception:
3166 except Exception:
3139 preprocessing_exc_tuple = sys.exc_info()
3167 preprocessing_exc_tuple = sys.exc_info()
3140 cell = raw_cell # cell has to exist so it can be stored/logged
3168 cell = raw_cell # cell has to exist so it can be stored/logged
3141 else:
3169 else:
3142 preprocessing_exc_tuple = None
3170 preprocessing_exc_tuple = None
3143 else:
3171 else:
3144 if preprocessing_exc_tuple is None:
3172 if preprocessing_exc_tuple is None:
3145 cell = transformed_cell
3173 cell = transformed_cell
3146 else:
3174 else:
3147 cell = raw_cell
3175 cell = raw_cell
3148
3176
3149 # Store raw and processed history
3177 # Store raw and processed history
3150 if store_history:
3178 if store_history:
3151 self.history_manager.store_inputs(self.execution_count,
3179 self.history_manager.store_inputs(self.execution_count,
3152 cell, raw_cell)
3180 cell, raw_cell)
3153 if not silent:
3181 if not silent:
3154 self.logger.log(cell, raw_cell)
3182 self.logger.log(cell, raw_cell)
3155
3183
3156 # Display the exception if input processing failed.
3184 # Display the exception if input processing failed.
3157 if preprocessing_exc_tuple is not None:
3185 if preprocessing_exc_tuple is not None:
3158 self.showtraceback(preprocessing_exc_tuple)
3186 self.showtraceback(preprocessing_exc_tuple)
3159 if store_history:
3187 if store_history:
3160 self.execution_count += 1
3188 self.execution_count += 1
3161 return error_before_exec(preprocessing_exc_tuple[1])
3189 return error_before_exec(preprocessing_exc_tuple[1])
3162
3190
3163 # Our own compiler remembers the __future__ environment. If we want to
3191 # Our own compiler remembers the __future__ environment. If we want to
3164 # run code with a separate __future__ environment, use the default
3192 # run code with a separate __future__ environment, use the default
3165 # compiler
3193 # compiler
3166 compiler = self.compile if shell_futures else self.compiler_class()
3194 compiler = self.compile if shell_futures else self.compiler_class()
3167
3195
3168 _run_async = False
3196 _run_async = False
3169
3197
3170 with self.builtin_trap:
3198 with self.builtin_trap:
3171 cell_name = self.compile.cache(
3199 cell_name = self.compile.cache(
3172 cell, self.execution_count, raw_code=raw_cell
3200 cell, self.execution_count, raw_code=raw_cell
3173 )
3201 )
3174
3202
3175 with self.display_trap:
3203 with self.display_trap:
3176 # Compile to bytecode
3204 # Compile to bytecode
3177 try:
3205 try:
3178 if sys.version_info < (3,8) and self.autoawait:
3206 if sys.version_info < (3,8) and self.autoawait:
3179 if _should_be_async(cell):
3207 if _should_be_async(cell):
3180 # the code AST below will not be user code: we wrap it
3208 # the code AST below will not be user code: we wrap it
3181 # in an `async def`. This will likely make some AST
3209 # in an `async def`. This will likely make some AST
3182 # transformer below miss some transform opportunity and
3210 # transformer below miss some transform opportunity and
3183 # introduce a small coupling to run_code (in which we
3211 # introduce a small coupling to run_code (in which we
3184 # bake some assumptions of what _ast_asyncify returns.
3212 # bake some assumptions of what _ast_asyncify returns.
3185 # they are ways around (like grafting part of the ast
3213 # they are ways around (like grafting part of the ast
3186 # later:
3214 # later:
3187 # - Here, return code_ast.body[0].body[1:-1], as well
3215 # - Here, return code_ast.body[0].body[1:-1], as well
3188 # as last expression in return statement which is
3216 # as last expression in return statement which is
3189 # the user code part.
3217 # the user code part.
3190 # - Let it go through the AST transformers, and graft
3218 # - Let it go through the AST transformers, and graft
3191 # - it back after the AST transform
3219 # - it back after the AST transform
3192 # But that seem unreasonable, at least while we
3220 # But that seem unreasonable, at least while we
3193 # do not need it.
3221 # do not need it.
3194 code_ast = _ast_asyncify(cell, 'async-def-wrapper')
3222 code_ast = _ast_asyncify(cell, 'async-def-wrapper')
3195 _run_async = True
3223 _run_async = True
3196 else:
3224 else:
3197 code_ast = compiler.ast_parse(cell, filename=cell_name)
3225 code_ast = compiler.ast_parse(cell, filename=cell_name)
3198 else:
3226 else:
3199 code_ast = compiler.ast_parse(cell, filename=cell_name)
3227 code_ast = compiler.ast_parse(cell, filename=cell_name)
3200 except self.custom_exceptions as e:
3228 except self.custom_exceptions as e:
3201 etype, value, tb = sys.exc_info()
3229 etype, value, tb = sys.exc_info()
3202 self.CustomTB(etype, value, tb)
3230 self.CustomTB(etype, value, tb)
3203 return error_before_exec(e)
3231 return error_before_exec(e)
3204 except IndentationError as e:
3232 except IndentationError as e:
3205 self.showindentationerror()
3233 self.showindentationerror()
3206 return error_before_exec(e)
3234 return error_before_exec(e)
3207 except (OverflowError, SyntaxError, ValueError, TypeError,
3235 except (OverflowError, SyntaxError, ValueError, TypeError,
3208 MemoryError) as e:
3236 MemoryError) as e:
3209 self.showsyntaxerror()
3237 self.showsyntaxerror()
3210 return error_before_exec(e)
3238 return error_before_exec(e)
3211
3239
3212 # Apply AST transformations
3240 # Apply AST transformations
3213 try:
3241 try:
3214 code_ast = self.transform_ast(code_ast)
3242 code_ast = self.transform_ast(code_ast)
3215 except InputRejected as e:
3243 except InputRejected as e:
3216 self.showtraceback()
3244 self.showtraceback()
3217 return error_before_exec(e)
3245 return error_before_exec(e)
3218
3246
3219 # Give the displayhook a reference to our ExecutionResult so it
3247 # Give the displayhook a reference to our ExecutionResult so it
3220 # can fill in the output value.
3248 # can fill in the output value.
3221 self.displayhook.exec_result = result
3249 self.displayhook.exec_result = result
3222
3250
3223 # Execute the user code
3251 # Execute the user code
3224 interactivity = "none" if silent else self.ast_node_interactivity
3252 interactivity = "none" if silent else self.ast_node_interactivity
3225 if _run_async:
3253 if _run_async:
3226 interactivity = 'async'
3254 interactivity = 'async'
3227
3255
3228 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3256 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
3229 interactivity=interactivity, compiler=compiler, result=result)
3257 interactivity=interactivity, compiler=compiler, result=result)
3230
3258
3231 self.last_execution_succeeded = not has_raised
3259 self.last_execution_succeeded = not has_raised
3232 self.last_execution_result = result
3260 self.last_execution_result = result
3233
3261
3234 # Reset this so later displayed values do not modify the
3262 # Reset this so later displayed values do not modify the
3235 # ExecutionResult
3263 # ExecutionResult
3236 self.displayhook.exec_result = None
3264 self.displayhook.exec_result = None
3237
3265
3238 if store_history:
3266 if store_history:
3239 # Write output to the database. Does nothing unless
3267 # Write output to the database. Does nothing unless
3240 # history output logging is enabled.
3268 # history output logging is enabled.
3241 self.history_manager.store_output(self.execution_count)
3269 self.history_manager.store_output(self.execution_count)
3242 # Each cell is a *single* input, regardless of how many lines it has
3270 # Each cell is a *single* input, regardless of how many lines it has
3243 self.execution_count += 1
3271 self.execution_count += 1
3244
3272
3245 return result
3273 return result
3246
3274
3247 def transform_cell(self, raw_cell):
3275 def transform_cell(self, raw_cell):
3248 """Transform an input cell before parsing it.
3276 """Transform an input cell before parsing it.
3249
3277
3250 Static transformations, implemented in IPython.core.inputtransformer2,
3278 Static transformations, implemented in IPython.core.inputtransformer2,
3251 deal with things like ``%magic`` and ``!system`` commands.
3279 deal with things like ``%magic`` and ``!system`` commands.
3252 These run on all input.
3280 These run on all input.
3253 Dynamic transformations, for things like unescaped magics and the exit
3281 Dynamic transformations, for things like unescaped magics and the exit
3254 autocall, depend on the state of the interpreter.
3282 autocall, depend on the state of the interpreter.
3255 These only apply to single line inputs.
3283 These only apply to single line inputs.
3256
3284
3257 These string-based transformations are followed by AST transformations;
3285 These string-based transformations are followed by AST transformations;
3258 see :meth:`transform_ast`.
3286 see :meth:`transform_ast`.
3259 """
3287 """
3260 # Static input transformations
3288 # Static input transformations
3261 cell = self.input_transformer_manager.transform_cell(raw_cell)
3289 cell = self.input_transformer_manager.transform_cell(raw_cell)
3262
3290
3263 if len(cell.splitlines()) == 1:
3291 if len(cell.splitlines()) == 1:
3264 # Dynamic transformations - only applied for single line commands
3292 # Dynamic transformations - only applied for single line commands
3265 with self.builtin_trap:
3293 with self.builtin_trap:
3266 # use prefilter_lines to handle trailing newlines
3294 # use prefilter_lines to handle trailing newlines
3267 # restore trailing newline for ast.parse
3295 # restore trailing newline for ast.parse
3268 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3296 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
3269
3297
3270 lines = cell.splitlines(keepends=True)
3298 lines = cell.splitlines(keepends=True)
3271 for transform in self.input_transformers_post:
3299 for transform in self.input_transformers_post:
3272 lines = transform(lines)
3300 lines = transform(lines)
3273 cell = ''.join(lines)
3301 cell = ''.join(lines)
3274
3302
3275 return cell
3303 return cell
3276
3304
3277 def transform_ast(self, node):
3305 def transform_ast(self, node):
3278 """Apply the AST transformations from self.ast_transformers
3306 """Apply the AST transformations from self.ast_transformers
3279
3307
3280 Parameters
3308 Parameters
3281 ----------
3309 ----------
3282 node : ast.Node
3310 node : ast.Node
3283 The root node to be transformed. Typically called with the ast.Module
3311 The root node to be transformed. Typically called with the ast.Module
3284 produced by parsing user input.
3312 produced by parsing user input.
3285
3313
3286 Returns
3314 Returns
3287 -------
3315 -------
3288 An ast.Node corresponding to the node it was called with. Note that it
3316 An ast.Node corresponding to the node it was called with. Note that it
3289 may also modify the passed object, so don't rely on references to the
3317 may also modify the passed object, so don't rely on references to the
3290 original AST.
3318 original AST.
3291 """
3319 """
3292 for transformer in self.ast_transformers:
3320 for transformer in self.ast_transformers:
3293 try:
3321 try:
3294 node = transformer.visit(node)
3322 node = transformer.visit(node)
3295 except InputRejected:
3323 except InputRejected:
3296 # User-supplied AST transformers can reject an input by raising
3324 # User-supplied AST transformers can reject an input by raising
3297 # an InputRejected. Short-circuit in this case so that we
3325 # an InputRejected. Short-circuit in this case so that we
3298 # don't unregister the transform.
3326 # don't unregister the transform.
3299 raise
3327 raise
3300 except Exception:
3328 except Exception:
3301 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3329 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
3302 self.ast_transformers.remove(transformer)
3330 self.ast_transformers.remove(transformer)
3303
3331
3304 if self.ast_transformers:
3332 if self.ast_transformers:
3305 ast.fix_missing_locations(node)
3333 ast.fix_missing_locations(node)
3306 return node
3334 return node
3307
3335
3308 def _update_code_co_name(self, code):
3336 def _update_code_co_name(self, code):
3309 """Python 3.10 changed the behaviour so that whenever a code object
3337 """Python 3.10 changed the behaviour so that whenever a code object
3310 is assembled in the compile(ast) the co_firstlineno would be == 1.
3338 is assembled in the compile(ast) the co_firstlineno would be == 1.
3311
3339
3312 This makes pydevd/debugpy think that all cells invoked are the same
3340 This makes pydevd/debugpy think that all cells invoked are the same
3313 since it caches information based on (co_firstlineno, co_name, co_filename).
3341 since it caches information based on (co_firstlineno, co_name, co_filename).
3314
3342
3315 Given that, this function changes the code 'co_name' to be unique
3343 Given that, this function changes the code 'co_name' to be unique
3316 based on the first real lineno of the code (which also has a nice
3344 based on the first real lineno of the code (which also has a nice
3317 side effect of customizing the name so that it's not always <module>).
3345 side effect of customizing the name so that it's not always <module>).
3318
3346
3319 See: https://github.com/ipython/ipykernel/issues/841
3347 See: https://github.com/ipython/ipykernel/issues/841
3320 """
3348 """
3321 if not hasattr(code, "replace"):
3349 if not hasattr(code, "replace"):
3322 # It may not be available on older versions of Python (only
3350 # It may not be available on older versions of Python (only
3323 # available for 3.8 onwards).
3351 # available for 3.8 onwards).
3324 return code
3352 return code
3325 try:
3353 try:
3326 first_real_line = next(dis.findlinestarts(code))[1]
3354 first_real_line = next(dis.findlinestarts(code))[1]
3327 except StopIteration:
3355 except StopIteration:
3328 return code
3356 return code
3329 return code.replace(co_name="<cell line: %s>" % (first_real_line,))
3357 return code.replace(co_name="<cell line: %s>" % (first_real_line,))
3330
3358
3331 async def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
3359 async def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
3332 compiler=compile, result=None):
3360 compiler=compile, result=None):
3333 """Run a sequence of AST nodes. The execution mode depends on the
3361 """Run a sequence of AST nodes. The execution mode depends on the
3334 interactivity parameter.
3362 interactivity parameter.
3335
3363
3336 Parameters
3364 Parameters
3337 ----------
3365 ----------
3338 nodelist : list
3366 nodelist : list
3339 A sequence of AST nodes to run.
3367 A sequence of AST nodes to run.
3340 cell_name : str
3368 cell_name : str
3341 Will be passed to the compiler as the filename of the cell. Typically
3369 Will be passed to the compiler as the filename of the cell. Typically
3342 the value returned by ip.compile.cache(cell).
3370 the value returned by ip.compile.cache(cell).
3343 interactivity : str
3371 interactivity : str
3344 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3372 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
3345 specifying which nodes should be run interactively (displaying output
3373 specifying which nodes should be run interactively (displaying output
3346 from expressions). 'last_expr' will run the last node interactively
3374 from expressions). 'last_expr' will run the last node interactively
3347 only if it is an expression (i.e. expressions in loops or other blocks
3375 only if it is an expression (i.e. expressions in loops or other blocks
3348 are not displayed) 'last_expr_or_assign' will run the last expression
3376 are not displayed) 'last_expr_or_assign' will run the last expression
3349 or the last assignment. Other values for this parameter will raise a
3377 or the last assignment. Other values for this parameter will raise a
3350 ValueError.
3378 ValueError.
3351
3379
3352 Experimental value: 'async' Will try to run top level interactive
3380 Experimental value: 'async' Will try to run top level interactive
3353 async/await code in default runner, this will not respect the
3381 async/await code in default runner, this will not respect the
3354 interactivity setting and will only run the last node if it is an
3382 interactivity setting and will only run the last node if it is an
3355 expression.
3383 expression.
3356
3384
3357 compiler : callable
3385 compiler : callable
3358 A function with the same interface as the built-in compile(), to turn
3386 A function with the same interface as the built-in compile(), to turn
3359 the AST nodes into code objects. Default is the built-in compile().
3387 the AST nodes into code objects. Default is the built-in compile().
3360 result : ExecutionResult, optional
3388 result : ExecutionResult, optional
3361 An object to store exceptions that occur during execution.
3389 An object to store exceptions that occur during execution.
3362
3390
3363 Returns
3391 Returns
3364 -------
3392 -------
3365 True if an exception occurred while running code, False if it finished
3393 True if an exception occurred while running code, False if it finished
3366 running.
3394 running.
3367 """
3395 """
3368 if not nodelist:
3396 if not nodelist:
3369 return
3397 return
3370
3398
3371 if interactivity == 'last_expr_or_assign':
3399 if interactivity == 'last_expr_or_assign':
3372 if isinstance(nodelist[-1], _assign_nodes):
3400 if isinstance(nodelist[-1], _assign_nodes):
3373 asg = nodelist[-1]
3401 asg = nodelist[-1]
3374 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3402 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
3375 target = asg.targets[0]
3403 target = asg.targets[0]
3376 elif isinstance(asg, _single_targets_nodes):
3404 elif isinstance(asg, _single_targets_nodes):
3377 target = asg.target
3405 target = asg.target
3378 else:
3406 else:
3379 target = None
3407 target = None
3380 if isinstance(target, ast.Name):
3408 if isinstance(target, ast.Name):
3381 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3409 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
3382 ast.fix_missing_locations(nnode)
3410 ast.fix_missing_locations(nnode)
3383 nodelist.append(nnode)
3411 nodelist.append(nnode)
3384 interactivity = 'last_expr'
3412 interactivity = 'last_expr'
3385
3413
3386 _async = False
3414 _async = False
3387 if interactivity == 'last_expr':
3415 if interactivity == 'last_expr':
3388 if isinstance(nodelist[-1], ast.Expr):
3416 if isinstance(nodelist[-1], ast.Expr):
3389 interactivity = "last"
3417 interactivity = "last"
3390 else:
3418 else:
3391 interactivity = "none"
3419 interactivity = "none"
3392
3420
3393 if interactivity == 'none':
3421 if interactivity == 'none':
3394 to_run_exec, to_run_interactive = nodelist, []
3422 to_run_exec, to_run_interactive = nodelist, []
3395 elif interactivity == 'last':
3423 elif interactivity == 'last':
3396 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3424 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
3397 elif interactivity == 'all':
3425 elif interactivity == 'all':
3398 to_run_exec, to_run_interactive = [], nodelist
3426 to_run_exec, to_run_interactive = [], nodelist
3399 elif interactivity == 'async':
3427 elif interactivity == 'async':
3400 to_run_exec, to_run_interactive = [], nodelist
3428 to_run_exec, to_run_interactive = [], nodelist
3401 _async = True
3429 _async = True
3402 else:
3430 else:
3403 raise ValueError("Interactivity was %r" % interactivity)
3431 raise ValueError("Interactivity was %r" % interactivity)
3404
3432
3405 try:
3433 try:
3406 if _async and sys.version_info > (3,8):
3434 if _async and sys.version_info > (3,8):
3407 raise ValueError("This branch should never happen on Python 3.8 and above, "
3435 raise ValueError("This branch should never happen on Python 3.8 and above, "
3408 "please try to upgrade IPython and open a bug report with your case.")
3436 "please try to upgrade IPython and open a bug report with your case.")
3409 if _async:
3437 if _async:
3410 # If interactivity is async the semantics of run_code are
3438 # If interactivity is async the semantics of run_code are
3411 # completely different Skip usual machinery.
3439 # completely different Skip usual machinery.
3412 mod = Module(nodelist, [])
3440 mod = Module(nodelist, [])
3413 async_wrapper_code = compiler(mod, cell_name, 'exec')
3441 async_wrapper_code = compiler(mod, cell_name, 'exec')
3414 exec(async_wrapper_code, self.user_global_ns, self.user_ns)
3442 exec(async_wrapper_code, self.user_global_ns, self.user_ns)
3415 async_code = removed_co_newlocals(self.user_ns.pop('async-def-wrapper')).__code__
3443 async_code = removed_co_newlocals(self.user_ns.pop('async-def-wrapper')).__code__
3416 if (await self.run_code(async_code, result, async_=True)):
3444 if (await self.run_code(async_code, result, async_=True)):
3417 return True
3445 return True
3418 else:
3446 else:
3419 if sys.version_info > (3, 8):
3447 if sys.version_info > (3, 8):
3420 def compare(code):
3448 def compare(code):
3421 is_async = (inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE)
3449 is_async = (inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE)
3422 return is_async
3450 return is_async
3423 else:
3451 else:
3424 def compare(code):
3452 def compare(code):
3425 return _async
3453 return _async
3426
3454
3427 # refactor that to just change the mod constructor.
3455 # refactor that to just change the mod constructor.
3428 to_run = []
3456 to_run = []
3429 for node in to_run_exec:
3457 for node in to_run_exec:
3430 to_run.append((node, 'exec'))
3458 to_run.append((node, 'exec'))
3431
3459
3432 for node in to_run_interactive:
3460 for node in to_run_interactive:
3433 to_run.append((node, 'single'))
3461 to_run.append((node, 'single'))
3434
3462
3435 for node,mode in to_run:
3463 for node,mode in to_run:
3436 if mode == 'exec':
3464 if mode == 'exec':
3437 mod = Module([node], [])
3465 mod = Module([node], [])
3438 elif mode == 'single':
3466 elif mode == 'single':
3439 mod = ast.Interactive([node])
3467 mod = ast.Interactive([node])
3440 with compiler.extra_flags(getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0x0) if self.autoawait else 0x0):
3468 with compiler.extra_flags(getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0x0) if self.autoawait else 0x0):
3441 code = compiler(mod, cell_name, mode)
3469 code = compiler(mod, cell_name, mode)
3442 code = self._update_code_co_name(code)
3470 code = self._update_code_co_name(code)
3443 asy = compare(code)
3471 asy = compare(code)
3444 if (await self.run_code(code, result, async_=asy)):
3472 if (await self.run_code(code, result, async_=asy)):
3445 return True
3473 return True
3446
3474
3447 # Flush softspace
3475 # Flush softspace
3448 if softspace(sys.stdout, 0):
3476 if softspace(sys.stdout, 0):
3449 print()
3477 print()
3450
3478
3451 except:
3479 except:
3452 # It's possible to have exceptions raised here, typically by
3480 # It's possible to have exceptions raised here, typically by
3453 # compilation of odd code (such as a naked 'return' outside a
3481 # compilation of odd code (such as a naked 'return' outside a
3454 # function) that did parse but isn't valid. Typically the exception
3482 # function) that did parse but isn't valid. Typically the exception
3455 # is a SyntaxError, but it's safest just to catch anything and show
3483 # is a SyntaxError, but it's safest just to catch anything and show
3456 # the user a traceback.
3484 # the user a traceback.
3457
3485
3458 # We do only one try/except outside the loop to minimize the impact
3486 # We do only one try/except outside the loop to minimize the impact
3459 # on runtime, and also because if any node in the node list is
3487 # on runtime, and also because if any node in the node list is
3460 # broken, we should stop execution completely.
3488 # broken, we should stop execution completely.
3461 if result:
3489 if result:
3462 result.error_before_exec = sys.exc_info()[1]
3490 result.error_before_exec = sys.exc_info()[1]
3463 self.showtraceback()
3491 self.showtraceback()
3464 return True
3492 return True
3465
3493
3466 return False
3494 return False
3467
3495
3468 def _async_exec(self, code_obj: types.CodeType, user_ns: dict):
3496 def _async_exec(self, code_obj: types.CodeType, user_ns: dict):
3469 """
3497 """
3470 Evaluate an asynchronous code object using a code runner
3498 Evaluate an asynchronous code object using a code runner
3471
3499
3472 Fake asynchronous execution of code_object in a namespace via a proxy namespace.
3500 Fake asynchronous execution of code_object in a namespace via a proxy namespace.
3473
3501
3474 Returns coroutine object, which can be executed via async loop runner
3502 Returns coroutine object, which can be executed via async loop runner
3475
3503
3476 WARNING: The semantics of `async_exec` are quite different from `exec`,
3504 WARNING: The semantics of `async_exec` are quite different from `exec`,
3477 in particular you can only pass a single namespace. It also return a
3505 in particular you can only pass a single namespace. It also return a
3478 handle to the value of the last things returned by code_object.
3506 handle to the value of the last things returned by code_object.
3479 """
3507 """
3480
3508
3481 return eval(code_obj, user_ns)
3509 return eval(code_obj, user_ns)
3482
3510
3483 async def run_code(self, code_obj, result=None, *, async_=False):
3511 async def run_code(self, code_obj, result=None, *, async_=False):
3484 """Execute a code object.
3512 """Execute a code object.
3485
3513
3486 When an exception occurs, self.showtraceback() is called to display a
3514 When an exception occurs, self.showtraceback() is called to display a
3487 traceback.
3515 traceback.
3488
3516
3489 Parameters
3517 Parameters
3490 ----------
3518 ----------
3491 code_obj : code object
3519 code_obj : code object
3492 A compiled code object, to be executed
3520 A compiled code object, to be executed
3493 result : ExecutionResult, optional
3521 result : ExecutionResult, optional
3494 An object to store exceptions that occur during execution.
3522 An object to store exceptions that occur during execution.
3495 async_ : Bool (Experimental)
3523 async_ : Bool (Experimental)
3496 Attempt to run top-level asynchronous code in a default loop.
3524 Attempt to run top-level asynchronous code in a default loop.
3497
3525
3498 Returns
3526 Returns
3499 -------
3527 -------
3500 False : successful execution.
3528 False : successful execution.
3501 True : an error occurred.
3529 True : an error occurred.
3502 """
3530 """
3503 # special value to say that anything above is IPython and should be
3531 # special value to say that anything above is IPython and should be
3504 # hidden.
3532 # hidden.
3505 __tracebackhide__ = "__ipython_bottom__"
3533 __tracebackhide__ = "__ipython_bottom__"
3506 # Set our own excepthook in case the user code tries to call it
3534 # Set our own excepthook in case the user code tries to call it
3507 # directly, so that the IPython crash handler doesn't get triggered
3535 # directly, so that the IPython crash handler doesn't get triggered
3508 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3536 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
3509
3537
3510 # we save the original sys.excepthook in the instance, in case config
3538 # we save the original sys.excepthook in the instance, in case config
3511 # code (such as magics) needs access to it.
3539 # code (such as magics) needs access to it.
3512 self.sys_excepthook = old_excepthook
3540 self.sys_excepthook = old_excepthook
3513 outflag = True # happens in more places, so it's easier as default
3541 outflag = True # happens in more places, so it's easier as default
3514 try:
3542 try:
3515 try:
3543 try:
3516 self.hooks.pre_run_code_hook()
3544 self.hooks.pre_run_code_hook()
3517 if async_ and sys.version_info < (3,8):
3545 if async_ and sys.version_info < (3,8):
3518 last_expr = (await self._async_exec(code_obj, self.user_ns))
3546 last_expr = (await self._async_exec(code_obj, self.user_ns))
3519 code = compile('last_expr', 'fake', "single")
3547 code = compile('last_expr', 'fake', "single")
3520 exec(code, {'last_expr': last_expr})
3548 exec(code, {'last_expr': last_expr})
3521 elif async_ :
3549 elif async_ :
3522 await eval(code_obj, self.user_global_ns, self.user_ns)
3550 await eval(code_obj, self.user_global_ns, self.user_ns)
3523 else:
3551 else:
3524 exec(code_obj, self.user_global_ns, self.user_ns)
3552 exec(code_obj, self.user_global_ns, self.user_ns)
3525 finally:
3553 finally:
3526 # Reset our crash handler in place
3554 # Reset our crash handler in place
3527 sys.excepthook = old_excepthook
3555 sys.excepthook = old_excepthook
3528 except SystemExit as e:
3556 except SystemExit as e:
3529 if result is not None:
3557 if result is not None:
3530 result.error_in_exec = e
3558 result.error_in_exec = e
3531 self.showtraceback(exception_only=True)
3559 self.showtraceback(exception_only=True)
3532 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3560 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
3533 except self.custom_exceptions:
3561 except self.custom_exceptions:
3534 etype, value, tb = sys.exc_info()
3562 etype, value, tb = sys.exc_info()
3535 if result is not None:
3563 if result is not None:
3536 result.error_in_exec = value
3564 result.error_in_exec = value
3537 self.CustomTB(etype, value, tb)
3565 self.CustomTB(etype, value, tb)
3538 except:
3566 except:
3539 if result is not None:
3567 if result is not None:
3540 result.error_in_exec = sys.exc_info()[1]
3568 result.error_in_exec = sys.exc_info()[1]
3541 self.showtraceback(running_compiled_code=True)
3569 self.showtraceback(running_compiled_code=True)
3542 else:
3570 else:
3543 outflag = False
3571 outflag = False
3544 return outflag
3572 return outflag
3545
3573
3546 # For backwards compatibility
3574 # For backwards compatibility
3547 runcode = run_code
3575 runcode = run_code
3548
3576
3549 def check_complete(self, code: str) -> Tuple[str, str]:
3577 def check_complete(self, code: str) -> Tuple[str, str]:
3550 """Return whether a block of code is ready to execute, or should be continued
3578 """Return whether a block of code is ready to execute, or should be continued
3551
3579
3552 Parameters
3580 Parameters
3553 ----------
3581 ----------
3554 source : string
3582 source : string
3555 Python input code, which can be multiline.
3583 Python input code, which can be multiline.
3556
3584
3557 Returns
3585 Returns
3558 -------
3586 -------
3559 status : str
3587 status : str
3560 One of 'complete', 'incomplete', or 'invalid' if source is not a
3588 One of 'complete', 'incomplete', or 'invalid' if source is not a
3561 prefix of valid code.
3589 prefix of valid code.
3562 indent : str
3590 indent : str
3563 When status is 'incomplete', this is some whitespace to insert on
3591 When status is 'incomplete', this is some whitespace to insert on
3564 the next line of the prompt.
3592 the next line of the prompt.
3565 """
3593 """
3566 status, nspaces = self.input_transformer_manager.check_complete(code)
3594 status, nspaces = self.input_transformer_manager.check_complete(code)
3567 return status, ' ' * (nspaces or 0)
3595 return status, ' ' * (nspaces or 0)
3568
3596
3569 #-------------------------------------------------------------------------
3597 #-------------------------------------------------------------------------
3570 # Things related to GUI support and pylab
3598 # Things related to GUI support and pylab
3571 #-------------------------------------------------------------------------
3599 #-------------------------------------------------------------------------
3572
3600
3573 active_eventloop = None
3601 active_eventloop = None
3574
3602
3575 def enable_gui(self, gui=None):
3603 def enable_gui(self, gui=None):
3576 raise NotImplementedError('Implement enable_gui in a subclass')
3604 raise NotImplementedError('Implement enable_gui in a subclass')
3577
3605
3578 def enable_matplotlib(self, gui=None):
3606 def enable_matplotlib(self, gui=None):
3579 """Enable interactive matplotlib and inline figure support.
3607 """Enable interactive matplotlib and inline figure support.
3580
3608
3581 This takes the following steps:
3609 This takes the following steps:
3582
3610
3583 1. select the appropriate eventloop and matplotlib backend
3611 1. select the appropriate eventloop and matplotlib backend
3584 2. set up matplotlib for interactive use with that backend
3612 2. set up matplotlib for interactive use with that backend
3585 3. configure formatters for inline figure display
3613 3. configure formatters for inline figure display
3586 4. enable the selected gui eventloop
3614 4. enable the selected gui eventloop
3587
3615
3588 Parameters
3616 Parameters
3589 ----------
3617 ----------
3590 gui : optional, string
3618 gui : optional, string
3591 If given, dictates the choice of matplotlib GUI backend to use
3619 If given, dictates the choice of matplotlib GUI backend to use
3592 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3620 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3593 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3621 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3594 matplotlib (as dictated by the matplotlib build-time options plus the
3622 matplotlib (as dictated by the matplotlib build-time options plus the
3595 user's matplotlibrc configuration file). Note that not all backends
3623 user's matplotlibrc configuration file). Note that not all backends
3596 make sense in all contexts, for example a terminal ipython can't
3624 make sense in all contexts, for example a terminal ipython can't
3597 display figures inline.
3625 display figures inline.
3598 """
3626 """
3599 from IPython.core import pylabtools as pt
3627 from IPython.core import pylabtools as pt
3600 from matplotlib_inline.backend_inline import configure_inline_support
3628 from matplotlib_inline.backend_inline import configure_inline_support
3601 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3629 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3602
3630
3603 if gui != 'inline':
3631 if gui != 'inline':
3604 # If we have our first gui selection, store it
3632 # If we have our first gui selection, store it
3605 if self.pylab_gui_select is None:
3633 if self.pylab_gui_select is None:
3606 self.pylab_gui_select = gui
3634 self.pylab_gui_select = gui
3607 # Otherwise if they are different
3635 # Otherwise if they are different
3608 elif gui != self.pylab_gui_select:
3636 elif gui != self.pylab_gui_select:
3609 print('Warning: Cannot change to a different GUI toolkit: %s.'
3637 print('Warning: Cannot change to a different GUI toolkit: %s.'
3610 ' Using %s instead.' % (gui, self.pylab_gui_select))
3638 ' Using %s instead.' % (gui, self.pylab_gui_select))
3611 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3639 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3612
3640
3613 pt.activate_matplotlib(backend)
3641 pt.activate_matplotlib(backend)
3614 configure_inline_support(self, backend)
3642 configure_inline_support(self, backend)
3615
3643
3616 # Now we must activate the gui pylab wants to use, and fix %run to take
3644 # Now we must activate the gui pylab wants to use, and fix %run to take
3617 # plot updates into account
3645 # plot updates into account
3618 self.enable_gui(gui)
3646 self.enable_gui(gui)
3619 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3647 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3620 pt.mpl_runner(self.safe_execfile)
3648 pt.mpl_runner(self.safe_execfile)
3621
3649
3622 return gui, backend
3650 return gui, backend
3623
3651
3624 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3652 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3625 """Activate pylab support at runtime.
3653 """Activate pylab support at runtime.
3626
3654
3627 This turns on support for matplotlib, preloads into the interactive
3655 This turns on support for matplotlib, preloads into the interactive
3628 namespace all of numpy and pylab, and configures IPython to correctly
3656 namespace all of numpy and pylab, and configures IPython to correctly
3629 interact with the GUI event loop. The GUI backend to be used can be
3657 interact with the GUI event loop. The GUI backend to be used can be
3630 optionally selected with the optional ``gui`` argument.
3658 optionally selected with the optional ``gui`` argument.
3631
3659
3632 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3660 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3633
3661
3634 Parameters
3662 Parameters
3635 ----------
3663 ----------
3636 gui : optional, string
3664 gui : optional, string
3637 If given, dictates the choice of matplotlib GUI backend to use
3665 If given, dictates the choice of matplotlib GUI backend to use
3638 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3666 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3639 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3667 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3640 matplotlib (as dictated by the matplotlib build-time options plus the
3668 matplotlib (as dictated by the matplotlib build-time options plus the
3641 user's matplotlibrc configuration file). Note that not all backends
3669 user's matplotlibrc configuration file). Note that not all backends
3642 make sense in all contexts, for example a terminal ipython can't
3670 make sense in all contexts, for example a terminal ipython can't
3643 display figures inline.
3671 display figures inline.
3644 import_all : optional, bool, default: True
3672 import_all : optional, bool, default: True
3645 Whether to do `from numpy import *` and `from pylab import *`
3673 Whether to do `from numpy import *` and `from pylab import *`
3646 in addition to module imports.
3674 in addition to module imports.
3647 welcome_message : deprecated
3675 welcome_message : deprecated
3648 This argument is ignored, no welcome message will be displayed.
3676 This argument is ignored, no welcome message will be displayed.
3649 """
3677 """
3650 from IPython.core.pylabtools import import_pylab
3678 from IPython.core.pylabtools import import_pylab
3651
3679
3652 gui, backend = self.enable_matplotlib(gui)
3680 gui, backend = self.enable_matplotlib(gui)
3653
3681
3654 # We want to prevent the loading of pylab to pollute the user's
3682 # We want to prevent the loading of pylab to pollute the user's
3655 # namespace as shown by the %who* magics, so we execute the activation
3683 # namespace as shown by the %who* magics, so we execute the activation
3656 # code in an empty namespace, and we update *both* user_ns and
3684 # code in an empty namespace, and we update *both* user_ns and
3657 # user_ns_hidden with this information.
3685 # user_ns_hidden with this information.
3658 ns = {}
3686 ns = {}
3659 import_pylab(ns, import_all)
3687 import_pylab(ns, import_all)
3660 # warn about clobbered names
3688 # warn about clobbered names
3661 ignored = {"__builtins__"}
3689 ignored = {"__builtins__"}
3662 both = set(ns).intersection(self.user_ns).difference(ignored)
3690 both = set(ns).intersection(self.user_ns).difference(ignored)
3663 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3691 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3664 self.user_ns.update(ns)
3692 self.user_ns.update(ns)
3665 self.user_ns_hidden.update(ns)
3693 self.user_ns_hidden.update(ns)
3666 return gui, backend, clobbered
3694 return gui, backend, clobbered
3667
3695
3668 #-------------------------------------------------------------------------
3696 #-------------------------------------------------------------------------
3669 # Utilities
3697 # Utilities
3670 #-------------------------------------------------------------------------
3698 #-------------------------------------------------------------------------
3671
3699
3672 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3700 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3673 """Expand python variables in a string.
3701 """Expand python variables in a string.
3674
3702
3675 The depth argument indicates how many frames above the caller should
3703 The depth argument indicates how many frames above the caller should
3676 be walked to look for the local namespace where to expand variables.
3704 be walked to look for the local namespace where to expand variables.
3677
3705
3678 The global namespace for expansion is always the user's interactive
3706 The global namespace for expansion is always the user's interactive
3679 namespace.
3707 namespace.
3680 """
3708 """
3681 ns = self.user_ns.copy()
3709 ns = self.user_ns.copy()
3682 try:
3710 try:
3683 frame = sys._getframe(depth+1)
3711 frame = sys._getframe(depth+1)
3684 except ValueError:
3712 except ValueError:
3685 # This is thrown if there aren't that many frames on the stack,
3713 # This is thrown if there aren't that many frames on the stack,
3686 # e.g. if a script called run_line_magic() directly.
3714 # e.g. if a script called run_line_magic() directly.
3687 pass
3715 pass
3688 else:
3716 else:
3689 ns.update(frame.f_locals)
3717 ns.update(frame.f_locals)
3690
3718
3691 try:
3719 try:
3692 # We have to use .vformat() here, because 'self' is a valid and common
3720 # We have to use .vformat() here, because 'self' is a valid and common
3693 # name, and expanding **ns for .format() would make it collide with
3721 # name, and expanding **ns for .format() would make it collide with
3694 # the 'self' argument of the method.
3722 # the 'self' argument of the method.
3695 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3723 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3696 except Exception:
3724 except Exception:
3697 # if formatter couldn't format, just let it go untransformed
3725 # if formatter couldn't format, just let it go untransformed
3698 pass
3726 pass
3699 return cmd
3727 return cmd
3700
3728
3701 def mktempfile(self, data=None, prefix='ipython_edit_'):
3729 def mktempfile(self, data=None, prefix='ipython_edit_'):
3702 """Make a new tempfile and return its filename.
3730 """Make a new tempfile and return its filename.
3703
3731
3704 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3732 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3705 but it registers the created filename internally so ipython cleans it up
3733 but it registers the created filename internally so ipython cleans it up
3706 at exit time.
3734 at exit time.
3707
3735
3708 Optional inputs:
3736 Optional inputs:
3709
3737
3710 - data(None): if data is given, it gets written out to the temp file
3738 - data(None): if data is given, it gets written out to the temp file
3711 immediately, and the file is closed again."""
3739 immediately, and the file is closed again."""
3712
3740
3713 dirname = tempfile.mkdtemp(prefix=prefix)
3741 dirname = tempfile.mkdtemp(prefix=prefix)
3714 self.tempdirs.append(dirname)
3742 self.tempdirs.append(dirname)
3715
3743
3716 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3744 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3717 os.close(handle) # On Windows, there can only be one open handle on a file
3745 os.close(handle) # On Windows, there can only be one open handle on a file
3718 self.tempfiles.append(filename)
3746 self.tempfiles.append(filename)
3719
3747
3720 if data:
3748 if data:
3721 with open(filename, 'w') as tmp_file:
3749 with open(filename, 'w') as tmp_file:
3722 tmp_file.write(data)
3750 tmp_file.write(data)
3723 return filename
3751 return filename
3724
3752
3725 @undoc
3753 @undoc
3726 def write(self,data):
3754 def write(self,data):
3727 """DEPRECATED: Write a string to the default output"""
3755 """DEPRECATED: Write a string to the default output"""
3728 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3756 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3729 DeprecationWarning, stacklevel=2)
3757 DeprecationWarning, stacklevel=2)
3730 sys.stdout.write(data)
3758 sys.stdout.write(data)
3731
3759
3732 @undoc
3760 @undoc
3733 def write_err(self,data):
3761 def write_err(self,data):
3734 """DEPRECATED: Write a string to the default error output"""
3762 """DEPRECATED: Write a string to the default error output"""
3735 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3763 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3736 DeprecationWarning, stacklevel=2)
3764 DeprecationWarning, stacklevel=2)
3737 sys.stderr.write(data)
3765 sys.stderr.write(data)
3738
3766
3739 def ask_yes_no(self, prompt, default=None, interrupt=None):
3767 def ask_yes_no(self, prompt, default=None, interrupt=None):
3740 if self.quiet:
3768 if self.quiet:
3741 return True
3769 return True
3742 return ask_yes_no(prompt,default,interrupt)
3770 return ask_yes_no(prompt,default,interrupt)
3743
3771
3744 def show_usage(self):
3772 def show_usage(self):
3745 """Show a usage message"""
3773 """Show a usage message"""
3746 page.page(IPython.core.usage.interactive_usage)
3774 page.page(IPython.core.usage.interactive_usage)
3747
3775
3748 def extract_input_lines(self, range_str, raw=False):
3776 def extract_input_lines(self, range_str, raw=False):
3749 """Return as a string a set of input history slices.
3777 """Return as a string a set of input history slices.
3750
3778
3751 Parameters
3779 Parameters
3752 ----------
3780 ----------
3753 range_str : string
3781 range_str : string
3754 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3782 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3755 since this function is for use by magic functions which get their
3783 since this function is for use by magic functions which get their
3756 arguments as strings. The number before the / is the session
3784 arguments as strings. The number before the / is the session
3757 number: ~n goes n back from the current session.
3785 number: ~n goes n back from the current session.
3758
3786
3759 raw : bool, optional
3787 raw : bool, optional
3760 By default, the processed input is used. If this is true, the raw
3788 By default, the processed input is used. If this is true, the raw
3761 input history is used instead.
3789 input history is used instead.
3762
3790
3763 Notes
3791 Notes
3764 -----
3792 -----
3765
3793
3766 Slices can be described with two notations:
3794 Slices can be described with two notations:
3767
3795
3768 * ``N:M`` -> standard python form, means including items N...(M-1).
3796 * ``N:M`` -> standard python form, means including items N...(M-1).
3769 * ``N-M`` -> include items N..M (closed endpoint).
3797 * ``N-M`` -> include items N..M (closed endpoint).
3770 """
3798 """
3771 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3799 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3772 return "\n".join(x for _, _, x in lines)
3800 return "\n".join(x for _, _, x in lines)
3773
3801
3774 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3802 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3775 """Get a code string from history, file, url, or a string or macro.
3803 """Get a code string from history, file, url, or a string or macro.
3776
3804
3777 This is mainly used by magic functions.
3805 This is mainly used by magic functions.
3778
3806
3779 Parameters
3807 Parameters
3780 ----------
3808 ----------
3781
3809
3782 target : str
3810 target : str
3783
3811
3784 A string specifying code to retrieve. This will be tried respectively
3812 A string specifying code to retrieve. This will be tried respectively
3785 as: ranges of input history (see %history for syntax), url,
3813 as: ranges of input history (see %history for syntax), url,
3786 corresponding .py file, filename, or an expression evaluating to a
3814 corresponding .py file, filename, or an expression evaluating to a
3787 string or Macro in the user namespace.
3815 string or Macro in the user namespace.
3788
3816
3789 raw : bool
3817 raw : bool
3790 If true (default), retrieve raw history. Has no effect on the other
3818 If true (default), retrieve raw history. Has no effect on the other
3791 retrieval mechanisms.
3819 retrieval mechanisms.
3792
3820
3793 py_only : bool (default False)
3821 py_only : bool (default False)
3794 Only try to fetch python code, do not try alternative methods to decode file
3822 Only try to fetch python code, do not try alternative methods to decode file
3795 if unicode fails.
3823 if unicode fails.
3796
3824
3797 Returns
3825 Returns
3798 -------
3826 -------
3799 A string of code.
3827 A string of code.
3800
3828
3801 ValueError is raised if nothing is found, and TypeError if it evaluates
3829 ValueError is raised if nothing is found, and TypeError if it evaluates
3802 to an object of another type. In each case, .args[0] is a printable
3830 to an object of another type. In each case, .args[0] is a printable
3803 message.
3831 message.
3804 """
3832 """
3805 code = self.extract_input_lines(target, raw=raw) # Grab history
3833 code = self.extract_input_lines(target, raw=raw) # Grab history
3806 if code:
3834 if code:
3807 return code
3835 return code
3808 try:
3836 try:
3809 if target.startswith(('http://', 'https://')):
3837 if target.startswith(('http://', 'https://')):
3810 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3838 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3811 except UnicodeDecodeError:
3839 except UnicodeDecodeError:
3812 if not py_only :
3840 if not py_only :
3813 # Deferred import
3841 # Deferred import
3814 from urllib.request import urlopen
3842 from urllib.request import urlopen
3815 response = urlopen(target)
3843 response = urlopen(target)
3816 return response.read().decode('latin1')
3844 return response.read().decode('latin1')
3817 raise ValueError(("'%s' seem to be unreadable.") % target)
3845 raise ValueError(("'%s' seem to be unreadable.") % target)
3818
3846
3819 potential_target = [target]
3847 potential_target = [target]
3820 try :
3848 try :
3821 potential_target.insert(0,get_py_filename(target))
3849 potential_target.insert(0,get_py_filename(target))
3822 except IOError:
3850 except IOError:
3823 pass
3851 pass
3824
3852
3825 for tgt in potential_target :
3853 for tgt in potential_target :
3826 if os.path.isfile(tgt): # Read file
3854 if os.path.isfile(tgt): # Read file
3827 try :
3855 try :
3828 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3856 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3829 except UnicodeDecodeError :
3857 except UnicodeDecodeError :
3830 if not py_only :
3858 if not py_only :
3831 with io_open(tgt,'r', encoding='latin1') as f :
3859 with io_open(tgt,'r', encoding='latin1') as f :
3832 return f.read()
3860 return f.read()
3833 raise ValueError(("'%s' seem to be unreadable.") % target)
3861 raise ValueError(("'%s' seem to be unreadable.") % target)
3834 elif os.path.isdir(os.path.expanduser(tgt)):
3862 elif os.path.isdir(os.path.expanduser(tgt)):
3835 raise ValueError("'%s' is a directory, not a regular file." % target)
3863 raise ValueError("'%s' is a directory, not a regular file." % target)
3836
3864
3837 if search_ns:
3865 if search_ns:
3838 # Inspect namespace to load object source
3866 # Inspect namespace to load object source
3839 object_info = self.object_inspect(target, detail_level=1)
3867 object_info = self.object_inspect(target, detail_level=1)
3840 if object_info['found'] and object_info['source']:
3868 if object_info['found'] and object_info['source']:
3841 return object_info['source']
3869 return object_info['source']
3842
3870
3843 try: # User namespace
3871 try: # User namespace
3844 codeobj = eval(target, self.user_ns)
3872 codeobj = eval(target, self.user_ns)
3845 except Exception:
3873 except Exception:
3846 raise ValueError(("'%s' was not found in history, as a file, url, "
3874 raise ValueError(("'%s' was not found in history, as a file, url, "
3847 "nor in the user namespace.") % target)
3875 "nor in the user namespace.") % target)
3848
3876
3849 if isinstance(codeobj, str):
3877 if isinstance(codeobj, str):
3850 return codeobj
3878 return codeobj
3851 elif isinstance(codeobj, Macro):
3879 elif isinstance(codeobj, Macro):
3852 return codeobj.value
3880 return codeobj.value
3853
3881
3854 raise TypeError("%s is neither a string nor a macro." % target,
3882 raise TypeError("%s is neither a string nor a macro." % target,
3855 codeobj)
3883 codeobj)
3856
3884
3857 #-------------------------------------------------------------------------
3885 #-------------------------------------------------------------------------
3858 # Things related to IPython exiting
3886 # Things related to IPython exiting
3859 #-------------------------------------------------------------------------
3887 #-------------------------------------------------------------------------
3860 def atexit_operations(self):
3888 def atexit_operations(self):
3861 """This will be executed at the time of exit.
3889 """This will be executed at the time of exit.
3862
3890
3863 Cleanup operations and saving of persistent data that is done
3891 Cleanup operations and saving of persistent data that is done
3864 unconditionally by IPython should be performed here.
3892 unconditionally by IPython should be performed here.
3865
3893
3866 For things that may depend on startup flags or platform specifics (such
3894 For things that may depend on startup flags or platform specifics (such
3867 as having readline or not), register a separate atexit function in the
3895 as having readline or not), register a separate atexit function in the
3868 code that has the appropriate information, rather than trying to
3896 code that has the appropriate information, rather than trying to
3869 clutter
3897 clutter
3870 """
3898 """
3871 # Close the history session (this stores the end time and line count)
3899 # Close the history session (this stores the end time and line count)
3872 # this must be *before* the tempfile cleanup, in case of temporary
3900 # this must be *before* the tempfile cleanup, in case of temporary
3873 # history db
3901 # history db
3874 self.history_manager.end_session()
3902 self.history_manager.end_session()
3875
3903
3876 # Cleanup all tempfiles and folders left around
3904 # Cleanup all tempfiles and folders left around
3877 for tfile in self.tempfiles:
3905 for tfile in self.tempfiles:
3878 try:
3906 try:
3879 os.unlink(tfile)
3907 os.unlink(tfile)
3880 except OSError:
3908 except OSError:
3881 pass
3909 pass
3882
3910
3883 for tdir in self.tempdirs:
3911 for tdir in self.tempdirs:
3884 try:
3912 try:
3885 os.rmdir(tdir)
3913 os.rmdir(tdir)
3886 except OSError:
3914 except OSError:
3887 pass
3915 pass
3888
3916
3889 # Clear all user namespaces to release all references cleanly.
3917 # Clear all user namespaces to release all references cleanly.
3890 self.reset(new_session=False)
3918 self.reset(new_session=False)
3891
3919
3892 # Run user hooks
3920 # Run user hooks
3893 self.hooks.shutdown_hook()
3921 self.hooks.shutdown_hook()
3894
3922
3895 def cleanup(self):
3923 def cleanup(self):
3896 self.restore_sys_module_state()
3924 self.restore_sys_module_state()
3897
3925
3898
3926
3899 # Overridden in terminal subclass to change prompts
3927 # Overridden in terminal subclass to change prompts
3900 def switch_doctest_mode(self, mode):
3928 def switch_doctest_mode(self, mode):
3901 pass
3929 pass
3902
3930
3903
3931
3904 class InteractiveShellABC(metaclass=abc.ABCMeta):
3932 class InteractiveShellABC(metaclass=abc.ABCMeta):
3905 """An abstract base class for InteractiveShell."""
3933 """An abstract base class for InteractiveShell."""
3906
3934
3907 InteractiveShellABC.register(InteractiveShell)
3935 InteractiveShellABC.register(InteractiveShell)
@@ -1,382 +1,382 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 deprecated_subcommands = dict(
213 deprecated_subcommands = dict(
214 qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp',
214 qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp',
215 """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console."""
215 """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console."""
216 ),
216 ),
217 notebook=('notebook.notebookapp.NotebookApp',
217 notebook=('notebook.notebookapp.NotebookApp',
218 """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server."""
218 """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server."""
219 ),
219 ),
220 console=('jupyter_console.app.ZMQTerminalIPythonApp',
220 console=('jupyter_console.app.ZMQTerminalIPythonApp',
221 """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console."""
221 """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console."""
222 ),
222 ),
223 nbconvert=('nbconvert.nbconvertapp.NbConvertApp',
223 nbconvert=('nbconvert.nbconvertapp.NbConvertApp',
224 "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats."
224 "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats."
225 ),
225 ),
226 trust=('nbformat.sign.TrustNotebookApp',
226 trust=('nbformat.sign.TrustNotebookApp',
227 "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load."
227 "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load."
228 ),
228 ),
229 kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp',
229 kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp',
230 "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications."
230 "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications."
231 ),
231 ),
232 )
232 )
233 subcommands = dict(
233 subcommands = dict(
234 profile = ("IPython.core.profileapp.ProfileApp",
234 profile = ("IPython.core.profileapp.ProfileApp",
235 "Create and manage IPython profiles."
235 "Create and manage IPython profiles."
236 ),
236 ),
237 kernel = ("ipykernel.kernelapp.IPKernelApp",
237 kernel = ("ipykernel.kernelapp.IPKernelApp",
238 "Start a kernel without an attached frontend."
238 "Start a kernel without an attached frontend."
239 ),
239 ),
240 locate=('IPython.terminal.ipapp.LocateIPythonApp',
240 locate=('IPython.terminal.ipapp.LocateIPythonApp',
241 LocateIPythonApp.description
241 LocateIPythonApp.description
242 ),
242 ),
243 history=('IPython.core.historyapp.HistoryApp',
243 history=('IPython.core.historyapp.HistoryApp',
244 "Manage the IPython history database."
244 "Manage the IPython history database."
245 ),
245 ),
246 )
246 )
247 deprecated_subcommands['install-nbextension'] = (
247 deprecated_subcommands['install-nbextension'] = (
248 "notebook.nbextensions.InstallNBExtensionApp",
248 "notebook.nbextensions.InstallNBExtensionApp",
249 "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files"
249 "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files"
250 )
250 )
251 subcommands.update(deprecated_subcommands)
251 subcommands.update(deprecated_subcommands)
252
252
253 # *do* autocreate requested profile, but don't create the config file.
253 # *do* autocreate requested profile, but don't create the config file.
254 auto_create=Bool(True)
254 auto_create=Bool(True)
255 # configurables
255 # configurables
256 quick = Bool(False,
256 quick = Bool(False,
257 help="""Start IPython quickly by skipping the loading of config files."""
257 help="""Start IPython quickly by skipping the loading of config files."""
258 ).tag(config=True)
258 ).tag(config=True)
259 @observe('quick')
259 @observe('quick')
260 def _quick_changed(self, change):
260 def _quick_changed(self, change):
261 if change['new']:
261 if change['new']:
262 self.load_config_file = lambda *a, **kw: None
262 self.load_config_file = lambda *a, **kw: None
263
263
264 display_banner = Bool(True,
264 display_banner = Bool(True,
265 help="Whether to display a banner upon starting IPython."
265 help="Whether to display a banner upon starting IPython."
266 ).tag(config=True)
266 ).tag(config=True)
267
267
268 # if there is code of files to run from the cmd line, don't interact
268 # if there is code of files to run from the cmd line, don't interact
269 # unless the --i flag (App.force_interact) is true.
269 # unless the --i flag (App.force_interact) is true.
270 force_interact = Bool(False,
270 force_interact = Bool(False,
271 help="""If a command or file is given via the command-line,
271 help="""If a command or file is given via the command-line,
272 e.g. 'ipython foo.py', start an interactive shell after executing the
272 e.g. 'ipython foo.py', start an interactive shell after executing the
273 file or command."""
273 file or command."""
274 ).tag(config=True)
274 ).tag(config=True)
275 @observe('force_interact')
275 @observe('force_interact')
276 def _force_interact_changed(self, change):
276 def _force_interact_changed(self, change):
277 if change['new']:
277 if change['new']:
278 self.interact = True
278 self.interact = True
279
279
280 @observe('file_to_run', 'code_to_run', 'module_to_run')
280 @observe('file_to_run', 'code_to_run', 'module_to_run')
281 def _file_to_run_changed(self, change):
281 def _file_to_run_changed(self, change):
282 new = change['new']
282 new = change['new']
283 if new:
283 if new:
284 self.something_to_run = True
284 self.something_to_run = True
285 if new and not self.force_interact:
285 if new and not self.force_interact:
286 self.interact = False
286 self.interact = False
287
287
288 # internal, not-configurable
288 # internal, not-configurable
289 something_to_run=Bool(False)
289 something_to_run=Bool(False)
290
290
291 def parse_command_line(self, argv=None):
291 def parse_command_line(self, argv=None):
292 """override to allow old '-pylab' flag with deprecation warning"""
292 """override to allow old '-pylab' flag with deprecation warning"""
293
293
294 argv = sys.argv[1:] if argv is None else argv
294 argv = sys.argv[1:] if argv is None else argv
295
295
296 if '-pylab' in argv:
296 if '-pylab' in argv:
297 # deprecated `-pylab` given,
297 # deprecated `-pylab` given,
298 # warn and transform into current syntax
298 # warn and transform into current syntax
299 argv = argv[:] # copy, don't clobber
299 argv = argv[:] # copy, don't clobber
300 idx = argv.index('-pylab')
300 idx = argv.index('-pylab')
301 warnings.warn("`-pylab` flag has been deprecated.\n"
301 warnings.warn("`-pylab` flag has been deprecated.\n"
302 " Use `--matplotlib <backend>` and import pylab manually.")
302 " Use `--matplotlib <backend>` and import pylab manually.")
303 argv[idx] = '--pylab'
303 argv[idx] = '--pylab'
304
304
305 return super(TerminalIPythonApp, self).parse_command_line(argv)
305 return super(TerminalIPythonApp, self).parse_command_line(argv)
306
306
307 @catch_config_error
307 @catch_config_error
308 def initialize(self, argv=None):
308 def initialize(self, argv=None):
309 """Do actions after construct, but before starting the app."""
309 """Do actions after construct, but before starting the app."""
310 super(TerminalIPythonApp, self).initialize(argv)
310 super(TerminalIPythonApp, self).initialize(argv)
311 if self.subapp is not None:
311 if self.subapp is not None:
312 # don't bother initializing further, starting subapp
312 # don't bother initializing further, starting subapp
313 return
313 return
314 # print self.extra_args
314 # print self.extra_args
315 if self.extra_args and not self.something_to_run:
315 if self.extra_args and not self.something_to_run:
316 self.file_to_run = self.extra_args[0]
316 self.file_to_run = self.extra_args[0]
317 self.init_path()
317 self.init_path()
318 # create the shell
318 # create the shell
319 self.init_shell()
319 self.init_shell()
320 # and draw the banner
320 # and draw the banner
321 self.init_banner()
321 self.init_banner()
322 # Now a variety of things that happen after the banner is printed.
322 # Now a variety of things that happen after the banner is printed.
323 self.init_gui_pylab()
323 self.init_gui_pylab()
324 self.init_extensions()
324 self.init_extensions()
325 self.init_code()
325 self.init_code()
326
326
327 def init_shell(self):
327 def init_shell(self):
328 """initialize the InteractiveShell instance"""
328 """initialize the InteractiveShell instance"""
329 # Create an InteractiveShell instance.
329 # Create an InteractiveShell instance.
330 # shell.display_banner should always be False for the terminal
330 # shell.display_banner should always be False for the terminal
331 # based app, because we call shell.show_banner() by hand below
331 # based app, because we call shell.show_banner() by hand below
332 # so the banner shows *before* all extension loading stuff.
332 # so the banner shows *before* all extension loading stuff.
333 self.shell = self.interactive_shell_class.instance(parent=self,
333 self.shell = self.interactive_shell_class.instance(parent=self,
334 profile_dir=self.profile_dir,
334 profile_dir=self.profile_dir,
335 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
335 ipython_dir=self.ipython_dir, user_ns=self.user_ns)
336 self.shell.configurables.append(self)
336 self.shell.configurables.append(self)
337
337
338 def init_banner(self):
338 def init_banner(self):
339 """optionally display the banner"""
339 """optionally display the banner"""
340 if self.display_banner and self.interact:
340 if self.display_banner and self.interact:
341 self.shell.show_banner()
341 self.shell.show_banner()
342 # Make sure there is a space below the banner.
342 # Make sure there is a space below the banner.
343 if self.log_level <= logging.INFO: print()
343 if self.log_level <= logging.INFO: print()
344
344
345 def _pylab_changed(self, name, old, new):
345 def _pylab_changed(self, name, old, new):
346 """Replace --pylab='inline' with --pylab='auto'"""
346 """Replace --pylab='inline' with --pylab='auto'"""
347 if new == 'inline':
347 if new == 'inline':
348 warnings.warn("'inline' not available as pylab backend, "
348 warnings.warn("'inline' not available as pylab backend, "
349 "using 'auto' instead.")
349 "using 'auto' instead.")
350 self.pylab = 'auto'
350 self.pylab = 'auto'
351
351
352 def start(self):
352 def start(self):
353 if self.subapp is not None:
353 if self.subapp is not None:
354 return self.subapp.start()
354 return self.subapp.start()
355 # perform any prexec steps:
355 # perform any prexec steps:
356 if self.interact:
356 if self.interact:
357 self.log.debug("Starting IPython's mainloop...")
357 self.log.debug("Starting IPython's mainloop...")
358 self.shell.mainloop()
358 self.shell.mainloop()
359 else:
359 else:
360 self.log.debug("IPython not interactive...")
360 self.log.debug("IPython not interactive...")
361 if not self.shell.last_execution_succeeded:
361 if not self.shell.last_execution_succeeded:
362 sys.exit(1)
362 sys.exit(1)
363
363
364 def load_default_config(ipython_dir=None):
364 def load_default_config(ipython_dir=None):
365 """Load the default config file from the default ipython_dir.
365 """Load the default config file from the default ipython_dir.
366
366
367 This is useful for embedded shells.
367 This is useful for embedded shells.
368 """
368 """
369 if ipython_dir is None:
369 if ipython_dir is None:
370 ipython_dir = get_ipython_dir()
370 ipython_dir = get_ipython_dir()
371
371
372 profile_dir = os.path.join(ipython_dir, 'profile_default')
372 profile_dir = os.path.join(ipython_dir, 'profile_default')
373 app = TerminalIPythonApp()
373 app = TerminalIPythonApp()
374 app.config_file_paths.append(profile_dir)
374 app.config_file_paths.append(profile_dir)
375 app.load_config_file()
375 app.load_config_file()
376 return app.config
376 return app.config
377
377
378 launch_new_instance = TerminalIPythonApp.launch_instance
378 launch_new_instance = TerminalIPythonApp.launch_instance
379
379
380
380
381 if __name__ == '__main__':
381 if __name__ == '__main__':
382 launch_new_instance()
382 launch_new_instance()
@@ -1,99 +1,113 b''
1 .. _events:
1 .. _events:
2 .. _callbacks:
2 .. _callbacks:
3
3
4 ==============
4 ==============
5 IPython Events
5 IPython Events
6 ==============
6 ==============
7
7
8 Extension code can register callbacks functions which will be called on specific
8 Extension code can register callbacks functions which will be called on specific
9 events within the IPython code. You can see the current list of available
9 events within the IPython code. You can see the current list of available
10 callbacks, and the parameters that will be passed with each, in the callback
10 callbacks, and the parameters that will be passed with each, in the callback
11 prototype functions defined in :mod:`IPython.core.events`.
11 prototype functions defined in :mod:`IPython.core.events`.
12
12
13 To register callbacks, use :meth:`IPython.core.events.EventManager.register`.
13 To register callbacks, use :meth:`IPython.core.events.EventManager.register`.
14 For example::
14 For example::
15
15
16 class VarWatcher(object):
16 class VarWatcher(object):
17 def __init__(self, ip):
17 def __init__(self, ip):
18 self.shell = ip
18 self.shell = ip
19 self.last_x = None
19 self.last_x = None
20
20
21 def pre_execute(self):
21 def pre_execute(self):
22 self.last_x = self.shell.user_ns.get('x', None)
22 self.last_x = self.shell.user_ns.get('x', None)
23
23
24 def pre_run_cell(self, info):
24 def pre_run_cell(self, info):
25 print('Cell code: "%s"' % info.raw_cell)
25 print('info.raw_cell =', info.raw_cell)
26
26 print('info.store_history =', info.store_history)
27 print('info.silent =', info.silent)
28 print('info.shell_futures =', info.shell_futures)
29 print('info.cell_id =', info.cell_id)
30 print(dir(info))
31
27 def post_execute(self):
32 def post_execute(self):
28 if self.shell.user_ns.get('x', None) != self.last_x:
33 if self.shell.user_ns.get('x', None) != self.last_x:
29 print("x changed!")
34 print("x changed!")
30
35
31 def post_run_cell(self, result):
36 def post_run_cell(self, result):
32 print('Cell code: "%s"' % result.info.raw_cell)
37 print('result.execution_count = ', result.execution_count)
33 if result.error_before_exec:
38 print('result.error_before_exec = ', result.error_before_exec)
34 print('Error before execution: %s' % result.error_before_exec)
39 print('result.error_in_exec = ', result.error_in_exec)
35
40 print('result.info = ', result.info)
41 print('result.result = ', result.result)
42
36 def load_ipython_extension(ip):
43 def load_ipython_extension(ip):
37 vw = VarWatcher(ip)
44 vw = VarWatcher(ip)
38 ip.events.register('pre_execute', vw.pre_execute)
45 ip.events.register('pre_execute', vw.pre_execute)
39 ip.events.register('pre_run_cell', vw.pre_run_cell)
46 ip.events.register('pre_run_cell', vw.pre_run_cell)
40 ip.events.register('post_execute', vw.post_execute)
47 ip.events.register('post_execute', vw.post_execute)
41 ip.events.register('post_run_cell', vw.post_run_cell)
48 ip.events.register('post_run_cell', vw.post_run_cell)
42
49
50 .. versionadded:: 8.3
51
52 Since IPython 8.3 and ipykernel 6.12.1, the ``info`` objects in the callback
53 now have a the ``cell_id`` that will be set to the value sent by the
54 frontened, when those send it.
55
56
43
57
44 Events
58 Events
45 ======
59 ======
46
60
47 These are the events IPython will emit. Callbacks will be passed no arguments, unless otherwise specified.
61 These are the events IPython will emit. Callbacks will be passed no arguments, unless otherwise specified.
48
62
49 shell_initialized
63 shell_initialized
50 -----------------
64 -----------------
51
65
52 .. code-block:: python
66 .. code-block:: python
53
67
54 def shell_initialized(ipython):
68 def shell_initialized(ipython):
55 ...
69 ...
56
70
57 This event is triggered only once, at the end of setting up IPython.
71 This event is triggered only once, at the end of setting up IPython.
58 Extensions registered to load by default as part of configuration can use this to execute code to finalize setup.
72 Extensions registered to load by default as part of configuration can use this to execute code to finalize setup.
59 Callbacks will be passed the InteractiveShell instance.
73 Callbacks will be passed the InteractiveShell instance.
60
74
61 pre_run_cell
75 pre_run_cell
62 ------------
76 ------------
63
77
64 ``pre_run_cell`` fires prior to interactive execution (e.g. a cell in a notebook).
78 ``pre_run_cell`` fires prior to interactive execution (e.g. a cell in a notebook).
65 It can be used to note the state prior to execution, and keep track of changes.
79 It can be used to note the state prior to execution, and keep track of changes.
66 An object containing information used for the code execution is provided as an argument.
80 An object containing information used for the code execution is provided as an argument.
67
81
68 pre_execute
82 pre_execute
69 -----------
83 -----------
70
84
71 ``pre_execute`` is like ``pre_run_cell``, but is triggered prior to *any* execution.
85 ``pre_execute`` is like ``pre_run_cell``, but is triggered prior to *any* execution.
72 Sometimes code can be executed by libraries, etc. which
86 Sometimes code can be executed by libraries, etc. which
73 skipping the history/display mechanisms, in which cases ``pre_run_cell`` will not fire.
87 skipping the history/display mechanisms, in which cases ``pre_run_cell`` will not fire.
74
88
75 post_run_cell
89 post_run_cell
76 -------------
90 -------------
77
91
78 ``post_run_cell`` runs after interactive execution (e.g. a cell in a notebook).
92 ``post_run_cell`` runs after interactive execution (e.g. a cell in a notebook).
79 It can be used to cleanup or notify or perform operations on any side effects produced during execution.
93 It can be used to cleanup or notify or perform operations on any side effects produced during execution.
80 For instance, the inline matplotlib backend uses this event to display any figures created but not explicitly displayed during the course of the cell.
94 For instance, the inline matplotlib backend uses this event to display any figures created but not explicitly displayed during the course of the cell.
81 The object which will be returned as the execution result is provided as an
95 The object which will be returned as the execution result is provided as an
82 argument.
96 argument.
83
97
84 post_execute
98 post_execute
85 ------------
99 ------------
86
100
87 The same as ``pre_execute``, ``post_execute`` is like ``post_run_cell``,
101 The same as ``pre_execute``, ``post_execute`` is like ``post_run_cell``,
88 but fires for *all* executions, not just interactive ones.
102 but fires for *all* executions, not just interactive ones.
89
103
90
104
91 .. seealso::
105 .. seealso::
92
106
93 Module :mod:`IPython.core.hooks`
107 Module :mod:`IPython.core.hooks`
94 The older 'hooks' system allows end users to customise some parts of
108 The older 'hooks' system allows end users to customise some parts of
95 IPython's behaviour.
109 IPython's behaviour.
96
110
97 :doc:`inputtransforms`
111 :doc:`inputtransforms`
98 By registering input transformers that don't change code, you can monitor
112 By registering input transformers that don't change code, you can monitor
99 what is being executed.
113 what is being executed.
General Comments 0
You need to be logged in to leave comments. Login now