##// END OF EJS Templates
Add shell.check_complete() method...
Thomas Kluyver -
Show More
@@ -1,3329 +1,3349 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 functools
18 import functools
19 import os
19 import os
20 import re
20 import re
21 import runpy
21 import runpy
22 import sys
22 import sys
23 import tempfile
23 import tempfile
24 import traceback
24 import traceback
25 import types
25 import types
26 import subprocess
26 import subprocess
27 import warnings
27 import warnings
28 from io import open as io_open
28 from io import open as io_open
29
29
30 from pickleshare import PickleShareDB
30 from pickleshare import PickleShareDB
31
31
32 from traitlets.config.configurable import SingletonConfigurable
32 from traitlets.config.configurable import SingletonConfigurable
33 from IPython.core import oinspect
33 from IPython.core import oinspect
34 from IPython.core import magic
34 from IPython.core import magic
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import ultratb
37 from IPython.core import ultratb
38 from IPython.core.alias import Alias, AliasManager
38 from IPython.core.alias import Alias, AliasManager
39 from IPython.core.autocall import ExitAutocall
39 from IPython.core.autocall import ExitAutocall
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.events import EventManager, available_events
41 from IPython.core.events import EventManager, available_events
42 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
42 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
43 from IPython.core.debugger import Pdb
43 from IPython.core.debugger import Pdb
44 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.display_trap import DisplayTrap
45 from IPython.core.displayhook import DisplayHook
45 from IPython.core.displayhook import DisplayHook
46 from IPython.core.displaypub import DisplayPublisher
46 from IPython.core.displaypub import DisplayPublisher
47 from IPython.core.error import InputRejected, UsageError
47 from IPython.core.error import InputRejected, UsageError
48 from IPython.core.extensions import ExtensionManager
48 from IPython.core.extensions import ExtensionManager
49 from IPython.core.formatters import DisplayFormatter
49 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.history import HistoryManager
50 from IPython.core.history import HistoryManager
51 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
51 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.logger import Logger
52 from IPython.core.logger import Logger
53 from IPython.core.macro import Macro
53 from IPython.core.macro import Macro
54 from IPython.core.payload import PayloadManager
54 from IPython.core.payload import PayloadManager
55 from IPython.core.prefilter import PrefilterManager
55 from IPython.core.prefilter import PrefilterManager
56 from IPython.core.profiledir import ProfileDir
56 from IPython.core.profiledir import ProfileDir
57 from IPython.core.usage import default_banner
57 from IPython.core.usage import default_banner
58 from IPython.display import display
58 from IPython.display import display
59 from IPython.testing.skipdoctest import skip_doctest
59 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.utils import PyColorize
60 from IPython.utils import PyColorize
61 from IPython.utils import io
61 from IPython.utils import io
62 from IPython.utils import py3compat
62 from IPython.utils import py3compat
63 from IPython.utils import openpy
63 from IPython.utils import openpy
64 from IPython.utils.decorators import undoc
64 from IPython.utils.decorators import undoc
65 from IPython.utils.io import ask_yes_no
65 from IPython.utils.io import ask_yes_no
66 from IPython.utils.ipstruct import Struct
66 from IPython.utils.ipstruct import Struct
67 from IPython.paths import get_ipython_dir
67 from IPython.paths import get_ipython_dir
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.process import system, getoutput
69 from IPython.utils.process import system, getoutput
70 from IPython.utils.strdispatch import StrDispatch
70 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.syspathcontext import prepended_to_syspath
71 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
72 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
73 from IPython.utils.tempdir import TemporaryDirectory
73 from IPython.utils.tempdir import TemporaryDirectory
74 from traitlets import (
74 from traitlets import (
75 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
75 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
76 observe, default,
76 observe, default,
77 )
77 )
78 from warnings import warn
78 from warnings import warn
79 from logging import error
79 from logging import error
80 import IPython.core.hooks
80 import IPython.core.hooks
81
81
82 from typing import List as ListType
82 from typing import List as ListType
83 from ast import AST
83 from ast import AST
84
84
85 # NoOpContext is deprecated, but ipykernel imports it from here.
85 # NoOpContext is deprecated, but ipykernel imports it from here.
86 # See https://github.com/ipython/ipykernel/issues/157
86 # See https://github.com/ipython/ipykernel/issues/157
87 from IPython.utils.contexts import NoOpContext
87 from IPython.utils.contexts import NoOpContext
88
88
89 try:
89 try:
90 import docrepr.sphinxify as sphx
90 import docrepr.sphinxify as sphx
91
91
92 def sphinxify(doc):
92 def sphinxify(doc):
93 with TemporaryDirectory() as dirname:
93 with TemporaryDirectory() as dirname:
94 return {
94 return {
95 'text/html': sphx.sphinxify(doc, dirname),
95 'text/html': sphx.sphinxify(doc, dirname),
96 'text/plain': doc
96 'text/plain': doc
97 }
97 }
98 except ImportError:
98 except ImportError:
99 sphinxify = None
99 sphinxify = None
100
100
101
101
102 class ProvisionalWarning(DeprecationWarning):
102 class ProvisionalWarning(DeprecationWarning):
103 """
103 """
104 Warning class for unstable features
104 Warning class for unstable features
105 """
105 """
106 pass
106 pass
107
107
108 if sys.version_info > (3,6):
108 if sys.version_info > (3,6):
109 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
109 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
110 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
110 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
111 else:
111 else:
112 _assign_nodes = (ast.AugAssign, ast.Assign )
112 _assign_nodes = (ast.AugAssign, ast.Assign )
113 _single_targets_nodes = (ast.AugAssign, )
113 _single_targets_nodes = (ast.AugAssign, )
114
114
115 #-----------------------------------------------------------------------------
115 #-----------------------------------------------------------------------------
116 # Globals
116 # Globals
117 #-----------------------------------------------------------------------------
117 #-----------------------------------------------------------------------------
118
118
119 # compiled regexps for autoindent management
119 # compiled regexps for autoindent management
120 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
120 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
121
121
122 #-----------------------------------------------------------------------------
122 #-----------------------------------------------------------------------------
123 # Utilities
123 # Utilities
124 #-----------------------------------------------------------------------------
124 #-----------------------------------------------------------------------------
125
125
126 @undoc
126 @undoc
127 def softspace(file, newvalue):
127 def softspace(file, newvalue):
128 """Copied from code.py, to remove the dependency"""
128 """Copied from code.py, to remove the dependency"""
129
129
130 oldvalue = 0
130 oldvalue = 0
131 try:
131 try:
132 oldvalue = file.softspace
132 oldvalue = file.softspace
133 except AttributeError:
133 except AttributeError:
134 pass
134 pass
135 try:
135 try:
136 file.softspace = newvalue
136 file.softspace = newvalue
137 except (AttributeError, TypeError):
137 except (AttributeError, TypeError):
138 # "attribute-less object" or "read-only attributes"
138 # "attribute-less object" or "read-only attributes"
139 pass
139 pass
140 return oldvalue
140 return oldvalue
141
141
142 @undoc
142 @undoc
143 def no_op(*a, **kw):
143 def no_op(*a, **kw):
144 pass
144 pass
145
145
146
146
147 class SpaceInInput(Exception): pass
147 class SpaceInInput(Exception): pass
148
148
149
149
150 def get_default_colors():
150 def get_default_colors():
151 "DEPRECATED"
151 "DEPRECATED"
152 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
152 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
153 DeprecationWarning, stacklevel=2)
153 DeprecationWarning, stacklevel=2)
154 return 'Neutral'
154 return 'Neutral'
155
155
156
156
157 class SeparateUnicode(Unicode):
157 class SeparateUnicode(Unicode):
158 r"""A Unicode subclass to validate separate_in, separate_out, etc.
158 r"""A Unicode subclass to validate separate_in, separate_out, etc.
159
159
160 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
160 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
161 """
161 """
162
162
163 def validate(self, obj, value):
163 def validate(self, obj, value):
164 if value == '0': value = ''
164 if value == '0': value = ''
165 value = value.replace('\\n','\n')
165 value = value.replace('\\n','\n')
166 return super(SeparateUnicode, self).validate(obj, value)
166 return super(SeparateUnicode, self).validate(obj, value)
167
167
168
168
169 @undoc
169 @undoc
170 class DummyMod(object):
170 class DummyMod(object):
171 """A dummy module used for IPython's interactive module when
171 """A dummy module used for IPython's interactive module when
172 a namespace must be assigned to the module's __dict__."""
172 a namespace must be assigned to the module's __dict__."""
173 pass
173 pass
174
174
175
175
176 class ExecutionInfo(object):
176 class ExecutionInfo(object):
177 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
177 """The arguments used for a call to :meth:`InteractiveShell.run_cell`
178
178
179 Stores information about what is going to happen.
179 Stores information about what is going to happen.
180 """
180 """
181 raw_cell = None
181 raw_cell = None
182 store_history = False
182 store_history = False
183 silent = False
183 silent = False
184 shell_futures = True
184 shell_futures = True
185
185
186 def __init__(self, raw_cell, store_history, silent, shell_futures):
186 def __init__(self, raw_cell, store_history, silent, shell_futures):
187 self.raw_cell = raw_cell
187 self.raw_cell = raw_cell
188 self.store_history = store_history
188 self.store_history = store_history
189 self.silent = silent
189 self.silent = silent
190 self.shell_futures = shell_futures
190 self.shell_futures = shell_futures
191
191
192 def __repr__(self):
192 def __repr__(self):
193 name = self.__class__.__qualname__
193 name = self.__class__.__qualname__
194 raw_cell = ((self.raw_cell[:50] + '..')
194 raw_cell = ((self.raw_cell[:50] + '..')
195 if len(self.raw_cell) > 50 else self.raw_cell)
195 if len(self.raw_cell) > 50 else self.raw_cell)
196 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
196 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
197 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
197 (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
198
198
199
199
200 class ExecutionResult(object):
200 class ExecutionResult(object):
201 """The result of a call to :meth:`InteractiveShell.run_cell`
201 """The result of a call to :meth:`InteractiveShell.run_cell`
202
202
203 Stores information about what took place.
203 Stores information about what took place.
204 """
204 """
205 execution_count = None
205 execution_count = None
206 error_before_exec = None
206 error_before_exec = None
207 error_in_exec = None
207 error_in_exec = None
208 info = None
208 info = None
209 result = None
209 result = None
210
210
211 def __init__(self, info):
211 def __init__(self, info):
212 self.info = info
212 self.info = info
213
213
214 @property
214 @property
215 def success(self):
215 def success(self):
216 return (self.error_before_exec is None) and (self.error_in_exec is None)
216 return (self.error_before_exec is None) and (self.error_in_exec is None)
217
217
218 def raise_error(self):
218 def raise_error(self):
219 """Reraises error if `success` is `False`, otherwise does nothing"""
219 """Reraises error if `success` is `False`, otherwise does nothing"""
220 if self.error_before_exec is not None:
220 if self.error_before_exec is not None:
221 raise self.error_before_exec
221 raise self.error_before_exec
222 if self.error_in_exec is not None:
222 if self.error_in_exec is not None:
223 raise self.error_in_exec
223 raise self.error_in_exec
224
224
225 def __repr__(self):
225 def __repr__(self):
226 name = self.__class__.__qualname__
226 name = self.__class__.__qualname__
227 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
227 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
228 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
228 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
229
229
230
230
231 class InteractiveShell(SingletonConfigurable):
231 class InteractiveShell(SingletonConfigurable):
232 """An enhanced, interactive shell for Python."""
232 """An enhanced, interactive shell for Python."""
233
233
234 _instance = None
234 _instance = None
235
235
236 ast_transformers = List([], help=
236 ast_transformers = List([], help=
237 """
237 """
238 A list of ast.NodeTransformer subclass instances, which will be applied
238 A list of ast.NodeTransformer subclass instances, which will be applied
239 to user input before code is run.
239 to user input before code is run.
240 """
240 """
241 ).tag(config=True)
241 ).tag(config=True)
242
242
243 autocall = Enum((0,1,2), default_value=0, help=
243 autocall = Enum((0,1,2), default_value=0, help=
244 """
244 """
245 Make IPython automatically call any callable object even if you didn't
245 Make IPython automatically call any callable object even if you didn't
246 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
246 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
247 automatically. The value can be '0' to disable the feature, '1' for
247 automatically. The value can be '0' to disable the feature, '1' for
248 'smart' autocall, where it is not applied if there are no more
248 'smart' autocall, where it is not applied if there are no more
249 arguments on the line, and '2' for 'full' autocall, where all callable
249 arguments on the line, and '2' for 'full' autocall, where all callable
250 objects are automatically called (even if no arguments are present).
250 objects are automatically called (even if no arguments are present).
251 """
251 """
252 ).tag(config=True)
252 ).tag(config=True)
253 # TODO: remove all autoindent logic and put into frontends.
253 # TODO: remove all autoindent logic and put into frontends.
254 # We can't do this yet because even runlines uses the autoindent.
254 # We can't do this yet because even runlines uses the autoindent.
255 autoindent = Bool(True, help=
255 autoindent = Bool(True, help=
256 """
256 """
257 Autoindent IPython code entered interactively.
257 Autoindent IPython code entered interactively.
258 """
258 """
259 ).tag(config=True)
259 ).tag(config=True)
260
260
261 automagic = Bool(True, help=
261 automagic = Bool(True, help=
262 """
262 """
263 Enable magic commands to be called without the leading %.
263 Enable magic commands to be called without the leading %.
264 """
264 """
265 ).tag(config=True)
265 ).tag(config=True)
266
266
267 banner1 = Unicode(default_banner,
267 banner1 = Unicode(default_banner,
268 help="""The part of the banner to be printed before the profile"""
268 help="""The part of the banner to be printed before the profile"""
269 ).tag(config=True)
269 ).tag(config=True)
270 banner2 = Unicode('',
270 banner2 = Unicode('',
271 help="""The part of the banner to be printed after the profile"""
271 help="""The part of the banner to be printed after the profile"""
272 ).tag(config=True)
272 ).tag(config=True)
273
273
274 cache_size = Integer(1000, help=
274 cache_size = Integer(1000, help=
275 """
275 """
276 Set the size of the output cache. The default is 1000, you can
276 Set the size of the output cache. The default is 1000, you can
277 change it permanently in your config file. Setting it to 0 completely
277 change it permanently in your config file. Setting it to 0 completely
278 disables the caching system, and the minimum value accepted is 3 (if
278 disables the caching system, and the minimum value accepted is 3 (if
279 you provide a value less than 3, it is reset to 0 and a warning is
279 you provide a value less than 3, it is reset to 0 and a warning is
280 issued). This limit is defined because otherwise you'll spend more
280 issued). This limit is defined because otherwise you'll spend more
281 time re-flushing a too small cache than working
281 time re-flushing a too small cache than working
282 """
282 """
283 ).tag(config=True)
283 ).tag(config=True)
284 color_info = Bool(True, help=
284 color_info = Bool(True, help=
285 """
285 """
286 Use colors for displaying information about objects. Because this
286 Use colors for displaying information about objects. Because this
287 information is passed through a pager (like 'less'), and some pagers
287 information is passed through a pager (like 'less'), and some pagers
288 get confused with color codes, this capability can be turned off.
288 get confused with color codes, this capability can be turned off.
289 """
289 """
290 ).tag(config=True)
290 ).tag(config=True)
291 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
291 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
292 default_value='Neutral',
292 default_value='Neutral',
293 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
293 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
294 ).tag(config=True)
294 ).tag(config=True)
295 debug = Bool(False).tag(config=True)
295 debug = Bool(False).tag(config=True)
296 disable_failing_post_execute = Bool(False,
296 disable_failing_post_execute = Bool(False,
297 help="Don't call post-execute functions that have failed in the past."
297 help="Don't call post-execute functions that have failed in the past."
298 ).tag(config=True)
298 ).tag(config=True)
299 display_formatter = Instance(DisplayFormatter, allow_none=True)
299 display_formatter = Instance(DisplayFormatter, allow_none=True)
300 displayhook_class = Type(DisplayHook)
300 displayhook_class = Type(DisplayHook)
301 display_pub_class = Type(DisplayPublisher)
301 display_pub_class = Type(DisplayPublisher)
302
302
303 sphinxify_docstring = Bool(False, help=
303 sphinxify_docstring = Bool(False, help=
304 """
304 """
305 Enables rich html representation of docstrings. (This requires the
305 Enables rich html representation of docstrings. (This requires the
306 docrepr module).
306 docrepr module).
307 """).tag(config=True)
307 """).tag(config=True)
308
308
309 @observe("sphinxify_docstring")
309 @observe("sphinxify_docstring")
310 def _sphinxify_docstring_changed(self, change):
310 def _sphinxify_docstring_changed(self, change):
311 if change['new']:
311 if change['new']:
312 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
312 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
313
313
314 enable_html_pager = Bool(False, help=
314 enable_html_pager = Bool(False, help=
315 """
315 """
316 (Provisional API) enables html representation in mime bundles sent
316 (Provisional API) enables html representation in mime bundles sent
317 to pagers.
317 to pagers.
318 """).tag(config=True)
318 """).tag(config=True)
319
319
320 @observe("enable_html_pager")
320 @observe("enable_html_pager")
321 def _enable_html_pager_changed(self, change):
321 def _enable_html_pager_changed(self, change):
322 if change['new']:
322 if change['new']:
323 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
323 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
324
324
325 data_pub_class = None
325 data_pub_class = None
326
326
327 exit_now = Bool(False)
327 exit_now = Bool(False)
328 exiter = Instance(ExitAutocall)
328 exiter = Instance(ExitAutocall)
329 @default('exiter')
329 @default('exiter')
330 def _exiter_default(self):
330 def _exiter_default(self):
331 return ExitAutocall(self)
331 return ExitAutocall(self)
332 # Monotonically increasing execution counter
332 # Monotonically increasing execution counter
333 execution_count = Integer(1)
333 execution_count = Integer(1)
334 filename = Unicode("<ipython console>")
334 filename = Unicode("<ipython console>")
335 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
335 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
336
336
337 # Used to transform cells before running them, and check whether code is complete
337 # Used to transform cells before running them, and check whether code is complete
338 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
338 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
339 ())
339 ())
340
340
341 @property
341 @property
342 def input_splitter(self):
342 def input_splitter(self):
343 """Make this available for compatibility
343 """Make this available for compatibility
344
344
345 ipykernel currently uses shell.input_splitter.check_complete
345 ipykernel currently uses shell.input_splitter.check_complete
346 """
346 """
347 return self.input_transformer_manager
347 return self.input_transformer_manager
348
348
349 logstart = Bool(False, help=
349 logstart = Bool(False, help=
350 """
350 """
351 Start logging to the default log file in overwrite mode.
351 Start logging to the default log file in overwrite mode.
352 Use `logappend` to specify a log file to **append** logs to.
352 Use `logappend` to specify a log file to **append** logs to.
353 """
353 """
354 ).tag(config=True)
354 ).tag(config=True)
355 logfile = Unicode('', help=
355 logfile = Unicode('', help=
356 """
356 """
357 The name of the logfile to use.
357 The name of the logfile to use.
358 """
358 """
359 ).tag(config=True)
359 ).tag(config=True)
360 logappend = Unicode('', help=
360 logappend = Unicode('', help=
361 """
361 """
362 Start logging to the given file in append mode.
362 Start logging to the given file in append mode.
363 Use `logfile` to specify a log file to **overwrite** logs to.
363 Use `logfile` to specify a log file to **overwrite** logs to.
364 """
364 """
365 ).tag(config=True)
365 ).tag(config=True)
366 object_info_string_level = Enum((0,1,2), default_value=0,
366 object_info_string_level = Enum((0,1,2), default_value=0,
367 ).tag(config=True)
367 ).tag(config=True)
368 pdb = Bool(False, help=
368 pdb = Bool(False, help=
369 """
369 """
370 Automatically call the pdb debugger after every exception.
370 Automatically call the pdb debugger after every exception.
371 """
371 """
372 ).tag(config=True)
372 ).tag(config=True)
373 display_page = Bool(False,
373 display_page = Bool(False,
374 help="""If True, anything that would be passed to the pager
374 help="""If True, anything that would be passed to the pager
375 will be displayed as regular output instead."""
375 will be displayed as regular output instead."""
376 ).tag(config=True)
376 ).tag(config=True)
377
377
378 # deprecated prompt traits:
378 # deprecated prompt traits:
379
379
380 prompt_in1 = Unicode('In [\\#]: ',
380 prompt_in1 = Unicode('In [\\#]: ',
381 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
381 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
382 ).tag(config=True)
382 ).tag(config=True)
383 prompt_in2 = Unicode(' .\\D.: ',
383 prompt_in2 = Unicode(' .\\D.: ',
384 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
384 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
385 ).tag(config=True)
385 ).tag(config=True)
386 prompt_out = Unicode('Out[\\#]: ',
386 prompt_out = Unicode('Out[\\#]: ',
387 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
387 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
388 ).tag(config=True)
388 ).tag(config=True)
389 prompts_pad_left = Bool(True,
389 prompts_pad_left = Bool(True,
390 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
390 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
391 ).tag(config=True)
391 ).tag(config=True)
392
392
393 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
393 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
394 def _prompt_trait_changed(self, change):
394 def _prompt_trait_changed(self, change):
395 name = change['name']
395 name = change['name']
396 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
396 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
397 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
397 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
398 " object directly.".format(name=name))
398 " object directly.".format(name=name))
399
399
400 # protect against weird cases where self.config may not exist:
400 # protect against weird cases where self.config may not exist:
401
401
402 show_rewritten_input = Bool(True,
402 show_rewritten_input = Bool(True,
403 help="Show rewritten input, e.g. for autocall."
403 help="Show rewritten input, e.g. for autocall."
404 ).tag(config=True)
404 ).tag(config=True)
405
405
406 quiet = Bool(False).tag(config=True)
406 quiet = Bool(False).tag(config=True)
407
407
408 history_length = Integer(10000,
408 history_length = Integer(10000,
409 help='Total length of command history'
409 help='Total length of command history'
410 ).tag(config=True)
410 ).tag(config=True)
411
411
412 history_load_length = Integer(1000, help=
412 history_load_length = Integer(1000, help=
413 """
413 """
414 The number of saved history entries to be loaded
414 The number of saved history entries to be loaded
415 into the history buffer at startup.
415 into the history buffer at startup.
416 """
416 """
417 ).tag(config=True)
417 ).tag(config=True)
418
418
419 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
419 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
420 default_value='last_expr',
420 default_value='last_expr',
421 help="""
421 help="""
422 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
422 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
423 which nodes should be run interactively (displaying output from expressions).
423 which nodes should be run interactively (displaying output from expressions).
424 """
424 """
425 ).tag(config=True)
425 ).tag(config=True)
426
426
427 # TODO: this part of prompt management should be moved to the frontends.
427 # TODO: this part of prompt management should be moved to the frontends.
428 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
428 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
429 separate_in = SeparateUnicode('\n').tag(config=True)
429 separate_in = SeparateUnicode('\n').tag(config=True)
430 separate_out = SeparateUnicode('').tag(config=True)
430 separate_out = SeparateUnicode('').tag(config=True)
431 separate_out2 = SeparateUnicode('').tag(config=True)
431 separate_out2 = SeparateUnicode('').tag(config=True)
432 wildcards_case_sensitive = Bool(True).tag(config=True)
432 wildcards_case_sensitive = Bool(True).tag(config=True)
433 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
433 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
434 default_value='Context',
434 default_value='Context',
435 help="Switch modes for the IPython exception handlers."
435 help="Switch modes for the IPython exception handlers."
436 ).tag(config=True)
436 ).tag(config=True)
437
437
438 # Subcomponents of InteractiveShell
438 # Subcomponents of InteractiveShell
439 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
439 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
440 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
440 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
441 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
441 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
442 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
442 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
443 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
443 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
444 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
444 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
445 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
445 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
446 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
446 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
447
447
448 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
448 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
449 @property
449 @property
450 def profile(self):
450 def profile(self):
451 if self.profile_dir is not None:
451 if self.profile_dir is not None:
452 name = os.path.basename(self.profile_dir.location)
452 name = os.path.basename(self.profile_dir.location)
453 return name.replace('profile_','')
453 return name.replace('profile_','')
454
454
455
455
456 # Private interface
456 # Private interface
457 _post_execute = Dict()
457 _post_execute = Dict()
458
458
459 # Tracks any GUI loop loaded for pylab
459 # Tracks any GUI loop loaded for pylab
460 pylab_gui_select = None
460 pylab_gui_select = None
461
461
462 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
462 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
463
463
464 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
464 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
465
465
466 def __init__(self, ipython_dir=None, profile_dir=None,
466 def __init__(self, ipython_dir=None, profile_dir=None,
467 user_module=None, user_ns=None,
467 user_module=None, user_ns=None,
468 custom_exceptions=((), None), **kwargs):
468 custom_exceptions=((), None), **kwargs):
469
469
470 # This is where traits with a config_key argument are updated
470 # This is where traits with a config_key argument are updated
471 # from the values on config.
471 # from the values on config.
472 super(InteractiveShell, self).__init__(**kwargs)
472 super(InteractiveShell, self).__init__(**kwargs)
473 if 'PromptManager' in self.config:
473 if 'PromptManager' in self.config:
474 warn('As of IPython 5.0 `PromptManager` config will have no effect'
474 warn('As of IPython 5.0 `PromptManager` config will have no effect'
475 ' and has been replaced by TerminalInteractiveShell.prompts_class')
475 ' and has been replaced by TerminalInteractiveShell.prompts_class')
476 self.configurables = [self]
476 self.configurables = [self]
477
477
478 # These are relatively independent and stateless
478 # These are relatively independent and stateless
479 self.init_ipython_dir(ipython_dir)
479 self.init_ipython_dir(ipython_dir)
480 self.init_profile_dir(profile_dir)
480 self.init_profile_dir(profile_dir)
481 self.init_instance_attrs()
481 self.init_instance_attrs()
482 self.init_environment()
482 self.init_environment()
483
483
484 # Check if we're in a virtualenv, and set up sys.path.
484 # Check if we're in a virtualenv, and set up sys.path.
485 self.init_virtualenv()
485 self.init_virtualenv()
486
486
487 # Create namespaces (user_ns, user_global_ns, etc.)
487 # Create namespaces (user_ns, user_global_ns, etc.)
488 self.init_create_namespaces(user_module, user_ns)
488 self.init_create_namespaces(user_module, user_ns)
489 # This has to be done after init_create_namespaces because it uses
489 # This has to be done after init_create_namespaces because it uses
490 # something in self.user_ns, but before init_sys_modules, which
490 # something in self.user_ns, but before init_sys_modules, which
491 # is the first thing to modify sys.
491 # is the first thing to modify sys.
492 # TODO: When we override sys.stdout and sys.stderr before this class
492 # TODO: When we override sys.stdout and sys.stderr before this class
493 # is created, we are saving the overridden ones here. Not sure if this
493 # is created, we are saving the overridden ones here. Not sure if this
494 # is what we want to do.
494 # is what we want to do.
495 self.save_sys_module_state()
495 self.save_sys_module_state()
496 self.init_sys_modules()
496 self.init_sys_modules()
497
497
498 # While we're trying to have each part of the code directly access what
498 # While we're trying to have each part of the code directly access what
499 # it needs without keeping redundant references to objects, we have too
499 # it needs without keeping redundant references to objects, we have too
500 # much legacy code that expects ip.db to exist.
500 # much legacy code that expects ip.db to exist.
501 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
501 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
502
502
503 self.init_history()
503 self.init_history()
504 self.init_encoding()
504 self.init_encoding()
505 self.init_prefilter()
505 self.init_prefilter()
506
506
507 self.init_syntax_highlighting()
507 self.init_syntax_highlighting()
508 self.init_hooks()
508 self.init_hooks()
509 self.init_events()
509 self.init_events()
510 self.init_pushd_popd_magic()
510 self.init_pushd_popd_magic()
511 self.init_user_ns()
511 self.init_user_ns()
512 self.init_logger()
512 self.init_logger()
513 self.init_builtins()
513 self.init_builtins()
514
514
515 # The following was in post_config_initialization
515 # The following was in post_config_initialization
516 self.init_inspector()
516 self.init_inspector()
517 self.raw_input_original = input
517 self.raw_input_original = input
518 self.init_completer()
518 self.init_completer()
519 # TODO: init_io() needs to happen before init_traceback handlers
519 # TODO: init_io() needs to happen before init_traceback handlers
520 # because the traceback handlers hardcode the stdout/stderr streams.
520 # because the traceback handlers hardcode the stdout/stderr streams.
521 # This logic in in debugger.Pdb and should eventually be changed.
521 # This logic in in debugger.Pdb and should eventually be changed.
522 self.init_io()
522 self.init_io()
523 self.init_traceback_handlers(custom_exceptions)
523 self.init_traceback_handlers(custom_exceptions)
524 self.init_prompts()
524 self.init_prompts()
525 self.init_display_formatter()
525 self.init_display_formatter()
526 self.init_display_pub()
526 self.init_display_pub()
527 self.init_data_pub()
527 self.init_data_pub()
528 self.init_displayhook()
528 self.init_displayhook()
529 self.init_magics()
529 self.init_magics()
530 self.init_alias()
530 self.init_alias()
531 self.init_logstart()
531 self.init_logstart()
532 self.init_pdb()
532 self.init_pdb()
533 self.init_extension_manager()
533 self.init_extension_manager()
534 self.init_payload()
534 self.init_payload()
535 self.init_deprecation_warnings()
535 self.init_deprecation_warnings()
536 self.hooks.late_startup_hook()
536 self.hooks.late_startup_hook()
537 self.events.trigger('shell_initialized', self)
537 self.events.trigger('shell_initialized', self)
538 atexit.register(self.atexit_operations)
538 atexit.register(self.atexit_operations)
539
539
540 def get_ipython(self):
540 def get_ipython(self):
541 """Return the currently running IPython instance."""
541 """Return the currently running IPython instance."""
542 return self
542 return self
543
543
544 #-------------------------------------------------------------------------
544 #-------------------------------------------------------------------------
545 # Trait changed handlers
545 # Trait changed handlers
546 #-------------------------------------------------------------------------
546 #-------------------------------------------------------------------------
547 @observe('ipython_dir')
547 @observe('ipython_dir')
548 def _ipython_dir_changed(self, change):
548 def _ipython_dir_changed(self, change):
549 ensure_dir_exists(change['new'])
549 ensure_dir_exists(change['new'])
550
550
551 def set_autoindent(self,value=None):
551 def set_autoindent(self,value=None):
552 """Set the autoindent flag.
552 """Set the autoindent flag.
553
553
554 If called with no arguments, it acts as a toggle."""
554 If called with no arguments, it acts as a toggle."""
555 if value is None:
555 if value is None:
556 self.autoindent = not self.autoindent
556 self.autoindent = not self.autoindent
557 else:
557 else:
558 self.autoindent = value
558 self.autoindent = value
559
559
560 #-------------------------------------------------------------------------
560 #-------------------------------------------------------------------------
561 # init_* methods called by __init__
561 # init_* methods called by __init__
562 #-------------------------------------------------------------------------
562 #-------------------------------------------------------------------------
563
563
564 def init_ipython_dir(self, ipython_dir):
564 def init_ipython_dir(self, ipython_dir):
565 if ipython_dir is not None:
565 if ipython_dir is not None:
566 self.ipython_dir = ipython_dir
566 self.ipython_dir = ipython_dir
567 return
567 return
568
568
569 self.ipython_dir = get_ipython_dir()
569 self.ipython_dir = get_ipython_dir()
570
570
571 def init_profile_dir(self, profile_dir):
571 def init_profile_dir(self, profile_dir):
572 if profile_dir is not None:
572 if profile_dir is not None:
573 self.profile_dir = profile_dir
573 self.profile_dir = profile_dir
574 return
574 return
575 self.profile_dir =\
575 self.profile_dir =\
576 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
576 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
577
577
578 def init_instance_attrs(self):
578 def init_instance_attrs(self):
579 self.more = False
579 self.more = False
580
580
581 # command compiler
581 # command compiler
582 self.compile = CachingCompiler()
582 self.compile = CachingCompiler()
583
583
584 # Make an empty namespace, which extension writers can rely on both
584 # Make an empty namespace, which extension writers can rely on both
585 # existing and NEVER being used by ipython itself. This gives them a
585 # existing and NEVER being used by ipython itself. This gives them a
586 # convenient location for storing additional information and state
586 # convenient location for storing additional information and state
587 # their extensions may require, without fear of collisions with other
587 # their extensions may require, without fear of collisions with other
588 # ipython names that may develop later.
588 # ipython names that may develop later.
589 self.meta = Struct()
589 self.meta = Struct()
590
590
591 # Temporary files used for various purposes. Deleted at exit.
591 # Temporary files used for various purposes. Deleted at exit.
592 self.tempfiles = []
592 self.tempfiles = []
593 self.tempdirs = []
593 self.tempdirs = []
594
594
595 # keep track of where we started running (mainly for crash post-mortem)
595 # keep track of where we started running (mainly for crash post-mortem)
596 # This is not being used anywhere currently.
596 # This is not being used anywhere currently.
597 self.starting_dir = os.getcwd()
597 self.starting_dir = os.getcwd()
598
598
599 # Indentation management
599 # Indentation management
600 self.indent_current_nsp = 0
600 self.indent_current_nsp = 0
601
601
602 # Dict to track post-execution functions that have been registered
602 # Dict to track post-execution functions that have been registered
603 self._post_execute = {}
603 self._post_execute = {}
604
604
605 def init_environment(self):
605 def init_environment(self):
606 """Any changes we need to make to the user's environment."""
606 """Any changes we need to make to the user's environment."""
607 pass
607 pass
608
608
609 def init_encoding(self):
609 def init_encoding(self):
610 # Get system encoding at startup time. Certain terminals (like Emacs
610 # Get system encoding at startup time. Certain terminals (like Emacs
611 # under Win32 have it set to None, and we need to have a known valid
611 # under Win32 have it set to None, and we need to have a known valid
612 # encoding to use in the raw_input() method
612 # encoding to use in the raw_input() method
613 try:
613 try:
614 self.stdin_encoding = sys.stdin.encoding or 'ascii'
614 self.stdin_encoding = sys.stdin.encoding or 'ascii'
615 except AttributeError:
615 except AttributeError:
616 self.stdin_encoding = 'ascii'
616 self.stdin_encoding = 'ascii'
617
617
618
618
619 @observe('colors')
619 @observe('colors')
620 def init_syntax_highlighting(self, changes=None):
620 def init_syntax_highlighting(self, changes=None):
621 # Python source parser/formatter for syntax highlighting
621 # Python source parser/formatter for syntax highlighting
622 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
622 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
623 self.pycolorize = lambda src: pyformat(src,'str')
623 self.pycolorize = lambda src: pyformat(src,'str')
624
624
625 def refresh_style(self):
625 def refresh_style(self):
626 # No-op here, used in subclass
626 # No-op here, used in subclass
627 pass
627 pass
628
628
629 def init_pushd_popd_magic(self):
629 def init_pushd_popd_magic(self):
630 # for pushd/popd management
630 # for pushd/popd management
631 self.home_dir = get_home_dir()
631 self.home_dir = get_home_dir()
632
632
633 self.dir_stack = []
633 self.dir_stack = []
634
634
635 def init_logger(self):
635 def init_logger(self):
636 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
636 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
637 logmode='rotate')
637 logmode='rotate')
638
638
639 def init_logstart(self):
639 def init_logstart(self):
640 """Initialize logging in case it was requested at the command line.
640 """Initialize logging in case it was requested at the command line.
641 """
641 """
642 if self.logappend:
642 if self.logappend:
643 self.magic('logstart %s append' % self.logappend)
643 self.magic('logstart %s append' % self.logappend)
644 elif self.logfile:
644 elif self.logfile:
645 self.magic('logstart %s' % self.logfile)
645 self.magic('logstart %s' % self.logfile)
646 elif self.logstart:
646 elif self.logstart:
647 self.magic('logstart')
647 self.magic('logstart')
648
648
649 def init_deprecation_warnings(self):
649 def init_deprecation_warnings(self):
650 """
650 """
651 register default filter for deprecation warning.
651 register default filter for deprecation warning.
652
652
653 This will allow deprecation warning of function used interactively to show
653 This will allow deprecation warning of function used interactively to show
654 warning to users, and still hide deprecation warning from libraries import.
654 warning to users, and still hide deprecation warning from libraries import.
655 """
655 """
656 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
656 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
657
657
658 def init_builtins(self):
658 def init_builtins(self):
659 # A single, static flag that we set to True. Its presence indicates
659 # A single, static flag that we set to True. Its presence indicates
660 # that an IPython shell has been created, and we make no attempts at
660 # that an IPython shell has been created, and we make no attempts at
661 # removing on exit or representing the existence of more than one
661 # removing on exit or representing the existence of more than one
662 # IPython at a time.
662 # IPython at a time.
663 builtin_mod.__dict__['__IPYTHON__'] = True
663 builtin_mod.__dict__['__IPYTHON__'] = True
664 builtin_mod.__dict__['display'] = display
664 builtin_mod.__dict__['display'] = display
665
665
666 self.builtin_trap = BuiltinTrap(shell=self)
666 self.builtin_trap = BuiltinTrap(shell=self)
667
667
668 @observe('colors')
668 @observe('colors')
669 def init_inspector(self, changes=None):
669 def init_inspector(self, changes=None):
670 # Object inspector
670 # Object inspector
671 self.inspector = oinspect.Inspector(oinspect.InspectColors,
671 self.inspector = oinspect.Inspector(oinspect.InspectColors,
672 PyColorize.ANSICodeColors,
672 PyColorize.ANSICodeColors,
673 self.colors,
673 self.colors,
674 self.object_info_string_level)
674 self.object_info_string_level)
675
675
676 def init_io(self):
676 def init_io(self):
677 # This will just use sys.stdout and sys.stderr. If you want to
677 # This will just use sys.stdout and sys.stderr. If you want to
678 # override sys.stdout and sys.stderr themselves, you need to do that
678 # override sys.stdout and sys.stderr themselves, you need to do that
679 # *before* instantiating this class, because io holds onto
679 # *before* instantiating this class, because io holds onto
680 # references to the underlying streams.
680 # references to the underlying streams.
681 # io.std* are deprecated, but don't show our own deprecation warnings
681 # io.std* are deprecated, but don't show our own deprecation warnings
682 # during initialization of the deprecated API.
682 # during initialization of the deprecated API.
683 with warnings.catch_warnings():
683 with warnings.catch_warnings():
684 warnings.simplefilter('ignore', DeprecationWarning)
684 warnings.simplefilter('ignore', DeprecationWarning)
685 io.stdout = io.IOStream(sys.stdout)
685 io.stdout = io.IOStream(sys.stdout)
686 io.stderr = io.IOStream(sys.stderr)
686 io.stderr = io.IOStream(sys.stderr)
687
687
688 def init_prompts(self):
688 def init_prompts(self):
689 # Set system prompts, so that scripts can decide if they are running
689 # Set system prompts, so that scripts can decide if they are running
690 # interactively.
690 # interactively.
691 sys.ps1 = 'In : '
691 sys.ps1 = 'In : '
692 sys.ps2 = '...: '
692 sys.ps2 = '...: '
693 sys.ps3 = 'Out: '
693 sys.ps3 = 'Out: '
694
694
695 def init_display_formatter(self):
695 def init_display_formatter(self):
696 self.display_formatter = DisplayFormatter(parent=self)
696 self.display_formatter = DisplayFormatter(parent=self)
697 self.configurables.append(self.display_formatter)
697 self.configurables.append(self.display_formatter)
698
698
699 def init_display_pub(self):
699 def init_display_pub(self):
700 self.display_pub = self.display_pub_class(parent=self)
700 self.display_pub = self.display_pub_class(parent=self)
701 self.configurables.append(self.display_pub)
701 self.configurables.append(self.display_pub)
702
702
703 def init_data_pub(self):
703 def init_data_pub(self):
704 if not self.data_pub_class:
704 if not self.data_pub_class:
705 self.data_pub = None
705 self.data_pub = None
706 return
706 return
707 self.data_pub = self.data_pub_class(parent=self)
707 self.data_pub = self.data_pub_class(parent=self)
708 self.configurables.append(self.data_pub)
708 self.configurables.append(self.data_pub)
709
709
710 def init_displayhook(self):
710 def init_displayhook(self):
711 # Initialize displayhook, set in/out prompts and printing system
711 # Initialize displayhook, set in/out prompts and printing system
712 self.displayhook = self.displayhook_class(
712 self.displayhook = self.displayhook_class(
713 parent=self,
713 parent=self,
714 shell=self,
714 shell=self,
715 cache_size=self.cache_size,
715 cache_size=self.cache_size,
716 )
716 )
717 self.configurables.append(self.displayhook)
717 self.configurables.append(self.displayhook)
718 # This is a context manager that installs/revmoes the displayhook at
718 # This is a context manager that installs/revmoes the displayhook at
719 # the appropriate time.
719 # the appropriate time.
720 self.display_trap = DisplayTrap(hook=self.displayhook)
720 self.display_trap = DisplayTrap(hook=self.displayhook)
721
721
722 def init_virtualenv(self):
722 def init_virtualenv(self):
723 """Add a virtualenv to sys.path so the user can import modules from it.
723 """Add a virtualenv to sys.path so the user can import modules from it.
724 This isn't perfect: it doesn't use the Python interpreter with which the
724 This isn't perfect: it doesn't use the Python interpreter with which the
725 virtualenv was built, and it ignores the --no-site-packages option. A
725 virtualenv was built, and it ignores the --no-site-packages option. A
726 warning will appear suggesting the user installs IPython in the
726 warning will appear suggesting the user installs IPython in the
727 virtualenv, but for many cases, it probably works well enough.
727 virtualenv, but for many cases, it probably works well enough.
728
728
729 Adapted from code snippets online.
729 Adapted from code snippets online.
730
730
731 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
731 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
732 """
732 """
733 if 'VIRTUAL_ENV' not in os.environ:
733 if 'VIRTUAL_ENV' not in os.environ:
734 # Not in a virtualenv
734 # Not in a virtualenv
735 return
735 return
736
736
737 p = os.path.normcase(sys.executable)
737 p = os.path.normcase(sys.executable)
738 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
738 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
739
739
740 # executable path should end like /bin/python or \\scripts\\python.exe
740 # executable path should end like /bin/python or \\scripts\\python.exe
741 p_exe_up2 = os.path.dirname(os.path.dirname(p))
741 p_exe_up2 = os.path.dirname(os.path.dirname(p))
742 if p_exe_up2 and os.path.samefile(p_exe_up2, p_venv):
742 if p_exe_up2 and os.path.samefile(p_exe_up2, p_venv):
743 # Our exe is inside the virtualenv, don't need to do anything.
743 # Our exe is inside the virtualenv, don't need to do anything.
744 return
744 return
745
745
746 # fallback venv detection:
746 # fallback venv detection:
747 # stdlib venv may symlink sys.executable, so we can't use realpath.
747 # stdlib venv may symlink sys.executable, so we can't use realpath.
748 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
748 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
749 # So we just check every item in the symlink tree (generally <= 3)
749 # So we just check every item in the symlink tree (generally <= 3)
750 paths = [p]
750 paths = [p]
751 while os.path.islink(p):
751 while os.path.islink(p):
752 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
752 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
753 paths.append(p)
753 paths.append(p)
754
754
755 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
755 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
756 if p_venv.startswith('\\cygdrive'):
756 if p_venv.startswith('\\cygdrive'):
757 p_venv = p_venv[11:]
757 p_venv = p_venv[11:]
758 elif len(p_venv) >= 2 and p_venv[1] == ':':
758 elif len(p_venv) >= 2 and p_venv[1] == ':':
759 p_venv = p_venv[2:]
759 p_venv = p_venv[2:]
760
760
761 if any(p_venv in p for p in paths):
761 if any(p_venv in p for p in paths):
762 # Running properly in the virtualenv, don't need to do anything
762 # Running properly in the virtualenv, don't need to do anything
763 return
763 return
764
764
765 warn("Attempting to work in a virtualenv. If you encounter problems, please "
765 warn("Attempting to work in a virtualenv. If you encounter problems, please "
766 "install IPython inside the virtualenv.")
766 "install IPython inside the virtualenv.")
767 if sys.platform == "win32":
767 if sys.platform == "win32":
768 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
768 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
769 else:
769 else:
770 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
770 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
771 'python%d.%d' % sys.version_info[:2], 'site-packages')
771 'python%d.%d' % sys.version_info[:2], 'site-packages')
772
772
773 import site
773 import site
774 sys.path.insert(0, virtual_env)
774 sys.path.insert(0, virtual_env)
775 site.addsitedir(virtual_env)
775 site.addsitedir(virtual_env)
776
776
777 #-------------------------------------------------------------------------
777 #-------------------------------------------------------------------------
778 # Things related to injections into the sys module
778 # Things related to injections into the sys module
779 #-------------------------------------------------------------------------
779 #-------------------------------------------------------------------------
780
780
781 def save_sys_module_state(self):
781 def save_sys_module_state(self):
782 """Save the state of hooks in the sys module.
782 """Save the state of hooks in the sys module.
783
783
784 This has to be called after self.user_module is created.
784 This has to be called after self.user_module is created.
785 """
785 """
786 self._orig_sys_module_state = {'stdin': sys.stdin,
786 self._orig_sys_module_state = {'stdin': sys.stdin,
787 'stdout': sys.stdout,
787 'stdout': sys.stdout,
788 'stderr': sys.stderr,
788 'stderr': sys.stderr,
789 'excepthook': sys.excepthook}
789 'excepthook': sys.excepthook}
790 self._orig_sys_modules_main_name = self.user_module.__name__
790 self._orig_sys_modules_main_name = self.user_module.__name__
791 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
791 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
792
792
793 def restore_sys_module_state(self):
793 def restore_sys_module_state(self):
794 """Restore the state of the sys module."""
794 """Restore the state of the sys module."""
795 try:
795 try:
796 for k, v in self._orig_sys_module_state.items():
796 for k, v in self._orig_sys_module_state.items():
797 setattr(sys, k, v)
797 setattr(sys, k, v)
798 except AttributeError:
798 except AttributeError:
799 pass
799 pass
800 # Reset what what done in self.init_sys_modules
800 # Reset what what done in self.init_sys_modules
801 if self._orig_sys_modules_main_mod is not None:
801 if self._orig_sys_modules_main_mod is not None:
802 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
802 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
803
803
804 #-------------------------------------------------------------------------
804 #-------------------------------------------------------------------------
805 # Things related to the banner
805 # Things related to the banner
806 #-------------------------------------------------------------------------
806 #-------------------------------------------------------------------------
807
807
808 @property
808 @property
809 def banner(self):
809 def banner(self):
810 banner = self.banner1
810 banner = self.banner1
811 if self.profile and self.profile != 'default':
811 if self.profile and self.profile != 'default':
812 banner += '\nIPython profile: %s\n' % self.profile
812 banner += '\nIPython profile: %s\n' % self.profile
813 if self.banner2:
813 if self.banner2:
814 banner += '\n' + self.banner2
814 banner += '\n' + self.banner2
815 return banner
815 return banner
816
816
817 def show_banner(self, banner=None):
817 def show_banner(self, banner=None):
818 if banner is None:
818 if banner is None:
819 banner = self.banner
819 banner = self.banner
820 sys.stdout.write(banner)
820 sys.stdout.write(banner)
821
821
822 #-------------------------------------------------------------------------
822 #-------------------------------------------------------------------------
823 # Things related to hooks
823 # Things related to hooks
824 #-------------------------------------------------------------------------
824 #-------------------------------------------------------------------------
825
825
826 def init_hooks(self):
826 def init_hooks(self):
827 # hooks holds pointers used for user-side customizations
827 # hooks holds pointers used for user-side customizations
828 self.hooks = Struct()
828 self.hooks = Struct()
829
829
830 self.strdispatchers = {}
830 self.strdispatchers = {}
831
831
832 # Set all default hooks, defined in the IPython.hooks module.
832 # Set all default hooks, defined in the IPython.hooks module.
833 hooks = IPython.core.hooks
833 hooks = IPython.core.hooks
834 for hook_name in hooks.__all__:
834 for hook_name in hooks.__all__:
835 # default hooks have priority 100, i.e. low; user hooks should have
835 # default hooks have priority 100, i.e. low; user hooks should have
836 # 0-100 priority
836 # 0-100 priority
837 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
837 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
838
838
839 if self.display_page:
839 if self.display_page:
840 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
840 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
841
841
842 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
842 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
843 _warn_deprecated=True):
843 _warn_deprecated=True):
844 """set_hook(name,hook) -> sets an internal IPython hook.
844 """set_hook(name,hook) -> sets an internal IPython hook.
845
845
846 IPython exposes some of its internal API as user-modifiable hooks. By
846 IPython exposes some of its internal API as user-modifiable hooks. By
847 adding your function to one of these hooks, you can modify IPython's
847 adding your function to one of these hooks, you can modify IPython's
848 behavior to call at runtime your own routines."""
848 behavior to call at runtime your own routines."""
849
849
850 # At some point in the future, this should validate the hook before it
850 # At some point in the future, this should validate the hook before it
851 # accepts it. Probably at least check that the hook takes the number
851 # accepts it. Probably at least check that the hook takes the number
852 # of args it's supposed to.
852 # of args it's supposed to.
853
853
854 f = types.MethodType(hook,self)
854 f = types.MethodType(hook,self)
855
855
856 # check if the hook is for strdispatcher first
856 # check if the hook is for strdispatcher first
857 if str_key is not None:
857 if str_key is not None:
858 sdp = self.strdispatchers.get(name, StrDispatch())
858 sdp = self.strdispatchers.get(name, StrDispatch())
859 sdp.add_s(str_key, f, priority )
859 sdp.add_s(str_key, f, priority )
860 self.strdispatchers[name] = sdp
860 self.strdispatchers[name] = sdp
861 return
861 return
862 if re_key is not None:
862 if re_key is not None:
863 sdp = self.strdispatchers.get(name, StrDispatch())
863 sdp = self.strdispatchers.get(name, StrDispatch())
864 sdp.add_re(re.compile(re_key), f, priority )
864 sdp.add_re(re.compile(re_key), f, priority )
865 self.strdispatchers[name] = sdp
865 self.strdispatchers[name] = sdp
866 return
866 return
867
867
868 dp = getattr(self.hooks, name, None)
868 dp = getattr(self.hooks, name, None)
869 if name not in IPython.core.hooks.__all__:
869 if name not in IPython.core.hooks.__all__:
870 print("Warning! Hook '%s' is not one of %s" % \
870 print("Warning! Hook '%s' is not one of %s" % \
871 (name, IPython.core.hooks.__all__ ))
871 (name, IPython.core.hooks.__all__ ))
872
872
873 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
873 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
874 alternative = IPython.core.hooks.deprecated[name]
874 alternative = IPython.core.hooks.deprecated[name]
875 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
875 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
876
876
877 if not dp:
877 if not dp:
878 dp = IPython.core.hooks.CommandChainDispatcher()
878 dp = IPython.core.hooks.CommandChainDispatcher()
879
879
880 try:
880 try:
881 dp.add(f,priority)
881 dp.add(f,priority)
882 except AttributeError:
882 except AttributeError:
883 # it was not commandchain, plain old func - replace
883 # it was not commandchain, plain old func - replace
884 dp = f
884 dp = f
885
885
886 setattr(self.hooks,name, dp)
886 setattr(self.hooks,name, dp)
887
887
888 #-------------------------------------------------------------------------
888 #-------------------------------------------------------------------------
889 # Things related to events
889 # Things related to events
890 #-------------------------------------------------------------------------
890 #-------------------------------------------------------------------------
891
891
892 def init_events(self):
892 def init_events(self):
893 self.events = EventManager(self, available_events)
893 self.events = EventManager(self, available_events)
894
894
895 self.events.register("pre_execute", self._clear_warning_registry)
895 self.events.register("pre_execute", self._clear_warning_registry)
896
896
897 def register_post_execute(self, func):
897 def register_post_execute(self, func):
898 """DEPRECATED: Use ip.events.register('post_run_cell', func)
898 """DEPRECATED: Use ip.events.register('post_run_cell', func)
899
899
900 Register a function for calling after code execution.
900 Register a function for calling after code execution.
901 """
901 """
902 warn("ip.register_post_execute is deprecated, use "
902 warn("ip.register_post_execute is deprecated, use "
903 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
903 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
904 self.events.register('post_run_cell', func)
904 self.events.register('post_run_cell', func)
905
905
906 def _clear_warning_registry(self):
906 def _clear_warning_registry(self):
907 # clear the warning registry, so that different code blocks with
907 # clear the warning registry, so that different code blocks with
908 # overlapping line number ranges don't cause spurious suppression of
908 # overlapping line number ranges don't cause spurious suppression of
909 # warnings (see gh-6611 for details)
909 # warnings (see gh-6611 for details)
910 if "__warningregistry__" in self.user_global_ns:
910 if "__warningregistry__" in self.user_global_ns:
911 del self.user_global_ns["__warningregistry__"]
911 del self.user_global_ns["__warningregistry__"]
912
912
913 #-------------------------------------------------------------------------
913 #-------------------------------------------------------------------------
914 # Things related to the "main" module
914 # Things related to the "main" module
915 #-------------------------------------------------------------------------
915 #-------------------------------------------------------------------------
916
916
917 def new_main_mod(self, filename, modname):
917 def new_main_mod(self, filename, modname):
918 """Return a new 'main' module object for user code execution.
918 """Return a new 'main' module object for user code execution.
919
919
920 ``filename`` should be the path of the script which will be run in the
920 ``filename`` should be the path of the script which will be run in the
921 module. Requests with the same filename will get the same module, with
921 module. Requests with the same filename will get the same module, with
922 its namespace cleared.
922 its namespace cleared.
923
923
924 ``modname`` should be the module name - normally either '__main__' or
924 ``modname`` should be the module name - normally either '__main__' or
925 the basename of the file without the extension.
925 the basename of the file without the extension.
926
926
927 When scripts are executed via %run, we must keep a reference to their
927 When scripts are executed via %run, we must keep a reference to their
928 __main__ module around so that Python doesn't
928 __main__ module around so that Python doesn't
929 clear it, rendering references to module globals useless.
929 clear it, rendering references to module globals useless.
930
930
931 This method keeps said reference in a private dict, keyed by the
931 This method keeps said reference in a private dict, keyed by the
932 absolute path of the script. This way, for multiple executions of the
932 absolute path of the script. This way, for multiple executions of the
933 same script we only keep one copy of the namespace (the last one),
933 same script we only keep one copy of the namespace (the last one),
934 thus preventing memory leaks from old references while allowing the
934 thus preventing memory leaks from old references while allowing the
935 objects from the last execution to be accessible.
935 objects from the last execution to be accessible.
936 """
936 """
937 filename = os.path.abspath(filename)
937 filename = os.path.abspath(filename)
938 try:
938 try:
939 main_mod = self._main_mod_cache[filename]
939 main_mod = self._main_mod_cache[filename]
940 except KeyError:
940 except KeyError:
941 main_mod = self._main_mod_cache[filename] = types.ModuleType(
941 main_mod = self._main_mod_cache[filename] = types.ModuleType(
942 modname,
942 modname,
943 doc="Module created for script run in IPython")
943 doc="Module created for script run in IPython")
944 else:
944 else:
945 main_mod.__dict__.clear()
945 main_mod.__dict__.clear()
946 main_mod.__name__ = modname
946 main_mod.__name__ = modname
947
947
948 main_mod.__file__ = filename
948 main_mod.__file__ = filename
949 # It seems pydoc (and perhaps others) needs any module instance to
949 # It seems pydoc (and perhaps others) needs any module instance to
950 # implement a __nonzero__ method
950 # implement a __nonzero__ method
951 main_mod.__nonzero__ = lambda : True
951 main_mod.__nonzero__ = lambda : True
952
952
953 return main_mod
953 return main_mod
954
954
955 def clear_main_mod_cache(self):
955 def clear_main_mod_cache(self):
956 """Clear the cache of main modules.
956 """Clear the cache of main modules.
957
957
958 Mainly for use by utilities like %reset.
958 Mainly for use by utilities like %reset.
959
959
960 Examples
960 Examples
961 --------
961 --------
962
962
963 In [15]: import IPython
963 In [15]: import IPython
964
964
965 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
965 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
966
966
967 In [17]: len(_ip._main_mod_cache) > 0
967 In [17]: len(_ip._main_mod_cache) > 0
968 Out[17]: True
968 Out[17]: True
969
969
970 In [18]: _ip.clear_main_mod_cache()
970 In [18]: _ip.clear_main_mod_cache()
971
971
972 In [19]: len(_ip._main_mod_cache) == 0
972 In [19]: len(_ip._main_mod_cache) == 0
973 Out[19]: True
973 Out[19]: True
974 """
974 """
975 self._main_mod_cache.clear()
975 self._main_mod_cache.clear()
976
976
977 #-------------------------------------------------------------------------
977 #-------------------------------------------------------------------------
978 # Things related to debugging
978 # Things related to debugging
979 #-------------------------------------------------------------------------
979 #-------------------------------------------------------------------------
980
980
981 def init_pdb(self):
981 def init_pdb(self):
982 # Set calling of pdb on exceptions
982 # Set calling of pdb on exceptions
983 # self.call_pdb is a property
983 # self.call_pdb is a property
984 self.call_pdb = self.pdb
984 self.call_pdb = self.pdb
985
985
986 def _get_call_pdb(self):
986 def _get_call_pdb(self):
987 return self._call_pdb
987 return self._call_pdb
988
988
989 def _set_call_pdb(self,val):
989 def _set_call_pdb(self,val):
990
990
991 if val not in (0,1,False,True):
991 if val not in (0,1,False,True):
992 raise ValueError('new call_pdb value must be boolean')
992 raise ValueError('new call_pdb value must be boolean')
993
993
994 # store value in instance
994 # store value in instance
995 self._call_pdb = val
995 self._call_pdb = val
996
996
997 # notify the actual exception handlers
997 # notify the actual exception handlers
998 self.InteractiveTB.call_pdb = val
998 self.InteractiveTB.call_pdb = val
999
999
1000 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1000 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1001 'Control auto-activation of pdb at exceptions')
1001 'Control auto-activation of pdb at exceptions')
1002
1002
1003 def debugger(self,force=False):
1003 def debugger(self,force=False):
1004 """Call the pdb debugger.
1004 """Call the pdb debugger.
1005
1005
1006 Keywords:
1006 Keywords:
1007
1007
1008 - force(False): by default, this routine checks the instance call_pdb
1008 - force(False): by default, this routine checks the instance call_pdb
1009 flag and does not actually invoke the debugger if the flag is false.
1009 flag and does not actually invoke the debugger if the flag is false.
1010 The 'force' option forces the debugger to activate even if the flag
1010 The 'force' option forces the debugger to activate even if the flag
1011 is false.
1011 is false.
1012 """
1012 """
1013
1013
1014 if not (force or self.call_pdb):
1014 if not (force or self.call_pdb):
1015 return
1015 return
1016
1016
1017 if not hasattr(sys,'last_traceback'):
1017 if not hasattr(sys,'last_traceback'):
1018 error('No traceback has been produced, nothing to debug.')
1018 error('No traceback has been produced, nothing to debug.')
1019 return
1019 return
1020
1020
1021 self.InteractiveTB.debugger(force=True)
1021 self.InteractiveTB.debugger(force=True)
1022
1022
1023 #-------------------------------------------------------------------------
1023 #-------------------------------------------------------------------------
1024 # Things related to IPython's various namespaces
1024 # Things related to IPython's various namespaces
1025 #-------------------------------------------------------------------------
1025 #-------------------------------------------------------------------------
1026 default_user_namespaces = True
1026 default_user_namespaces = True
1027
1027
1028 def init_create_namespaces(self, user_module=None, user_ns=None):
1028 def init_create_namespaces(self, user_module=None, user_ns=None):
1029 # Create the namespace where the user will operate. user_ns is
1029 # Create the namespace where the user will operate. user_ns is
1030 # normally the only one used, and it is passed to the exec calls as
1030 # normally the only one used, and it is passed to the exec calls as
1031 # the locals argument. But we do carry a user_global_ns namespace
1031 # the locals argument. But we do carry a user_global_ns namespace
1032 # given as the exec 'globals' argument, This is useful in embedding
1032 # given as the exec 'globals' argument, This is useful in embedding
1033 # situations where the ipython shell opens in a context where the
1033 # situations where the ipython shell opens in a context where the
1034 # distinction between locals and globals is meaningful. For
1034 # distinction between locals and globals is meaningful. For
1035 # non-embedded contexts, it is just the same object as the user_ns dict.
1035 # non-embedded contexts, it is just the same object as the user_ns dict.
1036
1036
1037 # FIXME. For some strange reason, __builtins__ is showing up at user
1037 # FIXME. For some strange reason, __builtins__ is showing up at user
1038 # level as a dict instead of a module. This is a manual fix, but I
1038 # level as a dict instead of a module. This is a manual fix, but I
1039 # should really track down where the problem is coming from. Alex
1039 # should really track down where the problem is coming from. Alex
1040 # Schmolck reported this problem first.
1040 # Schmolck reported this problem first.
1041
1041
1042 # A useful post by Alex Martelli on this topic:
1042 # A useful post by Alex Martelli on this topic:
1043 # Re: inconsistent value from __builtins__
1043 # Re: inconsistent value from __builtins__
1044 # Von: Alex Martelli <aleaxit@yahoo.com>
1044 # Von: Alex Martelli <aleaxit@yahoo.com>
1045 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1045 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1046 # Gruppen: comp.lang.python
1046 # Gruppen: comp.lang.python
1047
1047
1048 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1048 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1049 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1049 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1050 # > <type 'dict'>
1050 # > <type 'dict'>
1051 # > >>> print type(__builtins__)
1051 # > >>> print type(__builtins__)
1052 # > <type 'module'>
1052 # > <type 'module'>
1053 # > Is this difference in return value intentional?
1053 # > Is this difference in return value intentional?
1054
1054
1055 # Well, it's documented that '__builtins__' can be either a dictionary
1055 # Well, it's documented that '__builtins__' can be either a dictionary
1056 # or a module, and it's been that way for a long time. Whether it's
1056 # or a module, and it's been that way for a long time. Whether it's
1057 # intentional (or sensible), I don't know. In any case, the idea is
1057 # intentional (or sensible), I don't know. In any case, the idea is
1058 # that if you need to access the built-in namespace directly, you
1058 # that if you need to access the built-in namespace directly, you
1059 # should start with "import __builtin__" (note, no 's') which will
1059 # should start with "import __builtin__" (note, no 's') which will
1060 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1060 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1061
1061
1062 # These routines return a properly built module and dict as needed by
1062 # These routines return a properly built module and dict as needed by
1063 # the rest of the code, and can also be used by extension writers to
1063 # the rest of the code, and can also be used by extension writers to
1064 # generate properly initialized namespaces.
1064 # generate properly initialized namespaces.
1065 if (user_ns is not None) or (user_module is not None):
1065 if (user_ns is not None) or (user_module is not None):
1066 self.default_user_namespaces = False
1066 self.default_user_namespaces = False
1067 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1067 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1068
1068
1069 # A record of hidden variables we have added to the user namespace, so
1069 # A record of hidden variables we have added to the user namespace, so
1070 # we can list later only variables defined in actual interactive use.
1070 # we can list later only variables defined in actual interactive use.
1071 self.user_ns_hidden = {}
1071 self.user_ns_hidden = {}
1072
1072
1073 # Now that FakeModule produces a real module, we've run into a nasty
1073 # Now that FakeModule produces a real module, we've run into a nasty
1074 # problem: after script execution (via %run), the module where the user
1074 # problem: after script execution (via %run), the module where the user
1075 # code ran is deleted. Now that this object is a true module (needed
1075 # code ran is deleted. Now that this object is a true module (needed
1076 # so doctest and other tools work correctly), the Python module
1076 # so doctest and other tools work correctly), the Python module
1077 # teardown mechanism runs over it, and sets to None every variable
1077 # teardown mechanism runs over it, and sets to None every variable
1078 # present in that module. Top-level references to objects from the
1078 # present in that module. Top-level references to objects from the
1079 # script survive, because the user_ns is updated with them. However,
1079 # script survive, because the user_ns is updated with them. However,
1080 # calling functions defined in the script that use other things from
1080 # calling functions defined in the script that use other things from
1081 # the script will fail, because the function's closure had references
1081 # the script will fail, because the function's closure had references
1082 # to the original objects, which are now all None. So we must protect
1082 # to the original objects, which are now all None. So we must protect
1083 # these modules from deletion by keeping a cache.
1083 # these modules from deletion by keeping a cache.
1084 #
1084 #
1085 # To avoid keeping stale modules around (we only need the one from the
1085 # To avoid keeping stale modules around (we only need the one from the
1086 # last run), we use a dict keyed with the full path to the script, so
1086 # last run), we use a dict keyed with the full path to the script, so
1087 # only the last version of the module is held in the cache. Note,
1087 # only the last version of the module is held in the cache. Note,
1088 # however, that we must cache the module *namespace contents* (their
1088 # however, that we must cache the module *namespace contents* (their
1089 # __dict__). Because if we try to cache the actual modules, old ones
1089 # __dict__). Because if we try to cache the actual modules, old ones
1090 # (uncached) could be destroyed while still holding references (such as
1090 # (uncached) could be destroyed while still holding references (such as
1091 # those held by GUI objects that tend to be long-lived)>
1091 # those held by GUI objects that tend to be long-lived)>
1092 #
1092 #
1093 # The %reset command will flush this cache. See the cache_main_mod()
1093 # The %reset command will flush this cache. See the cache_main_mod()
1094 # and clear_main_mod_cache() methods for details on use.
1094 # and clear_main_mod_cache() methods for details on use.
1095
1095
1096 # This is the cache used for 'main' namespaces
1096 # This is the cache used for 'main' namespaces
1097 self._main_mod_cache = {}
1097 self._main_mod_cache = {}
1098
1098
1099 # A table holding all the namespaces IPython deals with, so that
1099 # A table holding all the namespaces IPython deals with, so that
1100 # introspection facilities can search easily.
1100 # introspection facilities can search easily.
1101 self.ns_table = {'user_global':self.user_module.__dict__,
1101 self.ns_table = {'user_global':self.user_module.__dict__,
1102 'user_local':self.user_ns,
1102 'user_local':self.user_ns,
1103 'builtin':builtin_mod.__dict__
1103 'builtin':builtin_mod.__dict__
1104 }
1104 }
1105
1105
1106 @property
1106 @property
1107 def user_global_ns(self):
1107 def user_global_ns(self):
1108 return self.user_module.__dict__
1108 return self.user_module.__dict__
1109
1109
1110 def prepare_user_module(self, user_module=None, user_ns=None):
1110 def prepare_user_module(self, user_module=None, user_ns=None):
1111 """Prepare the module and namespace in which user code will be run.
1111 """Prepare the module and namespace in which user code will be run.
1112
1112
1113 When IPython is started normally, both parameters are None: a new module
1113 When IPython is started normally, both parameters are None: a new module
1114 is created automatically, and its __dict__ used as the namespace.
1114 is created automatically, and its __dict__ used as the namespace.
1115
1115
1116 If only user_module is provided, its __dict__ is used as the namespace.
1116 If only user_module is provided, its __dict__ is used as the namespace.
1117 If only user_ns is provided, a dummy module is created, and user_ns
1117 If only user_ns is provided, a dummy module is created, and user_ns
1118 becomes the global namespace. If both are provided (as they may be
1118 becomes the global namespace. If both are provided (as they may be
1119 when embedding), user_ns is the local namespace, and user_module
1119 when embedding), user_ns is the local namespace, and user_module
1120 provides the global namespace.
1120 provides the global namespace.
1121
1121
1122 Parameters
1122 Parameters
1123 ----------
1123 ----------
1124 user_module : module, optional
1124 user_module : module, optional
1125 The current user module in which IPython is being run. If None,
1125 The current user module in which IPython is being run. If None,
1126 a clean module will be created.
1126 a clean module will be created.
1127 user_ns : dict, optional
1127 user_ns : dict, optional
1128 A namespace in which to run interactive commands.
1128 A namespace in which to run interactive commands.
1129
1129
1130 Returns
1130 Returns
1131 -------
1131 -------
1132 A tuple of user_module and user_ns, each properly initialised.
1132 A tuple of user_module and user_ns, each properly initialised.
1133 """
1133 """
1134 if user_module is None and user_ns is not None:
1134 if user_module is None and user_ns is not None:
1135 user_ns.setdefault("__name__", "__main__")
1135 user_ns.setdefault("__name__", "__main__")
1136 user_module = DummyMod()
1136 user_module = DummyMod()
1137 user_module.__dict__ = user_ns
1137 user_module.__dict__ = user_ns
1138
1138
1139 if user_module is None:
1139 if user_module is None:
1140 user_module = types.ModuleType("__main__",
1140 user_module = types.ModuleType("__main__",
1141 doc="Automatically created module for IPython interactive environment")
1141 doc="Automatically created module for IPython interactive environment")
1142
1142
1143 # We must ensure that __builtin__ (without the final 's') is always
1143 # We must ensure that __builtin__ (without the final 's') is always
1144 # available and pointing to the __builtin__ *module*. For more details:
1144 # available and pointing to the __builtin__ *module*. For more details:
1145 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1145 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1146 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1146 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1147 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1147 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1148
1148
1149 if user_ns is None:
1149 if user_ns is None:
1150 user_ns = user_module.__dict__
1150 user_ns = user_module.__dict__
1151
1151
1152 return user_module, user_ns
1152 return user_module, user_ns
1153
1153
1154 def init_sys_modules(self):
1154 def init_sys_modules(self):
1155 # We need to insert into sys.modules something that looks like a
1155 # We need to insert into sys.modules something that looks like a
1156 # module but which accesses the IPython namespace, for shelve and
1156 # module but which accesses the IPython namespace, for shelve and
1157 # pickle to work interactively. Normally they rely on getting
1157 # pickle to work interactively. Normally they rely on getting
1158 # everything out of __main__, but for embedding purposes each IPython
1158 # everything out of __main__, but for embedding purposes each IPython
1159 # instance has its own private namespace, so we can't go shoving
1159 # instance has its own private namespace, so we can't go shoving
1160 # everything into __main__.
1160 # everything into __main__.
1161
1161
1162 # note, however, that we should only do this for non-embedded
1162 # note, however, that we should only do this for non-embedded
1163 # ipythons, which really mimic the __main__.__dict__ with their own
1163 # ipythons, which really mimic the __main__.__dict__ with their own
1164 # namespace. Embedded instances, on the other hand, should not do
1164 # namespace. Embedded instances, on the other hand, should not do
1165 # this because they need to manage the user local/global namespaces
1165 # this because they need to manage the user local/global namespaces
1166 # only, but they live within a 'normal' __main__ (meaning, they
1166 # only, but they live within a 'normal' __main__ (meaning, they
1167 # shouldn't overtake the execution environment of the script they're
1167 # shouldn't overtake the execution environment of the script they're
1168 # embedded in).
1168 # embedded in).
1169
1169
1170 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1170 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1171 main_name = self.user_module.__name__
1171 main_name = self.user_module.__name__
1172 sys.modules[main_name] = self.user_module
1172 sys.modules[main_name] = self.user_module
1173
1173
1174 def init_user_ns(self):
1174 def init_user_ns(self):
1175 """Initialize all user-visible namespaces to their minimum defaults.
1175 """Initialize all user-visible namespaces to their minimum defaults.
1176
1176
1177 Certain history lists are also initialized here, as they effectively
1177 Certain history lists are also initialized here, as they effectively
1178 act as user namespaces.
1178 act as user namespaces.
1179
1179
1180 Notes
1180 Notes
1181 -----
1181 -----
1182 All data structures here are only filled in, they are NOT reset by this
1182 All data structures here are only filled in, they are NOT reset by this
1183 method. If they were not empty before, data will simply be added to
1183 method. If they were not empty before, data will simply be added to
1184 therm.
1184 therm.
1185 """
1185 """
1186 # This function works in two parts: first we put a few things in
1186 # This function works in two parts: first we put a few things in
1187 # user_ns, and we sync that contents into user_ns_hidden so that these
1187 # user_ns, and we sync that contents into user_ns_hidden so that these
1188 # initial variables aren't shown by %who. After the sync, we add the
1188 # initial variables aren't shown by %who. After the sync, we add the
1189 # rest of what we *do* want the user to see with %who even on a new
1189 # rest of what we *do* want the user to see with %who even on a new
1190 # session (probably nothing, so they really only see their own stuff)
1190 # session (probably nothing, so they really only see their own stuff)
1191
1191
1192 # The user dict must *always* have a __builtin__ reference to the
1192 # The user dict must *always* have a __builtin__ reference to the
1193 # Python standard __builtin__ namespace, which must be imported.
1193 # Python standard __builtin__ namespace, which must be imported.
1194 # This is so that certain operations in prompt evaluation can be
1194 # This is so that certain operations in prompt evaluation can be
1195 # reliably executed with builtins. Note that we can NOT use
1195 # reliably executed with builtins. Note that we can NOT use
1196 # __builtins__ (note the 's'), because that can either be a dict or a
1196 # __builtins__ (note the 's'), because that can either be a dict or a
1197 # module, and can even mutate at runtime, depending on the context
1197 # module, and can even mutate at runtime, depending on the context
1198 # (Python makes no guarantees on it). In contrast, __builtin__ is
1198 # (Python makes no guarantees on it). In contrast, __builtin__ is
1199 # always a module object, though it must be explicitly imported.
1199 # always a module object, though it must be explicitly imported.
1200
1200
1201 # For more details:
1201 # For more details:
1202 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1202 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1203 ns = {}
1203 ns = {}
1204
1204
1205 # make global variables for user access to the histories
1205 # make global variables for user access to the histories
1206 ns['_ih'] = self.history_manager.input_hist_parsed
1206 ns['_ih'] = self.history_manager.input_hist_parsed
1207 ns['_oh'] = self.history_manager.output_hist
1207 ns['_oh'] = self.history_manager.output_hist
1208 ns['_dh'] = self.history_manager.dir_hist
1208 ns['_dh'] = self.history_manager.dir_hist
1209
1209
1210 # user aliases to input and output histories. These shouldn't show up
1210 # user aliases to input and output histories. These shouldn't show up
1211 # in %who, as they can have very large reprs.
1211 # in %who, as they can have very large reprs.
1212 ns['In'] = self.history_manager.input_hist_parsed
1212 ns['In'] = self.history_manager.input_hist_parsed
1213 ns['Out'] = self.history_manager.output_hist
1213 ns['Out'] = self.history_manager.output_hist
1214
1214
1215 # Store myself as the public api!!!
1215 # Store myself as the public api!!!
1216 ns['get_ipython'] = self.get_ipython
1216 ns['get_ipython'] = self.get_ipython
1217
1217
1218 ns['exit'] = self.exiter
1218 ns['exit'] = self.exiter
1219 ns['quit'] = self.exiter
1219 ns['quit'] = self.exiter
1220
1220
1221 # Sync what we've added so far to user_ns_hidden so these aren't seen
1221 # Sync what we've added so far to user_ns_hidden so these aren't seen
1222 # by %who
1222 # by %who
1223 self.user_ns_hidden.update(ns)
1223 self.user_ns_hidden.update(ns)
1224
1224
1225 # Anything put into ns now would show up in %who. Think twice before
1225 # Anything put into ns now would show up in %who. Think twice before
1226 # putting anything here, as we really want %who to show the user their
1226 # putting anything here, as we really want %who to show the user their
1227 # stuff, not our variables.
1227 # stuff, not our variables.
1228
1228
1229 # Finally, update the real user's namespace
1229 # Finally, update the real user's namespace
1230 self.user_ns.update(ns)
1230 self.user_ns.update(ns)
1231
1231
1232 @property
1232 @property
1233 def all_ns_refs(self):
1233 def all_ns_refs(self):
1234 """Get a list of references to all the namespace dictionaries in which
1234 """Get a list of references to all the namespace dictionaries in which
1235 IPython might store a user-created object.
1235 IPython might store a user-created object.
1236
1236
1237 Note that this does not include the displayhook, which also caches
1237 Note that this does not include the displayhook, which also caches
1238 objects from the output."""
1238 objects from the output."""
1239 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1239 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1240 [m.__dict__ for m in self._main_mod_cache.values()]
1240 [m.__dict__ for m in self._main_mod_cache.values()]
1241
1241
1242 def reset(self, new_session=True):
1242 def reset(self, new_session=True):
1243 """Clear all internal namespaces, and attempt to release references to
1243 """Clear all internal namespaces, and attempt to release references to
1244 user objects.
1244 user objects.
1245
1245
1246 If new_session is True, a new history session will be opened.
1246 If new_session is True, a new history session will be opened.
1247 """
1247 """
1248 # Clear histories
1248 # Clear histories
1249 self.history_manager.reset(new_session)
1249 self.history_manager.reset(new_session)
1250 # Reset counter used to index all histories
1250 # Reset counter used to index all histories
1251 if new_session:
1251 if new_session:
1252 self.execution_count = 1
1252 self.execution_count = 1
1253
1253
1254 # Reset last execution result
1254 # Reset last execution result
1255 self.last_execution_succeeded = True
1255 self.last_execution_succeeded = True
1256 self.last_execution_result = None
1256 self.last_execution_result = None
1257
1257
1258 # Flush cached output items
1258 # Flush cached output items
1259 if self.displayhook.do_full_cache:
1259 if self.displayhook.do_full_cache:
1260 self.displayhook.flush()
1260 self.displayhook.flush()
1261
1261
1262 # The main execution namespaces must be cleared very carefully,
1262 # The main execution namespaces must be cleared very carefully,
1263 # skipping the deletion of the builtin-related keys, because doing so
1263 # skipping the deletion of the builtin-related keys, because doing so
1264 # would cause errors in many object's __del__ methods.
1264 # would cause errors in many object's __del__ methods.
1265 if self.user_ns is not self.user_global_ns:
1265 if self.user_ns is not self.user_global_ns:
1266 self.user_ns.clear()
1266 self.user_ns.clear()
1267 ns = self.user_global_ns
1267 ns = self.user_global_ns
1268 drop_keys = set(ns.keys())
1268 drop_keys = set(ns.keys())
1269 drop_keys.discard('__builtin__')
1269 drop_keys.discard('__builtin__')
1270 drop_keys.discard('__builtins__')
1270 drop_keys.discard('__builtins__')
1271 drop_keys.discard('__name__')
1271 drop_keys.discard('__name__')
1272 for k in drop_keys:
1272 for k in drop_keys:
1273 del ns[k]
1273 del ns[k]
1274
1274
1275 self.user_ns_hidden.clear()
1275 self.user_ns_hidden.clear()
1276
1276
1277 # Restore the user namespaces to minimal usability
1277 # Restore the user namespaces to minimal usability
1278 self.init_user_ns()
1278 self.init_user_ns()
1279
1279
1280 # Restore the default and user aliases
1280 # Restore the default and user aliases
1281 self.alias_manager.clear_aliases()
1281 self.alias_manager.clear_aliases()
1282 self.alias_manager.init_aliases()
1282 self.alias_manager.init_aliases()
1283
1283
1284 # Flush the private list of module references kept for script
1284 # Flush the private list of module references kept for script
1285 # execution protection
1285 # execution protection
1286 self.clear_main_mod_cache()
1286 self.clear_main_mod_cache()
1287
1287
1288 def del_var(self, varname, by_name=False):
1288 def del_var(self, varname, by_name=False):
1289 """Delete a variable from the various namespaces, so that, as
1289 """Delete a variable from the various namespaces, so that, as
1290 far as possible, we're not keeping any hidden references to it.
1290 far as possible, we're not keeping any hidden references to it.
1291
1291
1292 Parameters
1292 Parameters
1293 ----------
1293 ----------
1294 varname : str
1294 varname : str
1295 The name of the variable to delete.
1295 The name of the variable to delete.
1296 by_name : bool
1296 by_name : bool
1297 If True, delete variables with the given name in each
1297 If True, delete variables with the given name in each
1298 namespace. If False (default), find the variable in the user
1298 namespace. If False (default), find the variable in the user
1299 namespace, and delete references to it.
1299 namespace, and delete references to it.
1300 """
1300 """
1301 if varname in ('__builtin__', '__builtins__'):
1301 if varname in ('__builtin__', '__builtins__'):
1302 raise ValueError("Refusing to delete %s" % varname)
1302 raise ValueError("Refusing to delete %s" % varname)
1303
1303
1304 ns_refs = self.all_ns_refs
1304 ns_refs = self.all_ns_refs
1305
1305
1306 if by_name: # Delete by name
1306 if by_name: # Delete by name
1307 for ns in ns_refs:
1307 for ns in ns_refs:
1308 try:
1308 try:
1309 del ns[varname]
1309 del ns[varname]
1310 except KeyError:
1310 except KeyError:
1311 pass
1311 pass
1312 else: # Delete by object
1312 else: # Delete by object
1313 try:
1313 try:
1314 obj = self.user_ns[varname]
1314 obj = self.user_ns[varname]
1315 except KeyError:
1315 except KeyError:
1316 raise NameError("name '%s' is not defined" % varname)
1316 raise NameError("name '%s' is not defined" % varname)
1317 # Also check in output history
1317 # Also check in output history
1318 ns_refs.append(self.history_manager.output_hist)
1318 ns_refs.append(self.history_manager.output_hist)
1319 for ns in ns_refs:
1319 for ns in ns_refs:
1320 to_delete = [n for n, o in ns.items() if o is obj]
1320 to_delete = [n for n, o in ns.items() if o is obj]
1321 for name in to_delete:
1321 for name in to_delete:
1322 del ns[name]
1322 del ns[name]
1323
1323
1324 # Ensure it is removed from the last execution result
1324 # Ensure it is removed from the last execution result
1325 if self.last_execution_result.result is obj:
1325 if self.last_execution_result.result is obj:
1326 self.last_execution_result = None
1326 self.last_execution_result = None
1327
1327
1328 # displayhook keeps extra references, but not in a dictionary
1328 # displayhook keeps extra references, but not in a dictionary
1329 for name in ('_', '__', '___'):
1329 for name in ('_', '__', '___'):
1330 if getattr(self.displayhook, name) is obj:
1330 if getattr(self.displayhook, name) is obj:
1331 setattr(self.displayhook, name, None)
1331 setattr(self.displayhook, name, None)
1332
1332
1333 def reset_selective(self, regex=None):
1333 def reset_selective(self, regex=None):
1334 """Clear selective variables from internal namespaces based on a
1334 """Clear selective variables from internal namespaces based on a
1335 specified regular expression.
1335 specified regular expression.
1336
1336
1337 Parameters
1337 Parameters
1338 ----------
1338 ----------
1339 regex : string or compiled pattern, optional
1339 regex : string or compiled pattern, optional
1340 A regular expression pattern that will be used in searching
1340 A regular expression pattern that will be used in searching
1341 variable names in the users namespaces.
1341 variable names in the users namespaces.
1342 """
1342 """
1343 if regex is not None:
1343 if regex is not None:
1344 try:
1344 try:
1345 m = re.compile(regex)
1345 m = re.compile(regex)
1346 except TypeError:
1346 except TypeError:
1347 raise TypeError('regex must be a string or compiled pattern')
1347 raise TypeError('regex must be a string or compiled pattern')
1348 # Search for keys in each namespace that match the given regex
1348 # Search for keys in each namespace that match the given regex
1349 # If a match is found, delete the key/value pair.
1349 # If a match is found, delete the key/value pair.
1350 for ns in self.all_ns_refs:
1350 for ns in self.all_ns_refs:
1351 for var in ns:
1351 for var in ns:
1352 if m.search(var):
1352 if m.search(var):
1353 del ns[var]
1353 del ns[var]
1354
1354
1355 def push(self, variables, interactive=True):
1355 def push(self, variables, interactive=True):
1356 """Inject a group of variables into the IPython user namespace.
1356 """Inject a group of variables into the IPython user namespace.
1357
1357
1358 Parameters
1358 Parameters
1359 ----------
1359 ----------
1360 variables : dict, str or list/tuple of str
1360 variables : dict, str or list/tuple of str
1361 The variables to inject into the user's namespace. If a dict, a
1361 The variables to inject into the user's namespace. If a dict, a
1362 simple update is done. If a str, the string is assumed to have
1362 simple update is done. If a str, the string is assumed to have
1363 variable names separated by spaces. A list/tuple of str can also
1363 variable names separated by spaces. A list/tuple of str can also
1364 be used to give the variable names. If just the variable names are
1364 be used to give the variable names. If just the variable names are
1365 give (list/tuple/str) then the variable values looked up in the
1365 give (list/tuple/str) then the variable values looked up in the
1366 callers frame.
1366 callers frame.
1367 interactive : bool
1367 interactive : bool
1368 If True (default), the variables will be listed with the ``who``
1368 If True (default), the variables will be listed with the ``who``
1369 magic.
1369 magic.
1370 """
1370 """
1371 vdict = None
1371 vdict = None
1372
1372
1373 # We need a dict of name/value pairs to do namespace updates.
1373 # We need a dict of name/value pairs to do namespace updates.
1374 if isinstance(variables, dict):
1374 if isinstance(variables, dict):
1375 vdict = variables
1375 vdict = variables
1376 elif isinstance(variables, (str, list, tuple)):
1376 elif isinstance(variables, (str, list, tuple)):
1377 if isinstance(variables, str):
1377 if isinstance(variables, str):
1378 vlist = variables.split()
1378 vlist = variables.split()
1379 else:
1379 else:
1380 vlist = variables
1380 vlist = variables
1381 vdict = {}
1381 vdict = {}
1382 cf = sys._getframe(1)
1382 cf = sys._getframe(1)
1383 for name in vlist:
1383 for name in vlist:
1384 try:
1384 try:
1385 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1385 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1386 except:
1386 except:
1387 print('Could not get variable %s from %s' %
1387 print('Could not get variable %s from %s' %
1388 (name,cf.f_code.co_name))
1388 (name,cf.f_code.co_name))
1389 else:
1389 else:
1390 raise ValueError('variables must be a dict/str/list/tuple')
1390 raise ValueError('variables must be a dict/str/list/tuple')
1391
1391
1392 # Propagate variables to user namespace
1392 # Propagate variables to user namespace
1393 self.user_ns.update(vdict)
1393 self.user_ns.update(vdict)
1394
1394
1395 # And configure interactive visibility
1395 # And configure interactive visibility
1396 user_ns_hidden = self.user_ns_hidden
1396 user_ns_hidden = self.user_ns_hidden
1397 if interactive:
1397 if interactive:
1398 for name in vdict:
1398 for name in vdict:
1399 user_ns_hidden.pop(name, None)
1399 user_ns_hidden.pop(name, None)
1400 else:
1400 else:
1401 user_ns_hidden.update(vdict)
1401 user_ns_hidden.update(vdict)
1402
1402
1403 def drop_by_id(self, variables):
1403 def drop_by_id(self, variables):
1404 """Remove a dict of variables from the user namespace, if they are the
1404 """Remove a dict of variables from the user namespace, if they are the
1405 same as the values in the dictionary.
1405 same as the values in the dictionary.
1406
1406
1407 This is intended for use by extensions: variables that they've added can
1407 This is intended for use by extensions: variables that they've added can
1408 be taken back out if they are unloaded, without removing any that the
1408 be taken back out if they are unloaded, without removing any that the
1409 user has overwritten.
1409 user has overwritten.
1410
1410
1411 Parameters
1411 Parameters
1412 ----------
1412 ----------
1413 variables : dict
1413 variables : dict
1414 A dictionary mapping object names (as strings) to the objects.
1414 A dictionary mapping object names (as strings) to the objects.
1415 """
1415 """
1416 for name, obj in variables.items():
1416 for name, obj in variables.items():
1417 if name in self.user_ns and self.user_ns[name] is obj:
1417 if name in self.user_ns and self.user_ns[name] is obj:
1418 del self.user_ns[name]
1418 del self.user_ns[name]
1419 self.user_ns_hidden.pop(name, None)
1419 self.user_ns_hidden.pop(name, None)
1420
1420
1421 #-------------------------------------------------------------------------
1421 #-------------------------------------------------------------------------
1422 # Things related to object introspection
1422 # Things related to object introspection
1423 #-------------------------------------------------------------------------
1423 #-------------------------------------------------------------------------
1424
1424
1425 def _ofind(self, oname, namespaces=None):
1425 def _ofind(self, oname, namespaces=None):
1426 """Find an object in the available namespaces.
1426 """Find an object in the available namespaces.
1427
1427
1428 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1428 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1429
1429
1430 Has special code to detect magic functions.
1430 Has special code to detect magic functions.
1431 """
1431 """
1432 oname = oname.strip()
1432 oname = oname.strip()
1433 if not oname.startswith(ESC_MAGIC) and \
1433 if not oname.startswith(ESC_MAGIC) and \
1434 not oname.startswith(ESC_MAGIC2) and \
1434 not oname.startswith(ESC_MAGIC2) and \
1435 not all(a.isidentifier() for a in oname.split(".")):
1435 not all(a.isidentifier() for a in oname.split(".")):
1436 return {'found': False}
1436 return {'found': False}
1437
1437
1438 if namespaces is None:
1438 if namespaces is None:
1439 # Namespaces to search in:
1439 # Namespaces to search in:
1440 # Put them in a list. The order is important so that we
1440 # Put them in a list. The order is important so that we
1441 # find things in the same order that Python finds them.
1441 # find things in the same order that Python finds them.
1442 namespaces = [ ('Interactive', self.user_ns),
1442 namespaces = [ ('Interactive', self.user_ns),
1443 ('Interactive (global)', self.user_global_ns),
1443 ('Interactive (global)', self.user_global_ns),
1444 ('Python builtin', builtin_mod.__dict__),
1444 ('Python builtin', builtin_mod.__dict__),
1445 ]
1445 ]
1446
1446
1447 ismagic = False
1447 ismagic = False
1448 isalias = False
1448 isalias = False
1449 found = False
1449 found = False
1450 ospace = None
1450 ospace = None
1451 parent = None
1451 parent = None
1452 obj = None
1452 obj = None
1453
1453
1454 # Look for the given name by splitting it in parts. If the head is
1454 # Look for the given name by splitting it in parts. If the head is
1455 # found, then we look for all the remaining parts as members, and only
1455 # found, then we look for all the remaining parts as members, and only
1456 # declare success if we can find them all.
1456 # declare success if we can find them all.
1457 oname_parts = oname.split('.')
1457 oname_parts = oname.split('.')
1458 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1458 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1459 for nsname,ns in namespaces:
1459 for nsname,ns in namespaces:
1460 try:
1460 try:
1461 obj = ns[oname_head]
1461 obj = ns[oname_head]
1462 except KeyError:
1462 except KeyError:
1463 continue
1463 continue
1464 else:
1464 else:
1465 for idx, part in enumerate(oname_rest):
1465 for idx, part in enumerate(oname_rest):
1466 try:
1466 try:
1467 parent = obj
1467 parent = obj
1468 # The last part is looked up in a special way to avoid
1468 # The last part is looked up in a special way to avoid
1469 # descriptor invocation as it may raise or have side
1469 # descriptor invocation as it may raise or have side
1470 # effects.
1470 # effects.
1471 if idx == len(oname_rest) - 1:
1471 if idx == len(oname_rest) - 1:
1472 obj = self._getattr_property(obj, part)
1472 obj = self._getattr_property(obj, part)
1473 else:
1473 else:
1474 obj = getattr(obj, part)
1474 obj = getattr(obj, part)
1475 except:
1475 except:
1476 # Blanket except b/c some badly implemented objects
1476 # Blanket except b/c some badly implemented objects
1477 # allow __getattr__ to raise exceptions other than
1477 # allow __getattr__ to raise exceptions other than
1478 # AttributeError, which then crashes IPython.
1478 # AttributeError, which then crashes IPython.
1479 break
1479 break
1480 else:
1480 else:
1481 # If we finish the for loop (no break), we got all members
1481 # If we finish the for loop (no break), we got all members
1482 found = True
1482 found = True
1483 ospace = nsname
1483 ospace = nsname
1484 break # namespace loop
1484 break # namespace loop
1485
1485
1486 # Try to see if it's magic
1486 # Try to see if it's magic
1487 if not found:
1487 if not found:
1488 obj = None
1488 obj = None
1489 if oname.startswith(ESC_MAGIC2):
1489 if oname.startswith(ESC_MAGIC2):
1490 oname = oname.lstrip(ESC_MAGIC2)
1490 oname = oname.lstrip(ESC_MAGIC2)
1491 obj = self.find_cell_magic(oname)
1491 obj = self.find_cell_magic(oname)
1492 elif oname.startswith(ESC_MAGIC):
1492 elif oname.startswith(ESC_MAGIC):
1493 oname = oname.lstrip(ESC_MAGIC)
1493 oname = oname.lstrip(ESC_MAGIC)
1494 obj = self.find_line_magic(oname)
1494 obj = self.find_line_magic(oname)
1495 else:
1495 else:
1496 # search without prefix, so run? will find %run?
1496 # search without prefix, so run? will find %run?
1497 obj = self.find_line_magic(oname)
1497 obj = self.find_line_magic(oname)
1498 if obj is None:
1498 if obj is None:
1499 obj = self.find_cell_magic(oname)
1499 obj = self.find_cell_magic(oname)
1500 if obj is not None:
1500 if obj is not None:
1501 found = True
1501 found = True
1502 ospace = 'IPython internal'
1502 ospace = 'IPython internal'
1503 ismagic = True
1503 ismagic = True
1504 isalias = isinstance(obj, Alias)
1504 isalias = isinstance(obj, Alias)
1505
1505
1506 # Last try: special-case some literals like '', [], {}, etc:
1506 # Last try: special-case some literals like '', [], {}, etc:
1507 if not found and oname_head in ["''",'""','[]','{}','()']:
1507 if not found and oname_head in ["''",'""','[]','{}','()']:
1508 obj = eval(oname_head)
1508 obj = eval(oname_head)
1509 found = True
1509 found = True
1510 ospace = 'Interactive'
1510 ospace = 'Interactive'
1511
1511
1512 return {
1512 return {
1513 'obj':obj,
1513 'obj':obj,
1514 'found':found,
1514 'found':found,
1515 'parent':parent,
1515 'parent':parent,
1516 'ismagic':ismagic,
1516 'ismagic':ismagic,
1517 'isalias':isalias,
1517 'isalias':isalias,
1518 'namespace':ospace
1518 'namespace':ospace
1519 }
1519 }
1520
1520
1521 @staticmethod
1521 @staticmethod
1522 def _getattr_property(obj, attrname):
1522 def _getattr_property(obj, attrname):
1523 """Property-aware getattr to use in object finding.
1523 """Property-aware getattr to use in object finding.
1524
1524
1525 If attrname represents a property, return it unevaluated (in case it has
1525 If attrname represents a property, return it unevaluated (in case it has
1526 side effects or raises an error.
1526 side effects or raises an error.
1527
1527
1528 """
1528 """
1529 if not isinstance(obj, type):
1529 if not isinstance(obj, type):
1530 try:
1530 try:
1531 # `getattr(type(obj), attrname)` is not guaranteed to return
1531 # `getattr(type(obj), attrname)` is not guaranteed to return
1532 # `obj`, but does so for property:
1532 # `obj`, but does so for property:
1533 #
1533 #
1534 # property.__get__(self, None, cls) -> self
1534 # property.__get__(self, None, cls) -> self
1535 #
1535 #
1536 # The universal alternative is to traverse the mro manually
1536 # The universal alternative is to traverse the mro manually
1537 # searching for attrname in class dicts.
1537 # searching for attrname in class dicts.
1538 attr = getattr(type(obj), attrname)
1538 attr = getattr(type(obj), attrname)
1539 except AttributeError:
1539 except AttributeError:
1540 pass
1540 pass
1541 else:
1541 else:
1542 # This relies on the fact that data descriptors (with both
1542 # This relies on the fact that data descriptors (with both
1543 # __get__ & __set__ magic methods) take precedence over
1543 # __get__ & __set__ magic methods) take precedence over
1544 # instance-level attributes:
1544 # instance-level attributes:
1545 #
1545 #
1546 # class A(object):
1546 # class A(object):
1547 # @property
1547 # @property
1548 # def foobar(self): return 123
1548 # def foobar(self): return 123
1549 # a = A()
1549 # a = A()
1550 # a.__dict__['foobar'] = 345
1550 # a.__dict__['foobar'] = 345
1551 # a.foobar # == 123
1551 # a.foobar # == 123
1552 #
1552 #
1553 # So, a property may be returned right away.
1553 # So, a property may be returned right away.
1554 if isinstance(attr, property):
1554 if isinstance(attr, property):
1555 return attr
1555 return attr
1556
1556
1557 # Nothing helped, fall back.
1557 # Nothing helped, fall back.
1558 return getattr(obj, attrname)
1558 return getattr(obj, attrname)
1559
1559
1560 def _object_find(self, oname, namespaces=None):
1560 def _object_find(self, oname, namespaces=None):
1561 """Find an object and return a struct with info about it."""
1561 """Find an object and return a struct with info about it."""
1562 return Struct(self._ofind(oname, namespaces))
1562 return Struct(self._ofind(oname, namespaces))
1563
1563
1564 def _inspect(self, meth, oname, namespaces=None, **kw):
1564 def _inspect(self, meth, oname, namespaces=None, **kw):
1565 """Generic interface to the inspector system.
1565 """Generic interface to the inspector system.
1566
1566
1567 This function is meant to be called by pdef, pdoc & friends.
1567 This function is meant to be called by pdef, pdoc & friends.
1568 """
1568 """
1569 info = self._object_find(oname, namespaces)
1569 info = self._object_find(oname, namespaces)
1570 docformat = sphinxify if self.sphinxify_docstring else None
1570 docformat = sphinxify if self.sphinxify_docstring else None
1571 if info.found:
1571 if info.found:
1572 pmethod = getattr(self.inspector, meth)
1572 pmethod = getattr(self.inspector, meth)
1573 # TODO: only apply format_screen to the plain/text repr of the mime
1573 # TODO: only apply format_screen to the plain/text repr of the mime
1574 # bundle.
1574 # bundle.
1575 formatter = format_screen if info.ismagic else docformat
1575 formatter = format_screen if info.ismagic else docformat
1576 if meth == 'pdoc':
1576 if meth == 'pdoc':
1577 pmethod(info.obj, oname, formatter)
1577 pmethod(info.obj, oname, formatter)
1578 elif meth == 'pinfo':
1578 elif meth == 'pinfo':
1579 pmethod(info.obj, oname, formatter, info,
1579 pmethod(info.obj, oname, formatter, info,
1580 enable_html_pager=self.enable_html_pager, **kw)
1580 enable_html_pager=self.enable_html_pager, **kw)
1581 else:
1581 else:
1582 pmethod(info.obj, oname)
1582 pmethod(info.obj, oname)
1583 else:
1583 else:
1584 print('Object `%s` not found.' % oname)
1584 print('Object `%s` not found.' % oname)
1585 return 'not found' # so callers can take other action
1585 return 'not found' # so callers can take other action
1586
1586
1587 def object_inspect(self, oname, detail_level=0):
1587 def object_inspect(self, oname, detail_level=0):
1588 """Get object info about oname"""
1588 """Get object info about oname"""
1589 with self.builtin_trap:
1589 with self.builtin_trap:
1590 info = self._object_find(oname)
1590 info = self._object_find(oname)
1591 if info.found:
1591 if info.found:
1592 return self.inspector.info(info.obj, oname, info=info,
1592 return self.inspector.info(info.obj, oname, info=info,
1593 detail_level=detail_level
1593 detail_level=detail_level
1594 )
1594 )
1595 else:
1595 else:
1596 return oinspect.object_info(name=oname, found=False)
1596 return oinspect.object_info(name=oname, found=False)
1597
1597
1598 def object_inspect_text(self, oname, detail_level=0):
1598 def object_inspect_text(self, oname, detail_level=0):
1599 """Get object info as formatted text"""
1599 """Get object info as formatted text"""
1600 return self.object_inspect_mime(oname, detail_level)['text/plain']
1600 return self.object_inspect_mime(oname, detail_level)['text/plain']
1601
1601
1602 def object_inspect_mime(self, oname, detail_level=0):
1602 def object_inspect_mime(self, oname, detail_level=0):
1603 """Get object info as a mimebundle of formatted representations.
1603 """Get object info as a mimebundle of formatted representations.
1604
1604
1605 A mimebundle is a dictionary, keyed by mime-type.
1605 A mimebundle is a dictionary, keyed by mime-type.
1606 It must always have the key `'text/plain'`.
1606 It must always have the key `'text/plain'`.
1607 """
1607 """
1608 with self.builtin_trap:
1608 with self.builtin_trap:
1609 info = self._object_find(oname)
1609 info = self._object_find(oname)
1610 if info.found:
1610 if info.found:
1611 return self.inspector._get_info(info.obj, oname, info=info,
1611 return self.inspector._get_info(info.obj, oname, info=info,
1612 detail_level=detail_level
1612 detail_level=detail_level
1613 )
1613 )
1614 else:
1614 else:
1615 raise KeyError(oname)
1615 raise KeyError(oname)
1616
1616
1617 #-------------------------------------------------------------------------
1617 #-------------------------------------------------------------------------
1618 # Things related to history management
1618 # Things related to history management
1619 #-------------------------------------------------------------------------
1619 #-------------------------------------------------------------------------
1620
1620
1621 def init_history(self):
1621 def init_history(self):
1622 """Sets up the command history, and starts regular autosaves."""
1622 """Sets up the command history, and starts regular autosaves."""
1623 self.history_manager = HistoryManager(shell=self, parent=self)
1623 self.history_manager = HistoryManager(shell=self, parent=self)
1624 self.configurables.append(self.history_manager)
1624 self.configurables.append(self.history_manager)
1625
1625
1626 #-------------------------------------------------------------------------
1626 #-------------------------------------------------------------------------
1627 # Things related to exception handling and tracebacks (not debugging)
1627 # Things related to exception handling and tracebacks (not debugging)
1628 #-------------------------------------------------------------------------
1628 #-------------------------------------------------------------------------
1629
1629
1630 debugger_cls = Pdb
1630 debugger_cls = Pdb
1631
1631
1632 def init_traceback_handlers(self, custom_exceptions):
1632 def init_traceback_handlers(self, custom_exceptions):
1633 # Syntax error handler.
1633 # Syntax error handler.
1634 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1634 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1635
1635
1636 # The interactive one is initialized with an offset, meaning we always
1636 # The interactive one is initialized with an offset, meaning we always
1637 # want to remove the topmost item in the traceback, which is our own
1637 # want to remove the topmost item in the traceback, which is our own
1638 # internal code. Valid modes: ['Plain','Context','Verbose']
1638 # internal code. Valid modes: ['Plain','Context','Verbose']
1639 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1639 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1640 color_scheme='NoColor',
1640 color_scheme='NoColor',
1641 tb_offset = 1,
1641 tb_offset = 1,
1642 check_cache=check_linecache_ipython,
1642 check_cache=check_linecache_ipython,
1643 debugger_cls=self.debugger_cls, parent=self)
1643 debugger_cls=self.debugger_cls, parent=self)
1644
1644
1645 # The instance will store a pointer to the system-wide exception hook,
1645 # The instance will store a pointer to the system-wide exception hook,
1646 # so that runtime code (such as magics) can access it. This is because
1646 # so that runtime code (such as magics) can access it. This is because
1647 # during the read-eval loop, it may get temporarily overwritten.
1647 # during the read-eval loop, it may get temporarily overwritten.
1648 self.sys_excepthook = sys.excepthook
1648 self.sys_excepthook = sys.excepthook
1649
1649
1650 # and add any custom exception handlers the user may have specified
1650 # and add any custom exception handlers the user may have specified
1651 self.set_custom_exc(*custom_exceptions)
1651 self.set_custom_exc(*custom_exceptions)
1652
1652
1653 # Set the exception mode
1653 # Set the exception mode
1654 self.InteractiveTB.set_mode(mode=self.xmode)
1654 self.InteractiveTB.set_mode(mode=self.xmode)
1655
1655
1656 def set_custom_exc(self, exc_tuple, handler):
1656 def set_custom_exc(self, exc_tuple, handler):
1657 """set_custom_exc(exc_tuple, handler)
1657 """set_custom_exc(exc_tuple, handler)
1658
1658
1659 Set a custom exception handler, which will be called if any of the
1659 Set a custom exception handler, which will be called if any of the
1660 exceptions in exc_tuple occur in the mainloop (specifically, in the
1660 exceptions in exc_tuple occur in the mainloop (specifically, in the
1661 run_code() method).
1661 run_code() method).
1662
1662
1663 Parameters
1663 Parameters
1664 ----------
1664 ----------
1665
1665
1666 exc_tuple : tuple of exception classes
1666 exc_tuple : tuple of exception classes
1667 A *tuple* of exception classes, for which to call the defined
1667 A *tuple* of exception classes, for which to call the defined
1668 handler. It is very important that you use a tuple, and NOT A
1668 handler. It is very important that you use a tuple, and NOT A
1669 LIST here, because of the way Python's except statement works. If
1669 LIST here, because of the way Python's except statement works. If
1670 you only want to trap a single exception, use a singleton tuple::
1670 you only want to trap a single exception, use a singleton tuple::
1671
1671
1672 exc_tuple == (MyCustomException,)
1672 exc_tuple == (MyCustomException,)
1673
1673
1674 handler : callable
1674 handler : callable
1675 handler must have the following signature::
1675 handler must have the following signature::
1676
1676
1677 def my_handler(self, etype, value, tb, tb_offset=None):
1677 def my_handler(self, etype, value, tb, tb_offset=None):
1678 ...
1678 ...
1679 return structured_traceback
1679 return structured_traceback
1680
1680
1681 Your handler must return a structured traceback (a list of strings),
1681 Your handler must return a structured traceback (a list of strings),
1682 or None.
1682 or None.
1683
1683
1684 This will be made into an instance method (via types.MethodType)
1684 This will be made into an instance method (via types.MethodType)
1685 of IPython itself, and it will be called if any of the exceptions
1685 of IPython itself, and it will be called if any of the exceptions
1686 listed in the exc_tuple are caught. If the handler is None, an
1686 listed in the exc_tuple are caught. If the handler is None, an
1687 internal basic one is used, which just prints basic info.
1687 internal basic one is used, which just prints basic info.
1688
1688
1689 To protect IPython from crashes, if your handler ever raises an
1689 To protect IPython from crashes, if your handler ever raises an
1690 exception or returns an invalid result, it will be immediately
1690 exception or returns an invalid result, it will be immediately
1691 disabled.
1691 disabled.
1692
1692
1693 WARNING: by putting in your own exception handler into IPython's main
1693 WARNING: by putting in your own exception handler into IPython's main
1694 execution loop, you run a very good chance of nasty crashes. This
1694 execution loop, you run a very good chance of nasty crashes. This
1695 facility should only be used if you really know what you are doing."""
1695 facility should only be used if you really know what you are doing."""
1696 if not isinstance(exc_tuple, tuple):
1696 if not isinstance(exc_tuple, tuple):
1697 raise TypeError("The custom exceptions must be given as a tuple.")
1697 raise TypeError("The custom exceptions must be given as a tuple.")
1698
1698
1699 def dummy_handler(self, etype, value, tb, tb_offset=None):
1699 def dummy_handler(self, etype, value, tb, tb_offset=None):
1700 print('*** Simple custom exception handler ***')
1700 print('*** Simple custom exception handler ***')
1701 print('Exception type :', etype)
1701 print('Exception type :', etype)
1702 print('Exception value:', value)
1702 print('Exception value:', value)
1703 print('Traceback :', tb)
1703 print('Traceback :', tb)
1704
1704
1705 def validate_stb(stb):
1705 def validate_stb(stb):
1706 """validate structured traceback return type
1706 """validate structured traceback return type
1707
1707
1708 return type of CustomTB *should* be a list of strings, but allow
1708 return type of CustomTB *should* be a list of strings, but allow
1709 single strings or None, which are harmless.
1709 single strings or None, which are harmless.
1710
1710
1711 This function will *always* return a list of strings,
1711 This function will *always* return a list of strings,
1712 and will raise a TypeError if stb is inappropriate.
1712 and will raise a TypeError if stb is inappropriate.
1713 """
1713 """
1714 msg = "CustomTB must return list of strings, not %r" % stb
1714 msg = "CustomTB must return list of strings, not %r" % stb
1715 if stb is None:
1715 if stb is None:
1716 return []
1716 return []
1717 elif isinstance(stb, str):
1717 elif isinstance(stb, str):
1718 return [stb]
1718 return [stb]
1719 elif not isinstance(stb, list):
1719 elif not isinstance(stb, list):
1720 raise TypeError(msg)
1720 raise TypeError(msg)
1721 # it's a list
1721 # it's a list
1722 for line in stb:
1722 for line in stb:
1723 # check every element
1723 # check every element
1724 if not isinstance(line, str):
1724 if not isinstance(line, str):
1725 raise TypeError(msg)
1725 raise TypeError(msg)
1726 return stb
1726 return stb
1727
1727
1728 if handler is None:
1728 if handler is None:
1729 wrapped = dummy_handler
1729 wrapped = dummy_handler
1730 else:
1730 else:
1731 def wrapped(self,etype,value,tb,tb_offset=None):
1731 def wrapped(self,etype,value,tb,tb_offset=None):
1732 """wrap CustomTB handler, to protect IPython from user code
1732 """wrap CustomTB handler, to protect IPython from user code
1733
1733
1734 This makes it harder (but not impossible) for custom exception
1734 This makes it harder (but not impossible) for custom exception
1735 handlers to crash IPython.
1735 handlers to crash IPython.
1736 """
1736 """
1737 try:
1737 try:
1738 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1738 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1739 return validate_stb(stb)
1739 return validate_stb(stb)
1740 except:
1740 except:
1741 # clear custom handler immediately
1741 # clear custom handler immediately
1742 self.set_custom_exc((), None)
1742 self.set_custom_exc((), None)
1743 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1743 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1744 # show the exception in handler first
1744 # show the exception in handler first
1745 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1745 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1746 print(self.InteractiveTB.stb2text(stb))
1746 print(self.InteractiveTB.stb2text(stb))
1747 print("The original exception:")
1747 print("The original exception:")
1748 stb = self.InteractiveTB.structured_traceback(
1748 stb = self.InteractiveTB.structured_traceback(
1749 (etype,value,tb), tb_offset=tb_offset
1749 (etype,value,tb), tb_offset=tb_offset
1750 )
1750 )
1751 return stb
1751 return stb
1752
1752
1753 self.CustomTB = types.MethodType(wrapped,self)
1753 self.CustomTB = types.MethodType(wrapped,self)
1754 self.custom_exceptions = exc_tuple
1754 self.custom_exceptions = exc_tuple
1755
1755
1756 def excepthook(self, etype, value, tb):
1756 def excepthook(self, etype, value, tb):
1757 """One more defense for GUI apps that call sys.excepthook.
1757 """One more defense for GUI apps that call sys.excepthook.
1758
1758
1759 GUI frameworks like wxPython trap exceptions and call
1759 GUI frameworks like wxPython trap exceptions and call
1760 sys.excepthook themselves. I guess this is a feature that
1760 sys.excepthook themselves. I guess this is a feature that
1761 enables them to keep running after exceptions that would
1761 enables them to keep running after exceptions that would
1762 otherwise kill their mainloop. This is a bother for IPython
1762 otherwise kill their mainloop. This is a bother for IPython
1763 which excepts to catch all of the program exceptions with a try:
1763 which excepts to catch all of the program exceptions with a try:
1764 except: statement.
1764 except: statement.
1765
1765
1766 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1766 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1767 any app directly invokes sys.excepthook, it will look to the user like
1767 any app directly invokes sys.excepthook, it will look to the user like
1768 IPython crashed. In order to work around this, we can disable the
1768 IPython crashed. In order to work around this, we can disable the
1769 CrashHandler and replace it with this excepthook instead, which prints a
1769 CrashHandler and replace it with this excepthook instead, which prints a
1770 regular traceback using our InteractiveTB. In this fashion, apps which
1770 regular traceback using our InteractiveTB. In this fashion, apps which
1771 call sys.excepthook will generate a regular-looking exception from
1771 call sys.excepthook will generate a regular-looking exception from
1772 IPython, and the CrashHandler will only be triggered by real IPython
1772 IPython, and the CrashHandler will only be triggered by real IPython
1773 crashes.
1773 crashes.
1774
1774
1775 This hook should be used sparingly, only in places which are not likely
1775 This hook should be used sparingly, only in places which are not likely
1776 to be true IPython errors.
1776 to be true IPython errors.
1777 """
1777 """
1778 self.showtraceback((etype, value, tb), tb_offset=0)
1778 self.showtraceback((etype, value, tb), tb_offset=0)
1779
1779
1780 def _get_exc_info(self, exc_tuple=None):
1780 def _get_exc_info(self, exc_tuple=None):
1781 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1781 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1782
1782
1783 Ensures sys.last_type,value,traceback hold the exc_info we found,
1783 Ensures sys.last_type,value,traceback hold the exc_info we found,
1784 from whichever source.
1784 from whichever source.
1785
1785
1786 raises ValueError if none of these contain any information
1786 raises ValueError if none of these contain any information
1787 """
1787 """
1788 if exc_tuple is None:
1788 if exc_tuple is None:
1789 etype, value, tb = sys.exc_info()
1789 etype, value, tb = sys.exc_info()
1790 else:
1790 else:
1791 etype, value, tb = exc_tuple
1791 etype, value, tb = exc_tuple
1792
1792
1793 if etype is None:
1793 if etype is None:
1794 if hasattr(sys, 'last_type'):
1794 if hasattr(sys, 'last_type'):
1795 etype, value, tb = sys.last_type, sys.last_value, \
1795 etype, value, tb = sys.last_type, sys.last_value, \
1796 sys.last_traceback
1796 sys.last_traceback
1797
1797
1798 if etype is None:
1798 if etype is None:
1799 raise ValueError("No exception to find")
1799 raise ValueError("No exception to find")
1800
1800
1801 # Now store the exception info in sys.last_type etc.
1801 # Now store the exception info in sys.last_type etc.
1802 # WARNING: these variables are somewhat deprecated and not
1802 # WARNING: these variables are somewhat deprecated and not
1803 # necessarily safe to use in a threaded environment, but tools
1803 # necessarily safe to use in a threaded environment, but tools
1804 # like pdb depend on their existence, so let's set them. If we
1804 # like pdb depend on their existence, so let's set them. If we
1805 # find problems in the field, we'll need to revisit their use.
1805 # find problems in the field, we'll need to revisit their use.
1806 sys.last_type = etype
1806 sys.last_type = etype
1807 sys.last_value = value
1807 sys.last_value = value
1808 sys.last_traceback = tb
1808 sys.last_traceback = tb
1809
1809
1810 return etype, value, tb
1810 return etype, value, tb
1811
1811
1812 def show_usage_error(self, exc):
1812 def show_usage_error(self, exc):
1813 """Show a short message for UsageErrors
1813 """Show a short message for UsageErrors
1814
1814
1815 These are special exceptions that shouldn't show a traceback.
1815 These are special exceptions that shouldn't show a traceback.
1816 """
1816 """
1817 print("UsageError: %s" % exc, file=sys.stderr)
1817 print("UsageError: %s" % exc, file=sys.stderr)
1818
1818
1819 def get_exception_only(self, exc_tuple=None):
1819 def get_exception_only(self, exc_tuple=None):
1820 """
1820 """
1821 Return as a string (ending with a newline) the exception that
1821 Return as a string (ending with a newline) the exception that
1822 just occurred, without any traceback.
1822 just occurred, without any traceback.
1823 """
1823 """
1824 etype, value, tb = self._get_exc_info(exc_tuple)
1824 etype, value, tb = self._get_exc_info(exc_tuple)
1825 msg = traceback.format_exception_only(etype, value)
1825 msg = traceback.format_exception_only(etype, value)
1826 return ''.join(msg)
1826 return ''.join(msg)
1827
1827
1828 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1828 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1829 exception_only=False, running_compiled_code=False):
1829 exception_only=False, running_compiled_code=False):
1830 """Display the exception that just occurred.
1830 """Display the exception that just occurred.
1831
1831
1832 If nothing is known about the exception, this is the method which
1832 If nothing is known about the exception, this is the method which
1833 should be used throughout the code for presenting user tracebacks,
1833 should be used throughout the code for presenting user tracebacks,
1834 rather than directly invoking the InteractiveTB object.
1834 rather than directly invoking the InteractiveTB object.
1835
1835
1836 A specific showsyntaxerror() also exists, but this method can take
1836 A specific showsyntaxerror() also exists, but this method can take
1837 care of calling it if needed, so unless you are explicitly catching a
1837 care of calling it if needed, so unless you are explicitly catching a
1838 SyntaxError exception, don't try to analyze the stack manually and
1838 SyntaxError exception, don't try to analyze the stack manually and
1839 simply call this method."""
1839 simply call this method."""
1840
1840
1841 try:
1841 try:
1842 try:
1842 try:
1843 etype, value, tb = self._get_exc_info(exc_tuple)
1843 etype, value, tb = self._get_exc_info(exc_tuple)
1844 except ValueError:
1844 except ValueError:
1845 print('No traceback available to show.', file=sys.stderr)
1845 print('No traceback available to show.', file=sys.stderr)
1846 return
1846 return
1847
1847
1848 if issubclass(etype, SyntaxError):
1848 if issubclass(etype, SyntaxError):
1849 # Though this won't be called by syntax errors in the input
1849 # Though this won't be called by syntax errors in the input
1850 # line, there may be SyntaxError cases with imported code.
1850 # line, there may be SyntaxError cases with imported code.
1851 self.showsyntaxerror(filename, running_compiled_code)
1851 self.showsyntaxerror(filename, running_compiled_code)
1852 elif etype is UsageError:
1852 elif etype is UsageError:
1853 self.show_usage_error(value)
1853 self.show_usage_error(value)
1854 else:
1854 else:
1855 if exception_only:
1855 if exception_only:
1856 stb = ['An exception has occurred, use %tb to see '
1856 stb = ['An exception has occurred, use %tb to see '
1857 'the full traceback.\n']
1857 'the full traceback.\n']
1858 stb.extend(self.InteractiveTB.get_exception_only(etype,
1858 stb.extend(self.InteractiveTB.get_exception_only(etype,
1859 value))
1859 value))
1860 else:
1860 else:
1861 try:
1861 try:
1862 # Exception classes can customise their traceback - we
1862 # Exception classes can customise their traceback - we
1863 # use this in IPython.parallel for exceptions occurring
1863 # use this in IPython.parallel for exceptions occurring
1864 # in the engines. This should return a list of strings.
1864 # in the engines. This should return a list of strings.
1865 stb = value._render_traceback_()
1865 stb = value._render_traceback_()
1866 except Exception:
1866 except Exception:
1867 stb = self.InteractiveTB.structured_traceback(etype,
1867 stb = self.InteractiveTB.structured_traceback(etype,
1868 value, tb, tb_offset=tb_offset)
1868 value, tb, tb_offset=tb_offset)
1869
1869
1870 self._showtraceback(etype, value, stb)
1870 self._showtraceback(etype, value, stb)
1871 if self.call_pdb:
1871 if self.call_pdb:
1872 # drop into debugger
1872 # drop into debugger
1873 self.debugger(force=True)
1873 self.debugger(force=True)
1874 return
1874 return
1875
1875
1876 # Actually show the traceback
1876 # Actually show the traceback
1877 self._showtraceback(etype, value, stb)
1877 self._showtraceback(etype, value, stb)
1878
1878
1879 except KeyboardInterrupt:
1879 except KeyboardInterrupt:
1880 print('\n' + self.get_exception_only(), file=sys.stderr)
1880 print('\n' + self.get_exception_only(), file=sys.stderr)
1881
1881
1882 def _showtraceback(self, etype, evalue, stb):
1882 def _showtraceback(self, etype, evalue, stb):
1883 """Actually show a traceback.
1883 """Actually show a traceback.
1884
1884
1885 Subclasses may override this method to put the traceback on a different
1885 Subclasses may override this method to put the traceback on a different
1886 place, like a side channel.
1886 place, like a side channel.
1887 """
1887 """
1888 print(self.InteractiveTB.stb2text(stb))
1888 print(self.InteractiveTB.stb2text(stb))
1889
1889
1890 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1890 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1891 """Display the syntax error that just occurred.
1891 """Display the syntax error that just occurred.
1892
1892
1893 This doesn't display a stack trace because there isn't one.
1893 This doesn't display a stack trace because there isn't one.
1894
1894
1895 If a filename is given, it is stuffed in the exception instead
1895 If a filename is given, it is stuffed in the exception instead
1896 of what was there before (because Python's parser always uses
1896 of what was there before (because Python's parser always uses
1897 "<string>" when reading from a string).
1897 "<string>" when reading from a string).
1898
1898
1899 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1899 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1900 longer stack trace will be displayed.
1900 longer stack trace will be displayed.
1901 """
1901 """
1902 etype, value, last_traceback = self._get_exc_info()
1902 etype, value, last_traceback = self._get_exc_info()
1903
1903
1904 if filename and issubclass(etype, SyntaxError):
1904 if filename and issubclass(etype, SyntaxError):
1905 try:
1905 try:
1906 value.filename = filename
1906 value.filename = filename
1907 except:
1907 except:
1908 # Not the format we expect; leave it alone
1908 # Not the format we expect; leave it alone
1909 pass
1909 pass
1910
1910
1911 # If the error occurred when executing compiled code, we should provide full stacktrace.
1911 # If the error occurred when executing compiled code, we should provide full stacktrace.
1912 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1912 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1913 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1913 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1914 self._showtraceback(etype, value, stb)
1914 self._showtraceback(etype, value, stb)
1915
1915
1916 # This is overridden in TerminalInteractiveShell to show a message about
1916 # This is overridden in TerminalInteractiveShell to show a message about
1917 # the %paste magic.
1917 # the %paste magic.
1918 def showindentationerror(self):
1918 def showindentationerror(self):
1919 """Called by _run_cell when there's an IndentationError in code entered
1919 """Called by _run_cell when there's an IndentationError in code entered
1920 at the prompt.
1920 at the prompt.
1921
1921
1922 This is overridden in TerminalInteractiveShell to show a message about
1922 This is overridden in TerminalInteractiveShell to show a message about
1923 the %paste magic."""
1923 the %paste magic."""
1924 self.showsyntaxerror()
1924 self.showsyntaxerror()
1925
1925
1926 #-------------------------------------------------------------------------
1926 #-------------------------------------------------------------------------
1927 # Things related to readline
1927 # Things related to readline
1928 #-------------------------------------------------------------------------
1928 #-------------------------------------------------------------------------
1929
1929
1930 def init_readline(self):
1930 def init_readline(self):
1931 """DEPRECATED
1931 """DEPRECATED
1932
1932
1933 Moved to terminal subclass, here only to simplify the init logic."""
1933 Moved to terminal subclass, here only to simplify the init logic."""
1934 # Set a number of methods that depend on readline to be no-op
1934 # Set a number of methods that depend on readline to be no-op
1935 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1935 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1936 DeprecationWarning, stacklevel=2)
1936 DeprecationWarning, stacklevel=2)
1937 self.set_custom_completer = no_op
1937 self.set_custom_completer = no_op
1938
1938
1939 @skip_doctest
1939 @skip_doctest
1940 def set_next_input(self, s, replace=False):
1940 def set_next_input(self, s, replace=False):
1941 """ Sets the 'default' input string for the next command line.
1941 """ Sets the 'default' input string for the next command line.
1942
1942
1943 Example::
1943 Example::
1944
1944
1945 In [1]: _ip.set_next_input("Hello Word")
1945 In [1]: _ip.set_next_input("Hello Word")
1946 In [2]: Hello Word_ # cursor is here
1946 In [2]: Hello Word_ # cursor is here
1947 """
1947 """
1948 self.rl_next_input = s
1948 self.rl_next_input = s
1949
1949
1950 def _indent_current_str(self):
1950 def _indent_current_str(self):
1951 """return the current level of indentation as a string"""
1951 """return the current level of indentation as a string"""
1952 return self.input_splitter.get_indent_spaces() * ' '
1952 return self.input_splitter.get_indent_spaces() * ' '
1953
1953
1954 #-------------------------------------------------------------------------
1954 #-------------------------------------------------------------------------
1955 # Things related to text completion
1955 # Things related to text completion
1956 #-------------------------------------------------------------------------
1956 #-------------------------------------------------------------------------
1957
1957
1958 def init_completer(self):
1958 def init_completer(self):
1959 """Initialize the completion machinery.
1959 """Initialize the completion machinery.
1960
1960
1961 This creates completion machinery that can be used by client code,
1961 This creates completion machinery that can be used by client code,
1962 either interactively in-process (typically triggered by the readline
1962 either interactively in-process (typically triggered by the readline
1963 library), programmatically (such as in test suites) or out-of-process
1963 library), programmatically (such as in test suites) or out-of-process
1964 (typically over the network by remote frontends).
1964 (typically over the network by remote frontends).
1965 """
1965 """
1966 from IPython.core.completer import IPCompleter
1966 from IPython.core.completer import IPCompleter
1967 from IPython.core.completerlib import (module_completer,
1967 from IPython.core.completerlib import (module_completer,
1968 magic_run_completer, cd_completer, reset_completer)
1968 magic_run_completer, cd_completer, reset_completer)
1969
1969
1970 self.Completer = IPCompleter(shell=self,
1970 self.Completer = IPCompleter(shell=self,
1971 namespace=self.user_ns,
1971 namespace=self.user_ns,
1972 global_namespace=self.user_global_ns,
1972 global_namespace=self.user_global_ns,
1973 parent=self,
1973 parent=self,
1974 )
1974 )
1975 self.configurables.append(self.Completer)
1975 self.configurables.append(self.Completer)
1976
1976
1977 # Add custom completers to the basic ones built into IPCompleter
1977 # Add custom completers to the basic ones built into IPCompleter
1978 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1978 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1979 self.strdispatchers['complete_command'] = sdisp
1979 self.strdispatchers['complete_command'] = sdisp
1980 self.Completer.custom_completers = sdisp
1980 self.Completer.custom_completers = sdisp
1981
1981
1982 self.set_hook('complete_command', module_completer, str_key = 'import')
1982 self.set_hook('complete_command', module_completer, str_key = 'import')
1983 self.set_hook('complete_command', module_completer, str_key = 'from')
1983 self.set_hook('complete_command', module_completer, str_key = 'from')
1984 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1984 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1985 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1985 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1986 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1986 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1987 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1987 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1988
1988
1989
1989
1990 @skip_doctest
1990 @skip_doctest
1991 def complete(self, text, line=None, cursor_pos=None):
1991 def complete(self, text, line=None, cursor_pos=None):
1992 """Return the completed text and a list of completions.
1992 """Return the completed text and a list of completions.
1993
1993
1994 Parameters
1994 Parameters
1995 ----------
1995 ----------
1996
1996
1997 text : string
1997 text : string
1998 A string of text to be completed on. It can be given as empty and
1998 A string of text to be completed on. It can be given as empty and
1999 instead a line/position pair are given. In this case, the
1999 instead a line/position pair are given. In this case, the
2000 completer itself will split the line like readline does.
2000 completer itself will split the line like readline does.
2001
2001
2002 line : string, optional
2002 line : string, optional
2003 The complete line that text is part of.
2003 The complete line that text is part of.
2004
2004
2005 cursor_pos : int, optional
2005 cursor_pos : int, optional
2006 The position of the cursor on the input line.
2006 The position of the cursor on the input line.
2007
2007
2008 Returns
2008 Returns
2009 -------
2009 -------
2010 text : string
2010 text : string
2011 The actual text that was completed.
2011 The actual text that was completed.
2012
2012
2013 matches : list
2013 matches : list
2014 A sorted list with all possible completions.
2014 A sorted list with all possible completions.
2015
2015
2016 The optional arguments allow the completion to take more context into
2016 The optional arguments allow the completion to take more context into
2017 account, and are part of the low-level completion API.
2017 account, and are part of the low-level completion API.
2018
2018
2019 This is a wrapper around the completion mechanism, similar to what
2019 This is a wrapper around the completion mechanism, similar to what
2020 readline does at the command line when the TAB key is hit. By
2020 readline does at the command line when the TAB key is hit. By
2021 exposing it as a method, it can be used by other non-readline
2021 exposing it as a method, it can be used by other non-readline
2022 environments (such as GUIs) for text completion.
2022 environments (such as GUIs) for text completion.
2023
2023
2024 Simple usage example:
2024 Simple usage example:
2025
2025
2026 In [1]: x = 'hello'
2026 In [1]: x = 'hello'
2027
2027
2028 In [2]: _ip.complete('x.l')
2028 In [2]: _ip.complete('x.l')
2029 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2029 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2030 """
2030 """
2031
2031
2032 # Inject names into __builtin__ so we can complete on the added names.
2032 # Inject names into __builtin__ so we can complete on the added names.
2033 with self.builtin_trap:
2033 with self.builtin_trap:
2034 return self.Completer.complete(text, line, cursor_pos)
2034 return self.Completer.complete(text, line, cursor_pos)
2035
2035
2036 def set_custom_completer(self, completer, pos=0):
2036 def set_custom_completer(self, completer, pos=0):
2037 """Adds a new custom completer function.
2037 """Adds a new custom completer function.
2038
2038
2039 The position argument (defaults to 0) is the index in the completers
2039 The position argument (defaults to 0) is the index in the completers
2040 list where you want the completer to be inserted."""
2040 list where you want the completer to be inserted."""
2041
2041
2042 newcomp = types.MethodType(completer,self.Completer)
2042 newcomp = types.MethodType(completer,self.Completer)
2043 self.Completer.matchers.insert(pos,newcomp)
2043 self.Completer.matchers.insert(pos,newcomp)
2044
2044
2045 def set_completer_frame(self, frame=None):
2045 def set_completer_frame(self, frame=None):
2046 """Set the frame of the completer."""
2046 """Set the frame of the completer."""
2047 if frame:
2047 if frame:
2048 self.Completer.namespace = frame.f_locals
2048 self.Completer.namespace = frame.f_locals
2049 self.Completer.global_namespace = frame.f_globals
2049 self.Completer.global_namespace = frame.f_globals
2050 else:
2050 else:
2051 self.Completer.namespace = self.user_ns
2051 self.Completer.namespace = self.user_ns
2052 self.Completer.global_namespace = self.user_global_ns
2052 self.Completer.global_namespace = self.user_global_ns
2053
2053
2054 #-------------------------------------------------------------------------
2054 #-------------------------------------------------------------------------
2055 # Things related to magics
2055 # Things related to magics
2056 #-------------------------------------------------------------------------
2056 #-------------------------------------------------------------------------
2057
2057
2058 def init_magics(self):
2058 def init_magics(self):
2059 from IPython.core import magics as m
2059 from IPython.core import magics as m
2060 self.magics_manager = magic.MagicsManager(shell=self,
2060 self.magics_manager = magic.MagicsManager(shell=self,
2061 parent=self,
2061 parent=self,
2062 user_magics=m.UserMagics(self))
2062 user_magics=m.UserMagics(self))
2063 self.configurables.append(self.magics_manager)
2063 self.configurables.append(self.magics_manager)
2064
2064
2065 # Expose as public API from the magics manager
2065 # Expose as public API from the magics manager
2066 self.register_magics = self.magics_manager.register
2066 self.register_magics = self.magics_manager.register
2067
2067
2068 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2068 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2069 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2069 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2070 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2070 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2071 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2071 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2072 )
2072 )
2073
2073
2074 # Register Magic Aliases
2074 # Register Magic Aliases
2075 mman = self.magics_manager
2075 mman = self.magics_manager
2076 # FIXME: magic aliases should be defined by the Magics classes
2076 # FIXME: magic aliases should be defined by the Magics classes
2077 # or in MagicsManager, not here
2077 # or in MagicsManager, not here
2078 mman.register_alias('ed', 'edit')
2078 mman.register_alias('ed', 'edit')
2079 mman.register_alias('hist', 'history')
2079 mman.register_alias('hist', 'history')
2080 mman.register_alias('rep', 'recall')
2080 mman.register_alias('rep', 'recall')
2081 mman.register_alias('SVG', 'svg', 'cell')
2081 mman.register_alias('SVG', 'svg', 'cell')
2082 mman.register_alias('HTML', 'html', 'cell')
2082 mman.register_alias('HTML', 'html', 'cell')
2083 mman.register_alias('file', 'writefile', 'cell')
2083 mman.register_alias('file', 'writefile', 'cell')
2084
2084
2085 # FIXME: Move the color initialization to the DisplayHook, which
2085 # FIXME: Move the color initialization to the DisplayHook, which
2086 # should be split into a prompt manager and displayhook. We probably
2086 # should be split into a prompt manager and displayhook. We probably
2087 # even need a centralize colors management object.
2087 # even need a centralize colors management object.
2088 self.run_line_magic('colors', self.colors)
2088 self.run_line_magic('colors', self.colors)
2089
2089
2090 # Defined here so that it's included in the documentation
2090 # Defined here so that it's included in the documentation
2091 @functools.wraps(magic.MagicsManager.register_function)
2091 @functools.wraps(magic.MagicsManager.register_function)
2092 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2092 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2093 self.magics_manager.register_function(func,
2093 self.magics_manager.register_function(func,
2094 magic_kind=magic_kind, magic_name=magic_name)
2094 magic_kind=magic_kind, magic_name=magic_name)
2095
2095
2096 def run_line_magic(self, magic_name, line, _stack_depth=1):
2096 def run_line_magic(self, magic_name, line, _stack_depth=1):
2097 """Execute the given line magic.
2097 """Execute the given line magic.
2098
2098
2099 Parameters
2099 Parameters
2100 ----------
2100 ----------
2101 magic_name : str
2101 magic_name : str
2102 Name of the desired magic function, without '%' prefix.
2102 Name of the desired magic function, without '%' prefix.
2103
2103
2104 line : str
2104 line : str
2105 The rest of the input line as a single string.
2105 The rest of the input line as a single string.
2106
2106
2107 _stack_depth : int
2107 _stack_depth : int
2108 If run_line_magic() is called from magic() then _stack_depth=2.
2108 If run_line_magic() is called from magic() then _stack_depth=2.
2109 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2109 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2110 """
2110 """
2111 fn = self.find_line_magic(magic_name)
2111 fn = self.find_line_magic(magic_name)
2112 if fn is None:
2112 if fn is None:
2113 cm = self.find_cell_magic(magic_name)
2113 cm = self.find_cell_magic(magic_name)
2114 etpl = "Line magic function `%%%s` not found%s."
2114 etpl = "Line magic function `%%%s` not found%s."
2115 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2115 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2116 'did you mean that instead?)' % magic_name )
2116 'did you mean that instead?)' % magic_name )
2117 raise UsageError(etpl % (magic_name, extra))
2117 raise UsageError(etpl % (magic_name, extra))
2118 else:
2118 else:
2119 # Note: this is the distance in the stack to the user's frame.
2119 # Note: this is the distance in the stack to the user's frame.
2120 # This will need to be updated if the internal calling logic gets
2120 # This will need to be updated if the internal calling logic gets
2121 # refactored, or else we'll be expanding the wrong variables.
2121 # refactored, or else we'll be expanding the wrong variables.
2122
2122
2123 # Determine stack_depth depending on where run_line_magic() has been called
2123 # Determine stack_depth depending on where run_line_magic() has been called
2124 stack_depth = _stack_depth
2124 stack_depth = _stack_depth
2125 magic_arg_s = self.var_expand(line, stack_depth)
2125 magic_arg_s = self.var_expand(line, stack_depth)
2126 # Put magic args in a list so we can call with f(*a) syntax
2126 # Put magic args in a list so we can call with f(*a) syntax
2127 args = [magic_arg_s]
2127 args = [magic_arg_s]
2128 kwargs = {}
2128 kwargs = {}
2129 # Grab local namespace if we need it:
2129 # Grab local namespace if we need it:
2130 if getattr(fn, "needs_local_scope", False):
2130 if getattr(fn, "needs_local_scope", False):
2131 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2131 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2132 with self.builtin_trap:
2132 with self.builtin_trap:
2133 result = fn(*args,**kwargs)
2133 result = fn(*args,**kwargs)
2134 return result
2134 return result
2135
2135
2136 def run_cell_magic(self, magic_name, line, cell):
2136 def run_cell_magic(self, magic_name, line, cell):
2137 """Execute the given cell magic.
2137 """Execute the given cell magic.
2138
2138
2139 Parameters
2139 Parameters
2140 ----------
2140 ----------
2141 magic_name : str
2141 magic_name : str
2142 Name of the desired magic function, without '%' prefix.
2142 Name of the desired magic function, without '%' prefix.
2143
2143
2144 line : str
2144 line : str
2145 The rest of the first input line as a single string.
2145 The rest of the first input line as a single string.
2146
2146
2147 cell : str
2147 cell : str
2148 The body of the cell as a (possibly multiline) string.
2148 The body of the cell as a (possibly multiline) string.
2149 """
2149 """
2150 fn = self.find_cell_magic(magic_name)
2150 fn = self.find_cell_magic(magic_name)
2151 if fn is None:
2151 if fn is None:
2152 lm = self.find_line_magic(magic_name)
2152 lm = self.find_line_magic(magic_name)
2153 etpl = "Cell magic `%%{0}` not found{1}."
2153 etpl = "Cell magic `%%{0}` not found{1}."
2154 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2154 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2155 'did you mean that instead?)'.format(magic_name))
2155 'did you mean that instead?)'.format(magic_name))
2156 raise UsageError(etpl.format(magic_name, extra))
2156 raise UsageError(etpl.format(magic_name, extra))
2157 elif cell == '':
2157 elif cell == '':
2158 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2158 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2159 if self.find_line_magic(magic_name) is not None:
2159 if self.find_line_magic(magic_name) is not None:
2160 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2160 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2161 raise UsageError(message)
2161 raise UsageError(message)
2162 else:
2162 else:
2163 # Note: this is the distance in the stack to the user's frame.
2163 # Note: this is the distance in the stack to the user's frame.
2164 # This will need to be updated if the internal calling logic gets
2164 # This will need to be updated if the internal calling logic gets
2165 # refactored, or else we'll be expanding the wrong variables.
2165 # refactored, or else we'll be expanding the wrong variables.
2166 stack_depth = 2
2166 stack_depth = 2
2167 magic_arg_s = self.var_expand(line, stack_depth)
2167 magic_arg_s = self.var_expand(line, stack_depth)
2168 with self.builtin_trap:
2168 with self.builtin_trap:
2169 result = fn(magic_arg_s, cell)
2169 result = fn(magic_arg_s, cell)
2170 return result
2170 return result
2171
2171
2172 def find_line_magic(self, magic_name):
2172 def find_line_magic(self, magic_name):
2173 """Find and return a line magic by name.
2173 """Find and return a line magic by name.
2174
2174
2175 Returns None if the magic isn't found."""
2175 Returns None if the magic isn't found."""
2176 return self.magics_manager.magics['line'].get(magic_name)
2176 return self.magics_manager.magics['line'].get(magic_name)
2177
2177
2178 def find_cell_magic(self, magic_name):
2178 def find_cell_magic(self, magic_name):
2179 """Find and return a cell magic by name.
2179 """Find and return a cell magic by name.
2180
2180
2181 Returns None if the magic isn't found."""
2181 Returns None if the magic isn't found."""
2182 return self.magics_manager.magics['cell'].get(magic_name)
2182 return self.magics_manager.magics['cell'].get(magic_name)
2183
2183
2184 def find_magic(self, magic_name, magic_kind='line'):
2184 def find_magic(self, magic_name, magic_kind='line'):
2185 """Find and return a magic of the given type by name.
2185 """Find and return a magic of the given type by name.
2186
2186
2187 Returns None if the magic isn't found."""
2187 Returns None if the magic isn't found."""
2188 return self.magics_manager.magics[magic_kind].get(magic_name)
2188 return self.magics_manager.magics[magic_kind].get(magic_name)
2189
2189
2190 def magic(self, arg_s):
2190 def magic(self, arg_s):
2191 """DEPRECATED. Use run_line_magic() instead.
2191 """DEPRECATED. Use run_line_magic() instead.
2192
2192
2193 Call a magic function by name.
2193 Call a magic function by name.
2194
2194
2195 Input: a string containing the name of the magic function to call and
2195 Input: a string containing the name of the magic function to call and
2196 any additional arguments to be passed to the magic.
2196 any additional arguments to be passed to the magic.
2197
2197
2198 magic('name -opt foo bar') is equivalent to typing at the ipython
2198 magic('name -opt foo bar') is equivalent to typing at the ipython
2199 prompt:
2199 prompt:
2200
2200
2201 In[1]: %name -opt foo bar
2201 In[1]: %name -opt foo bar
2202
2202
2203 To call a magic without arguments, simply use magic('name').
2203 To call a magic without arguments, simply use magic('name').
2204
2204
2205 This provides a proper Python function to call IPython's magics in any
2205 This provides a proper Python function to call IPython's magics in any
2206 valid Python code you can type at the interpreter, including loops and
2206 valid Python code you can type at the interpreter, including loops and
2207 compound statements.
2207 compound statements.
2208 """
2208 """
2209 # TODO: should we issue a loud deprecation warning here?
2209 # TODO: should we issue a loud deprecation warning here?
2210 magic_name, _, magic_arg_s = arg_s.partition(' ')
2210 magic_name, _, magic_arg_s = arg_s.partition(' ')
2211 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2211 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2212 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2212 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2213
2213
2214 #-------------------------------------------------------------------------
2214 #-------------------------------------------------------------------------
2215 # Things related to macros
2215 # Things related to macros
2216 #-------------------------------------------------------------------------
2216 #-------------------------------------------------------------------------
2217
2217
2218 def define_macro(self, name, themacro):
2218 def define_macro(self, name, themacro):
2219 """Define a new macro
2219 """Define a new macro
2220
2220
2221 Parameters
2221 Parameters
2222 ----------
2222 ----------
2223 name : str
2223 name : str
2224 The name of the macro.
2224 The name of the macro.
2225 themacro : str or Macro
2225 themacro : str or Macro
2226 The action to do upon invoking the macro. If a string, a new
2226 The action to do upon invoking the macro. If a string, a new
2227 Macro object is created by passing the string to it.
2227 Macro object is created by passing the string to it.
2228 """
2228 """
2229
2229
2230 from IPython.core import macro
2230 from IPython.core import macro
2231
2231
2232 if isinstance(themacro, str):
2232 if isinstance(themacro, str):
2233 themacro = macro.Macro(themacro)
2233 themacro = macro.Macro(themacro)
2234 if not isinstance(themacro, macro.Macro):
2234 if not isinstance(themacro, macro.Macro):
2235 raise ValueError('A macro must be a string or a Macro instance.')
2235 raise ValueError('A macro must be a string or a Macro instance.')
2236 self.user_ns[name] = themacro
2236 self.user_ns[name] = themacro
2237
2237
2238 #-------------------------------------------------------------------------
2238 #-------------------------------------------------------------------------
2239 # Things related to the running of system commands
2239 # Things related to the running of system commands
2240 #-------------------------------------------------------------------------
2240 #-------------------------------------------------------------------------
2241
2241
2242 def system_piped(self, cmd):
2242 def system_piped(self, cmd):
2243 """Call the given cmd in a subprocess, piping stdout/err
2243 """Call the given cmd in a subprocess, piping stdout/err
2244
2244
2245 Parameters
2245 Parameters
2246 ----------
2246 ----------
2247 cmd : str
2247 cmd : str
2248 Command to execute (can not end in '&', as background processes are
2248 Command to execute (can not end in '&', as background processes are
2249 not supported. Should not be a command that expects input
2249 not supported. Should not be a command that expects input
2250 other than simple text.
2250 other than simple text.
2251 """
2251 """
2252 if cmd.rstrip().endswith('&'):
2252 if cmd.rstrip().endswith('&'):
2253 # this is *far* from a rigorous test
2253 # this is *far* from a rigorous test
2254 # We do not support backgrounding processes because we either use
2254 # We do not support backgrounding processes because we either use
2255 # pexpect or pipes to read from. Users can always just call
2255 # pexpect or pipes to read from. Users can always just call
2256 # os.system() or use ip.system=ip.system_raw
2256 # os.system() or use ip.system=ip.system_raw
2257 # if they really want a background process.
2257 # if they really want a background process.
2258 raise OSError("Background processes not supported.")
2258 raise OSError("Background processes not supported.")
2259
2259
2260 # we explicitly do NOT return the subprocess status code, because
2260 # we explicitly do NOT return the subprocess status code, because
2261 # a non-None value would trigger :func:`sys.displayhook` calls.
2261 # a non-None value would trigger :func:`sys.displayhook` calls.
2262 # Instead, we store the exit_code in user_ns.
2262 # Instead, we store the exit_code in user_ns.
2263 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2263 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2264
2264
2265 def system_raw(self, cmd):
2265 def system_raw(self, cmd):
2266 """Call the given cmd in a subprocess using os.system on Windows or
2266 """Call the given cmd in a subprocess using os.system on Windows or
2267 subprocess.call using the system shell on other platforms.
2267 subprocess.call using the system shell on other platforms.
2268
2268
2269 Parameters
2269 Parameters
2270 ----------
2270 ----------
2271 cmd : str
2271 cmd : str
2272 Command to execute.
2272 Command to execute.
2273 """
2273 """
2274 cmd = self.var_expand(cmd, depth=1)
2274 cmd = self.var_expand(cmd, depth=1)
2275 # protect os.system from UNC paths on Windows, which it can't handle:
2275 # protect os.system from UNC paths on Windows, which it can't handle:
2276 if sys.platform == 'win32':
2276 if sys.platform == 'win32':
2277 from IPython.utils._process_win32 import AvoidUNCPath
2277 from IPython.utils._process_win32 import AvoidUNCPath
2278 with AvoidUNCPath() as path:
2278 with AvoidUNCPath() as path:
2279 if path is not None:
2279 if path is not None:
2280 cmd = '"pushd %s &&"%s' % (path, cmd)
2280 cmd = '"pushd %s &&"%s' % (path, cmd)
2281 try:
2281 try:
2282 ec = os.system(cmd)
2282 ec = os.system(cmd)
2283 except KeyboardInterrupt:
2283 except KeyboardInterrupt:
2284 print('\n' + self.get_exception_only(), file=sys.stderr)
2284 print('\n' + self.get_exception_only(), file=sys.stderr)
2285 ec = -2
2285 ec = -2
2286 else:
2286 else:
2287 # For posix the result of the subprocess.call() below is an exit
2287 # For posix the result of the subprocess.call() below is an exit
2288 # code, which by convention is zero for success, positive for
2288 # code, which by convention is zero for success, positive for
2289 # program failure. Exit codes above 128 are reserved for signals,
2289 # program failure. Exit codes above 128 are reserved for signals,
2290 # and the formula for converting a signal to an exit code is usually
2290 # and the formula for converting a signal to an exit code is usually
2291 # signal_number+128. To more easily differentiate between exit
2291 # signal_number+128. To more easily differentiate between exit
2292 # codes and signals, ipython uses negative numbers. For instance
2292 # codes and signals, ipython uses negative numbers. For instance
2293 # since control-c is signal 2 but exit code 130, ipython's
2293 # since control-c is signal 2 but exit code 130, ipython's
2294 # _exit_code variable will read -2. Note that some shells like
2294 # _exit_code variable will read -2. Note that some shells like
2295 # csh and fish don't follow sh/bash conventions for exit codes.
2295 # csh and fish don't follow sh/bash conventions for exit codes.
2296 executable = os.environ.get('SHELL', None)
2296 executable = os.environ.get('SHELL', None)
2297 try:
2297 try:
2298 # Use env shell instead of default /bin/sh
2298 # Use env shell instead of default /bin/sh
2299 ec = subprocess.call(cmd, shell=True, executable=executable)
2299 ec = subprocess.call(cmd, shell=True, executable=executable)
2300 except KeyboardInterrupt:
2300 except KeyboardInterrupt:
2301 # intercept control-C; a long traceback is not useful here
2301 # intercept control-C; a long traceback is not useful here
2302 print('\n' + self.get_exception_only(), file=sys.stderr)
2302 print('\n' + self.get_exception_only(), file=sys.stderr)
2303 ec = 130
2303 ec = 130
2304 if ec > 128:
2304 if ec > 128:
2305 ec = -(ec - 128)
2305 ec = -(ec - 128)
2306
2306
2307 # We explicitly do NOT return the subprocess status code, because
2307 # We explicitly do NOT return the subprocess status code, because
2308 # a non-None value would trigger :func:`sys.displayhook` calls.
2308 # a non-None value would trigger :func:`sys.displayhook` calls.
2309 # Instead, we store the exit_code in user_ns. Note the semantics
2309 # Instead, we store the exit_code in user_ns. Note the semantics
2310 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2310 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2311 # but raising SystemExit(_exit_code) will give status 254!
2311 # but raising SystemExit(_exit_code) will give status 254!
2312 self.user_ns['_exit_code'] = ec
2312 self.user_ns['_exit_code'] = ec
2313
2313
2314 # use piped system by default, because it is better behaved
2314 # use piped system by default, because it is better behaved
2315 system = system_piped
2315 system = system_piped
2316
2316
2317 def getoutput(self, cmd, split=True, depth=0):
2317 def getoutput(self, cmd, split=True, depth=0):
2318 """Get output (possibly including stderr) from a subprocess.
2318 """Get output (possibly including stderr) from a subprocess.
2319
2319
2320 Parameters
2320 Parameters
2321 ----------
2321 ----------
2322 cmd : str
2322 cmd : str
2323 Command to execute (can not end in '&', as background processes are
2323 Command to execute (can not end in '&', as background processes are
2324 not supported.
2324 not supported.
2325 split : bool, optional
2325 split : bool, optional
2326 If True, split the output into an IPython SList. Otherwise, an
2326 If True, split the output into an IPython SList. Otherwise, an
2327 IPython LSString is returned. These are objects similar to normal
2327 IPython LSString is returned. These are objects similar to normal
2328 lists and strings, with a few convenience attributes for easier
2328 lists and strings, with a few convenience attributes for easier
2329 manipulation of line-based output. You can use '?' on them for
2329 manipulation of line-based output. You can use '?' on them for
2330 details.
2330 details.
2331 depth : int, optional
2331 depth : int, optional
2332 How many frames above the caller are the local variables which should
2332 How many frames above the caller are the local variables which should
2333 be expanded in the command string? The default (0) assumes that the
2333 be expanded in the command string? The default (0) assumes that the
2334 expansion variables are in the stack frame calling this function.
2334 expansion variables are in the stack frame calling this function.
2335 """
2335 """
2336 if cmd.rstrip().endswith('&'):
2336 if cmd.rstrip().endswith('&'):
2337 # this is *far* from a rigorous test
2337 # this is *far* from a rigorous test
2338 raise OSError("Background processes not supported.")
2338 raise OSError("Background processes not supported.")
2339 out = getoutput(self.var_expand(cmd, depth=depth+1))
2339 out = getoutput(self.var_expand(cmd, depth=depth+1))
2340 if split:
2340 if split:
2341 out = SList(out.splitlines())
2341 out = SList(out.splitlines())
2342 else:
2342 else:
2343 out = LSString(out)
2343 out = LSString(out)
2344 return out
2344 return out
2345
2345
2346 #-------------------------------------------------------------------------
2346 #-------------------------------------------------------------------------
2347 # Things related to aliases
2347 # Things related to aliases
2348 #-------------------------------------------------------------------------
2348 #-------------------------------------------------------------------------
2349
2349
2350 def init_alias(self):
2350 def init_alias(self):
2351 self.alias_manager = AliasManager(shell=self, parent=self)
2351 self.alias_manager = AliasManager(shell=self, parent=self)
2352 self.configurables.append(self.alias_manager)
2352 self.configurables.append(self.alias_manager)
2353
2353
2354 #-------------------------------------------------------------------------
2354 #-------------------------------------------------------------------------
2355 # Things related to extensions
2355 # Things related to extensions
2356 #-------------------------------------------------------------------------
2356 #-------------------------------------------------------------------------
2357
2357
2358 def init_extension_manager(self):
2358 def init_extension_manager(self):
2359 self.extension_manager = ExtensionManager(shell=self, parent=self)
2359 self.extension_manager = ExtensionManager(shell=self, parent=self)
2360 self.configurables.append(self.extension_manager)
2360 self.configurables.append(self.extension_manager)
2361
2361
2362 #-------------------------------------------------------------------------
2362 #-------------------------------------------------------------------------
2363 # Things related to payloads
2363 # Things related to payloads
2364 #-------------------------------------------------------------------------
2364 #-------------------------------------------------------------------------
2365
2365
2366 def init_payload(self):
2366 def init_payload(self):
2367 self.payload_manager = PayloadManager(parent=self)
2367 self.payload_manager = PayloadManager(parent=self)
2368 self.configurables.append(self.payload_manager)
2368 self.configurables.append(self.payload_manager)
2369
2369
2370 #-------------------------------------------------------------------------
2370 #-------------------------------------------------------------------------
2371 # Things related to the prefilter
2371 # Things related to the prefilter
2372 #-------------------------------------------------------------------------
2372 #-------------------------------------------------------------------------
2373
2373
2374 def init_prefilter(self):
2374 def init_prefilter(self):
2375 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2375 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2376 self.configurables.append(self.prefilter_manager)
2376 self.configurables.append(self.prefilter_manager)
2377 # Ultimately this will be refactored in the new interpreter code, but
2377 # Ultimately this will be refactored in the new interpreter code, but
2378 # for now, we should expose the main prefilter method (there's legacy
2378 # for now, we should expose the main prefilter method (there's legacy
2379 # code out there that may rely on this).
2379 # code out there that may rely on this).
2380 self.prefilter = self.prefilter_manager.prefilter_lines
2380 self.prefilter = self.prefilter_manager.prefilter_lines
2381
2381
2382 def auto_rewrite_input(self, cmd):
2382 def auto_rewrite_input(self, cmd):
2383 """Print to the screen the rewritten form of the user's command.
2383 """Print to the screen the rewritten form of the user's command.
2384
2384
2385 This shows visual feedback by rewriting input lines that cause
2385 This shows visual feedback by rewriting input lines that cause
2386 automatic calling to kick in, like::
2386 automatic calling to kick in, like::
2387
2387
2388 /f x
2388 /f x
2389
2389
2390 into::
2390 into::
2391
2391
2392 ------> f(x)
2392 ------> f(x)
2393
2393
2394 after the user's input prompt. This helps the user understand that the
2394 after the user's input prompt. This helps the user understand that the
2395 input line was transformed automatically by IPython.
2395 input line was transformed automatically by IPython.
2396 """
2396 """
2397 if not self.show_rewritten_input:
2397 if not self.show_rewritten_input:
2398 return
2398 return
2399
2399
2400 # This is overridden in TerminalInteractiveShell to use fancy prompts
2400 # This is overridden in TerminalInteractiveShell to use fancy prompts
2401 print("------> " + cmd)
2401 print("------> " + cmd)
2402
2402
2403 #-------------------------------------------------------------------------
2403 #-------------------------------------------------------------------------
2404 # Things related to extracting values/expressions from kernel and user_ns
2404 # Things related to extracting values/expressions from kernel and user_ns
2405 #-------------------------------------------------------------------------
2405 #-------------------------------------------------------------------------
2406
2406
2407 def _user_obj_error(self):
2407 def _user_obj_error(self):
2408 """return simple exception dict
2408 """return simple exception dict
2409
2409
2410 for use in user_expressions
2410 for use in user_expressions
2411 """
2411 """
2412
2412
2413 etype, evalue, tb = self._get_exc_info()
2413 etype, evalue, tb = self._get_exc_info()
2414 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2414 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2415
2415
2416 exc_info = {
2416 exc_info = {
2417 u'status' : 'error',
2417 u'status' : 'error',
2418 u'traceback' : stb,
2418 u'traceback' : stb,
2419 u'ename' : etype.__name__,
2419 u'ename' : etype.__name__,
2420 u'evalue' : py3compat.safe_unicode(evalue),
2420 u'evalue' : py3compat.safe_unicode(evalue),
2421 }
2421 }
2422
2422
2423 return exc_info
2423 return exc_info
2424
2424
2425 def _format_user_obj(self, obj):
2425 def _format_user_obj(self, obj):
2426 """format a user object to display dict
2426 """format a user object to display dict
2427
2427
2428 for use in user_expressions
2428 for use in user_expressions
2429 """
2429 """
2430
2430
2431 data, md = self.display_formatter.format(obj)
2431 data, md = self.display_formatter.format(obj)
2432 value = {
2432 value = {
2433 'status' : 'ok',
2433 'status' : 'ok',
2434 'data' : data,
2434 'data' : data,
2435 'metadata' : md,
2435 'metadata' : md,
2436 }
2436 }
2437 return value
2437 return value
2438
2438
2439 def user_expressions(self, expressions):
2439 def user_expressions(self, expressions):
2440 """Evaluate a dict of expressions in the user's namespace.
2440 """Evaluate a dict of expressions in the user's namespace.
2441
2441
2442 Parameters
2442 Parameters
2443 ----------
2443 ----------
2444 expressions : dict
2444 expressions : dict
2445 A dict with string keys and string values. The expression values
2445 A dict with string keys and string values. The expression values
2446 should be valid Python expressions, each of which will be evaluated
2446 should be valid Python expressions, each of which will be evaluated
2447 in the user namespace.
2447 in the user namespace.
2448
2448
2449 Returns
2449 Returns
2450 -------
2450 -------
2451 A dict, keyed like the input expressions dict, with the rich mime-typed
2451 A dict, keyed like the input expressions dict, with the rich mime-typed
2452 display_data of each value.
2452 display_data of each value.
2453 """
2453 """
2454 out = {}
2454 out = {}
2455 user_ns = self.user_ns
2455 user_ns = self.user_ns
2456 global_ns = self.user_global_ns
2456 global_ns = self.user_global_ns
2457
2457
2458 for key, expr in expressions.items():
2458 for key, expr in expressions.items():
2459 try:
2459 try:
2460 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2460 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2461 except:
2461 except:
2462 value = self._user_obj_error()
2462 value = self._user_obj_error()
2463 out[key] = value
2463 out[key] = value
2464 return out
2464 return out
2465
2465
2466 #-------------------------------------------------------------------------
2466 #-------------------------------------------------------------------------
2467 # Things related to the running of code
2467 # Things related to the running of code
2468 #-------------------------------------------------------------------------
2468 #-------------------------------------------------------------------------
2469
2469
2470 def ex(self, cmd):
2470 def ex(self, cmd):
2471 """Execute a normal python statement in user namespace."""
2471 """Execute a normal python statement in user namespace."""
2472 with self.builtin_trap:
2472 with self.builtin_trap:
2473 exec(cmd, self.user_global_ns, self.user_ns)
2473 exec(cmd, self.user_global_ns, self.user_ns)
2474
2474
2475 def ev(self, expr):
2475 def ev(self, expr):
2476 """Evaluate python expression expr in user namespace.
2476 """Evaluate python expression expr in user namespace.
2477
2477
2478 Returns the result of evaluation
2478 Returns the result of evaluation
2479 """
2479 """
2480 with self.builtin_trap:
2480 with self.builtin_trap:
2481 return eval(expr, self.user_global_ns, self.user_ns)
2481 return eval(expr, self.user_global_ns, self.user_ns)
2482
2482
2483 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2483 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2484 """A safe version of the builtin execfile().
2484 """A safe version of the builtin execfile().
2485
2485
2486 This version will never throw an exception, but instead print
2486 This version will never throw an exception, but instead print
2487 helpful error messages to the screen. This only works on pure
2487 helpful error messages to the screen. This only works on pure
2488 Python files with the .py extension.
2488 Python files with the .py extension.
2489
2489
2490 Parameters
2490 Parameters
2491 ----------
2491 ----------
2492 fname : string
2492 fname : string
2493 The name of the file to be executed.
2493 The name of the file to be executed.
2494 where : tuple
2494 where : tuple
2495 One or two namespaces, passed to execfile() as (globals,locals).
2495 One or two namespaces, passed to execfile() as (globals,locals).
2496 If only one is given, it is passed as both.
2496 If only one is given, it is passed as both.
2497 exit_ignore : bool (False)
2497 exit_ignore : bool (False)
2498 If True, then silence SystemExit for non-zero status (it is always
2498 If True, then silence SystemExit for non-zero status (it is always
2499 silenced for zero status, as it is so common).
2499 silenced for zero status, as it is so common).
2500 raise_exceptions : bool (False)
2500 raise_exceptions : bool (False)
2501 If True raise exceptions everywhere. Meant for testing.
2501 If True raise exceptions everywhere. Meant for testing.
2502 shell_futures : bool (False)
2502 shell_futures : bool (False)
2503 If True, the code will share future statements with the interactive
2503 If True, the code will share future statements with the interactive
2504 shell. It will both be affected by previous __future__ imports, and
2504 shell. It will both be affected by previous __future__ imports, and
2505 any __future__ imports in the code will affect the shell. If False,
2505 any __future__ imports in the code will affect the shell. If False,
2506 __future__ imports are not shared in either direction.
2506 __future__ imports are not shared in either direction.
2507
2507
2508 """
2508 """
2509 fname = os.path.abspath(os.path.expanduser(fname))
2509 fname = os.path.abspath(os.path.expanduser(fname))
2510
2510
2511 # Make sure we can open the file
2511 # Make sure we can open the file
2512 try:
2512 try:
2513 with open(fname):
2513 with open(fname):
2514 pass
2514 pass
2515 except:
2515 except:
2516 warn('Could not open file <%s> for safe execution.' % fname)
2516 warn('Could not open file <%s> for safe execution.' % fname)
2517 return
2517 return
2518
2518
2519 # Find things also in current directory. This is needed to mimic the
2519 # Find things also in current directory. This is needed to mimic the
2520 # behavior of running a script from the system command line, where
2520 # behavior of running a script from the system command line, where
2521 # Python inserts the script's directory into sys.path
2521 # Python inserts the script's directory into sys.path
2522 dname = os.path.dirname(fname)
2522 dname = os.path.dirname(fname)
2523
2523
2524 with prepended_to_syspath(dname), self.builtin_trap:
2524 with prepended_to_syspath(dname), self.builtin_trap:
2525 try:
2525 try:
2526 glob, loc = (where + (None, ))[:2]
2526 glob, loc = (where + (None, ))[:2]
2527 py3compat.execfile(
2527 py3compat.execfile(
2528 fname, glob, loc,
2528 fname, glob, loc,
2529 self.compile if shell_futures else None)
2529 self.compile if shell_futures else None)
2530 except SystemExit as status:
2530 except SystemExit as status:
2531 # If the call was made with 0 or None exit status (sys.exit(0)
2531 # If the call was made with 0 or None exit status (sys.exit(0)
2532 # or sys.exit() ), don't bother showing a traceback, as both of
2532 # or sys.exit() ), don't bother showing a traceback, as both of
2533 # these are considered normal by the OS:
2533 # these are considered normal by the OS:
2534 # > python -c'import sys;sys.exit(0)'; echo $?
2534 # > python -c'import sys;sys.exit(0)'; echo $?
2535 # 0
2535 # 0
2536 # > python -c'import sys;sys.exit()'; echo $?
2536 # > python -c'import sys;sys.exit()'; echo $?
2537 # 0
2537 # 0
2538 # For other exit status, we show the exception unless
2538 # For other exit status, we show the exception unless
2539 # explicitly silenced, but only in short form.
2539 # explicitly silenced, but only in short form.
2540 if status.code:
2540 if status.code:
2541 if raise_exceptions:
2541 if raise_exceptions:
2542 raise
2542 raise
2543 if not exit_ignore:
2543 if not exit_ignore:
2544 self.showtraceback(exception_only=True)
2544 self.showtraceback(exception_only=True)
2545 except:
2545 except:
2546 if raise_exceptions:
2546 if raise_exceptions:
2547 raise
2547 raise
2548 # tb offset is 2 because we wrap execfile
2548 # tb offset is 2 because we wrap execfile
2549 self.showtraceback(tb_offset=2)
2549 self.showtraceback(tb_offset=2)
2550
2550
2551 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2551 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2552 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2552 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2553
2553
2554 Parameters
2554 Parameters
2555 ----------
2555 ----------
2556 fname : str
2556 fname : str
2557 The name of the file to execute. The filename must have a
2557 The name of the file to execute. The filename must have a
2558 .ipy or .ipynb extension.
2558 .ipy or .ipynb extension.
2559 shell_futures : bool (False)
2559 shell_futures : bool (False)
2560 If True, the code will share future statements with the interactive
2560 If True, the code will share future statements with the interactive
2561 shell. It will both be affected by previous __future__ imports, and
2561 shell. It will both be affected by previous __future__ imports, and
2562 any __future__ imports in the code will affect the shell. If False,
2562 any __future__ imports in the code will affect the shell. If False,
2563 __future__ imports are not shared in either direction.
2563 __future__ imports are not shared in either direction.
2564 raise_exceptions : bool (False)
2564 raise_exceptions : bool (False)
2565 If True raise exceptions everywhere. Meant for testing.
2565 If True raise exceptions everywhere. Meant for testing.
2566 """
2566 """
2567 fname = os.path.abspath(os.path.expanduser(fname))
2567 fname = os.path.abspath(os.path.expanduser(fname))
2568
2568
2569 # Make sure we can open the file
2569 # Make sure we can open the file
2570 try:
2570 try:
2571 with open(fname):
2571 with open(fname):
2572 pass
2572 pass
2573 except:
2573 except:
2574 warn('Could not open file <%s> for safe execution.' % fname)
2574 warn('Could not open file <%s> for safe execution.' % fname)
2575 return
2575 return
2576
2576
2577 # Find things also in current directory. This is needed to mimic the
2577 # Find things also in current directory. This is needed to mimic the
2578 # behavior of running a script from the system command line, where
2578 # behavior of running a script from the system command line, where
2579 # Python inserts the script's directory into sys.path
2579 # Python inserts the script's directory into sys.path
2580 dname = os.path.dirname(fname)
2580 dname = os.path.dirname(fname)
2581
2581
2582 def get_cells():
2582 def get_cells():
2583 """generator for sequence of code blocks to run"""
2583 """generator for sequence of code blocks to run"""
2584 if fname.endswith('.ipynb'):
2584 if fname.endswith('.ipynb'):
2585 from nbformat import read
2585 from nbformat import read
2586 nb = read(fname, as_version=4)
2586 nb = read(fname, as_version=4)
2587 if not nb.cells:
2587 if not nb.cells:
2588 return
2588 return
2589 for cell in nb.cells:
2589 for cell in nb.cells:
2590 if cell.cell_type == 'code':
2590 if cell.cell_type == 'code':
2591 yield cell.source
2591 yield cell.source
2592 else:
2592 else:
2593 with open(fname) as f:
2593 with open(fname) as f:
2594 yield f.read()
2594 yield f.read()
2595
2595
2596 with prepended_to_syspath(dname):
2596 with prepended_to_syspath(dname):
2597 try:
2597 try:
2598 for cell in get_cells():
2598 for cell in get_cells():
2599 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2599 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2600 if raise_exceptions:
2600 if raise_exceptions:
2601 result.raise_error()
2601 result.raise_error()
2602 elif not result.success:
2602 elif not result.success:
2603 break
2603 break
2604 except:
2604 except:
2605 if raise_exceptions:
2605 if raise_exceptions:
2606 raise
2606 raise
2607 self.showtraceback()
2607 self.showtraceback()
2608 warn('Unknown failure executing file: <%s>' % fname)
2608 warn('Unknown failure executing file: <%s>' % fname)
2609
2609
2610 def safe_run_module(self, mod_name, where):
2610 def safe_run_module(self, mod_name, where):
2611 """A safe version of runpy.run_module().
2611 """A safe version of runpy.run_module().
2612
2612
2613 This version will never throw an exception, but instead print
2613 This version will never throw an exception, but instead print
2614 helpful error messages to the screen.
2614 helpful error messages to the screen.
2615
2615
2616 `SystemExit` exceptions with status code 0 or None are ignored.
2616 `SystemExit` exceptions with status code 0 or None are ignored.
2617
2617
2618 Parameters
2618 Parameters
2619 ----------
2619 ----------
2620 mod_name : string
2620 mod_name : string
2621 The name of the module to be executed.
2621 The name of the module to be executed.
2622 where : dict
2622 where : dict
2623 The globals namespace.
2623 The globals namespace.
2624 """
2624 """
2625 try:
2625 try:
2626 try:
2626 try:
2627 where.update(
2627 where.update(
2628 runpy.run_module(str(mod_name), run_name="__main__",
2628 runpy.run_module(str(mod_name), run_name="__main__",
2629 alter_sys=True)
2629 alter_sys=True)
2630 )
2630 )
2631 except SystemExit as status:
2631 except SystemExit as status:
2632 if status.code:
2632 if status.code:
2633 raise
2633 raise
2634 except:
2634 except:
2635 self.showtraceback()
2635 self.showtraceback()
2636 warn('Unknown failure executing module: <%s>' % mod_name)
2636 warn('Unknown failure executing module: <%s>' % mod_name)
2637
2637
2638 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2638 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2639 """Run a complete IPython cell.
2639 """Run a complete IPython cell.
2640
2640
2641 Parameters
2641 Parameters
2642 ----------
2642 ----------
2643 raw_cell : str
2643 raw_cell : str
2644 The code (including IPython code such as %magic functions) to run.
2644 The code (including IPython code such as %magic functions) to run.
2645 store_history : bool
2645 store_history : bool
2646 If True, the raw and translated cell will be stored in IPython's
2646 If True, the raw and translated cell will be stored in IPython's
2647 history. For user code calling back into IPython's machinery, this
2647 history. For user code calling back into IPython's machinery, this
2648 should be set to False.
2648 should be set to False.
2649 silent : bool
2649 silent : bool
2650 If True, avoid side-effects, such as implicit displayhooks and
2650 If True, avoid side-effects, such as implicit displayhooks and
2651 and logging. silent=True forces store_history=False.
2651 and logging. silent=True forces store_history=False.
2652 shell_futures : bool
2652 shell_futures : bool
2653 If True, the code will share future statements with the interactive
2653 If True, the code will share future statements with the interactive
2654 shell. It will both be affected by previous __future__ imports, and
2654 shell. It will both be affected by previous __future__ imports, and
2655 any __future__ imports in the code will affect the shell. If False,
2655 any __future__ imports in the code will affect the shell. If False,
2656 __future__ imports are not shared in either direction.
2656 __future__ imports are not shared in either direction.
2657
2657
2658 Returns
2658 Returns
2659 -------
2659 -------
2660 result : :class:`ExecutionResult`
2660 result : :class:`ExecutionResult`
2661 """
2661 """
2662 result = None
2662 result = None
2663 try:
2663 try:
2664 result = self._run_cell(
2664 result = self._run_cell(
2665 raw_cell, store_history, silent, shell_futures)
2665 raw_cell, store_history, silent, shell_futures)
2666 finally:
2666 finally:
2667 self.events.trigger('post_execute')
2667 self.events.trigger('post_execute')
2668 if not silent:
2668 if not silent:
2669 self.events.trigger('post_run_cell', result)
2669 self.events.trigger('post_run_cell', result)
2670 return result
2670 return result
2671
2671
2672 def _run_cell(self, raw_cell, store_history, silent, shell_futures):
2672 def _run_cell(self, raw_cell, store_history, silent, shell_futures):
2673 """Internal method to run a complete IPython cell.
2673 """Internal method to run a complete IPython cell.
2674
2674
2675 Parameters
2675 Parameters
2676 ----------
2676 ----------
2677 raw_cell : str
2677 raw_cell : str
2678 store_history : bool
2678 store_history : bool
2679 silent : bool
2679 silent : bool
2680 shell_futures : bool
2680 shell_futures : bool
2681
2681
2682 Returns
2682 Returns
2683 -------
2683 -------
2684 result : :class:`ExecutionResult`
2684 result : :class:`ExecutionResult`
2685 """
2685 """
2686 info = ExecutionInfo(
2686 info = ExecutionInfo(
2687 raw_cell, store_history, silent, shell_futures)
2687 raw_cell, store_history, silent, shell_futures)
2688 result = ExecutionResult(info)
2688 result = ExecutionResult(info)
2689
2689
2690 if (not raw_cell) or raw_cell.isspace():
2690 if (not raw_cell) or raw_cell.isspace():
2691 self.last_execution_succeeded = True
2691 self.last_execution_succeeded = True
2692 self.last_execution_result = result
2692 self.last_execution_result = result
2693 return result
2693 return result
2694
2694
2695 if silent:
2695 if silent:
2696 store_history = False
2696 store_history = False
2697
2697
2698 if store_history:
2698 if store_history:
2699 result.execution_count = self.execution_count
2699 result.execution_count = self.execution_count
2700
2700
2701 def error_before_exec(value):
2701 def error_before_exec(value):
2702 if store_history:
2702 if store_history:
2703 self.execution_count += 1
2703 self.execution_count += 1
2704 result.error_before_exec = value
2704 result.error_before_exec = value
2705 self.last_execution_succeeded = False
2705 self.last_execution_succeeded = False
2706 self.last_execution_result = result
2706 self.last_execution_result = result
2707 return result
2707 return result
2708
2708
2709 self.events.trigger('pre_execute')
2709 self.events.trigger('pre_execute')
2710 if not silent:
2710 if not silent:
2711 self.events.trigger('pre_run_cell', info)
2711 self.events.trigger('pre_run_cell', info)
2712
2712
2713 # If any of our input transformation (input_transformer_manager or
2713 # If any of our input transformation (input_transformer_manager or
2714 # prefilter_manager) raises an exception, we store it in this variable
2714 # prefilter_manager) raises an exception, we store it in this variable
2715 # so that we can display the error after logging the input and storing
2715 # so that we can display the error after logging the input and storing
2716 # it in the history.
2716 # it in the history.
2717 preprocessing_exc_tuple = None
2717 preprocessing_exc_tuple = None
2718 try:
2718 try:
2719 # Static input transformations
2719 # Static input transformations
2720 cell = self.input_transformer_manager.transform_cell(raw_cell)
2720 cell = self.input_transformer_manager.transform_cell(raw_cell)
2721 except SyntaxError:
2721 except SyntaxError:
2722 preprocessing_exc_tuple = sys.exc_info()
2722 preprocessing_exc_tuple = sys.exc_info()
2723 cell = raw_cell # cell has to exist so it can be stored/logged
2723 cell = raw_cell # cell has to exist so it can be stored/logged
2724 else:
2724 else:
2725 if len(cell.splitlines()) == 1:
2725 if len(cell.splitlines()) == 1:
2726 # Dynamic transformations - only applied for single line commands
2726 # Dynamic transformations - only applied for single line commands
2727 with self.builtin_trap:
2727 with self.builtin_trap:
2728 try:
2728 try:
2729 # use prefilter_lines to handle trailing newlines
2729 # use prefilter_lines to handle trailing newlines
2730 # restore trailing newline for ast.parse
2730 # restore trailing newline for ast.parse
2731 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2731 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2732 except Exception:
2732 except Exception:
2733 # don't allow prefilter errors to crash IPython
2733 # don't allow prefilter errors to crash IPython
2734 preprocessing_exc_tuple = sys.exc_info()
2734 preprocessing_exc_tuple = sys.exc_info()
2735
2735
2736 # Store raw and processed history
2736 # Store raw and processed history
2737 if store_history:
2737 if store_history:
2738 self.history_manager.store_inputs(self.execution_count,
2738 self.history_manager.store_inputs(self.execution_count,
2739 cell, raw_cell)
2739 cell, raw_cell)
2740 if not silent:
2740 if not silent:
2741 self.logger.log(cell, raw_cell)
2741 self.logger.log(cell, raw_cell)
2742
2742
2743 # Display the exception if input processing failed.
2743 # Display the exception if input processing failed.
2744 if preprocessing_exc_tuple is not None:
2744 if preprocessing_exc_tuple is not None:
2745 self.showtraceback(preprocessing_exc_tuple)
2745 self.showtraceback(preprocessing_exc_tuple)
2746 if store_history:
2746 if store_history:
2747 self.execution_count += 1
2747 self.execution_count += 1
2748 return error_before_exec(preprocessing_exc_tuple[2])
2748 return error_before_exec(preprocessing_exc_tuple[2])
2749
2749
2750 # Our own compiler remembers the __future__ environment. If we want to
2750 # Our own compiler remembers the __future__ environment. If we want to
2751 # run code with a separate __future__ environment, use the default
2751 # run code with a separate __future__ environment, use the default
2752 # compiler
2752 # compiler
2753 compiler = self.compile if shell_futures else CachingCompiler()
2753 compiler = self.compile if shell_futures else CachingCompiler()
2754
2754
2755 with self.builtin_trap:
2755 with self.builtin_trap:
2756 cell_name = self.compile.cache(cell, self.execution_count)
2756 cell_name = self.compile.cache(cell, self.execution_count)
2757
2757
2758 with self.display_trap:
2758 with self.display_trap:
2759 # Compile to bytecode
2759 # Compile to bytecode
2760 try:
2760 try:
2761 code_ast = compiler.ast_parse(cell, filename=cell_name)
2761 code_ast = compiler.ast_parse(cell, filename=cell_name)
2762 except self.custom_exceptions as e:
2762 except self.custom_exceptions as e:
2763 etype, value, tb = sys.exc_info()
2763 etype, value, tb = sys.exc_info()
2764 self.CustomTB(etype, value, tb)
2764 self.CustomTB(etype, value, tb)
2765 return error_before_exec(e)
2765 return error_before_exec(e)
2766 except IndentationError as e:
2766 except IndentationError as e:
2767 self.showindentationerror()
2767 self.showindentationerror()
2768 return error_before_exec(e)
2768 return error_before_exec(e)
2769 except (OverflowError, SyntaxError, ValueError, TypeError,
2769 except (OverflowError, SyntaxError, ValueError, TypeError,
2770 MemoryError) as e:
2770 MemoryError) as e:
2771 self.showsyntaxerror()
2771 self.showsyntaxerror()
2772 return error_before_exec(e)
2772 return error_before_exec(e)
2773
2773
2774 # Apply AST transformations
2774 # Apply AST transformations
2775 try:
2775 try:
2776 code_ast = self.transform_ast(code_ast)
2776 code_ast = self.transform_ast(code_ast)
2777 except InputRejected as e:
2777 except InputRejected as e:
2778 self.showtraceback()
2778 self.showtraceback()
2779 return error_before_exec(e)
2779 return error_before_exec(e)
2780
2780
2781 # Give the displayhook a reference to our ExecutionResult so it
2781 # Give the displayhook a reference to our ExecutionResult so it
2782 # can fill in the output value.
2782 # can fill in the output value.
2783 self.displayhook.exec_result = result
2783 self.displayhook.exec_result = result
2784
2784
2785 # Execute the user code
2785 # Execute the user code
2786 interactivity = 'none' if silent else self.ast_node_interactivity
2786 interactivity = 'none' if silent else self.ast_node_interactivity
2787 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2787 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2788 interactivity=interactivity, compiler=compiler, result=result)
2788 interactivity=interactivity, compiler=compiler, result=result)
2789
2789
2790 self.last_execution_succeeded = not has_raised
2790 self.last_execution_succeeded = not has_raised
2791 self.last_execution_result = result
2791 self.last_execution_result = result
2792
2792
2793 # Reset this so later displayed values do not modify the
2793 # Reset this so later displayed values do not modify the
2794 # ExecutionResult
2794 # ExecutionResult
2795 self.displayhook.exec_result = None
2795 self.displayhook.exec_result = None
2796
2796
2797 if store_history:
2797 if store_history:
2798 # Write output to the database. Does nothing unless
2798 # Write output to the database. Does nothing unless
2799 # history output logging is enabled.
2799 # history output logging is enabled.
2800 self.history_manager.store_output(self.execution_count)
2800 self.history_manager.store_output(self.execution_count)
2801 # Each cell is a *single* input, regardless of how many lines it has
2801 # Each cell is a *single* input, regardless of how many lines it has
2802 self.execution_count += 1
2802 self.execution_count += 1
2803
2803
2804 return result
2804 return result
2805
2805
2806 def transform_ast(self, node):
2806 def transform_ast(self, node):
2807 """Apply the AST transformations from self.ast_transformers
2807 """Apply the AST transformations from self.ast_transformers
2808
2808
2809 Parameters
2809 Parameters
2810 ----------
2810 ----------
2811 node : ast.Node
2811 node : ast.Node
2812 The root node to be transformed. Typically called with the ast.Module
2812 The root node to be transformed. Typically called with the ast.Module
2813 produced by parsing user input.
2813 produced by parsing user input.
2814
2814
2815 Returns
2815 Returns
2816 -------
2816 -------
2817 An ast.Node corresponding to the node it was called with. Note that it
2817 An ast.Node corresponding to the node it was called with. Note that it
2818 may also modify the passed object, so don't rely on references to the
2818 may also modify the passed object, so don't rely on references to the
2819 original AST.
2819 original AST.
2820 """
2820 """
2821 for transformer in self.ast_transformers:
2821 for transformer in self.ast_transformers:
2822 try:
2822 try:
2823 node = transformer.visit(node)
2823 node = transformer.visit(node)
2824 except InputRejected:
2824 except InputRejected:
2825 # User-supplied AST transformers can reject an input by raising
2825 # User-supplied AST transformers can reject an input by raising
2826 # an InputRejected. Short-circuit in this case so that we
2826 # an InputRejected. Short-circuit in this case so that we
2827 # don't unregister the transform.
2827 # don't unregister the transform.
2828 raise
2828 raise
2829 except Exception:
2829 except Exception:
2830 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2830 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2831 self.ast_transformers.remove(transformer)
2831 self.ast_transformers.remove(transformer)
2832
2832
2833 if self.ast_transformers:
2833 if self.ast_transformers:
2834 ast.fix_missing_locations(node)
2834 ast.fix_missing_locations(node)
2835 return node
2835 return node
2836
2836
2837
2837
2838 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2838 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2839 compiler=compile, result=None):
2839 compiler=compile, result=None):
2840 """Run a sequence of AST nodes. The execution mode depends on the
2840 """Run a sequence of AST nodes. The execution mode depends on the
2841 interactivity parameter.
2841 interactivity parameter.
2842
2842
2843 Parameters
2843 Parameters
2844 ----------
2844 ----------
2845 nodelist : list
2845 nodelist : list
2846 A sequence of AST nodes to run.
2846 A sequence of AST nodes to run.
2847 cell_name : str
2847 cell_name : str
2848 Will be passed to the compiler as the filename of the cell. Typically
2848 Will be passed to the compiler as the filename of the cell. Typically
2849 the value returned by ip.compile.cache(cell).
2849 the value returned by ip.compile.cache(cell).
2850 interactivity : str
2850 interactivity : str
2851 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2851 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2852 specifying which nodes should be run interactively (displaying output
2852 specifying which nodes should be run interactively (displaying output
2853 from expressions). 'last_expr' will run the last node interactively
2853 from expressions). 'last_expr' will run the last node interactively
2854 only if it is an expression (i.e. expressions in loops or other blocks
2854 only if it is an expression (i.e. expressions in loops or other blocks
2855 are not displayed) 'last_expr_or_assign' will run the last expression
2855 are not displayed) 'last_expr_or_assign' will run the last expression
2856 or the last assignment. Other values for this parameter will raise a
2856 or the last assignment. Other values for this parameter will raise a
2857 ValueError.
2857 ValueError.
2858 compiler : callable
2858 compiler : callable
2859 A function with the same interface as the built-in compile(), to turn
2859 A function with the same interface as the built-in compile(), to turn
2860 the AST nodes into code objects. Default is the built-in compile().
2860 the AST nodes into code objects. Default is the built-in compile().
2861 result : ExecutionResult, optional
2861 result : ExecutionResult, optional
2862 An object to store exceptions that occur during execution.
2862 An object to store exceptions that occur during execution.
2863
2863
2864 Returns
2864 Returns
2865 -------
2865 -------
2866 True if an exception occurred while running code, False if it finished
2866 True if an exception occurred while running code, False if it finished
2867 running.
2867 running.
2868 """
2868 """
2869 if not nodelist:
2869 if not nodelist:
2870 return
2870 return
2871
2871
2872 if interactivity == 'last_expr_or_assign':
2872 if interactivity == 'last_expr_or_assign':
2873 if isinstance(nodelist[-1], _assign_nodes):
2873 if isinstance(nodelist[-1], _assign_nodes):
2874 asg = nodelist[-1]
2874 asg = nodelist[-1]
2875 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2875 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2876 target = asg.targets[0]
2876 target = asg.targets[0]
2877 elif isinstance(asg, _single_targets_nodes):
2877 elif isinstance(asg, _single_targets_nodes):
2878 target = asg.target
2878 target = asg.target
2879 else:
2879 else:
2880 target = None
2880 target = None
2881 if isinstance(target, ast.Name):
2881 if isinstance(target, ast.Name):
2882 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2882 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2883 ast.fix_missing_locations(nnode)
2883 ast.fix_missing_locations(nnode)
2884 nodelist.append(nnode)
2884 nodelist.append(nnode)
2885 interactivity = 'last_expr'
2885 interactivity = 'last_expr'
2886
2886
2887 if interactivity == 'last_expr':
2887 if interactivity == 'last_expr':
2888 if isinstance(nodelist[-1], ast.Expr):
2888 if isinstance(nodelist[-1], ast.Expr):
2889 interactivity = "last"
2889 interactivity = "last"
2890 else:
2890 else:
2891 interactivity = "none"
2891 interactivity = "none"
2892
2892
2893 if interactivity == 'none':
2893 if interactivity == 'none':
2894 to_run_exec, to_run_interactive = nodelist, []
2894 to_run_exec, to_run_interactive = nodelist, []
2895 elif interactivity == 'last':
2895 elif interactivity == 'last':
2896 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2896 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2897 elif interactivity == 'all':
2897 elif interactivity == 'all':
2898 to_run_exec, to_run_interactive = [], nodelist
2898 to_run_exec, to_run_interactive = [], nodelist
2899 else:
2899 else:
2900 raise ValueError("Interactivity was %r" % interactivity)
2900 raise ValueError("Interactivity was %r" % interactivity)
2901
2901
2902 try:
2902 try:
2903 for i, node in enumerate(to_run_exec):
2903 for i, node in enumerate(to_run_exec):
2904 mod = ast.Module([node])
2904 mod = ast.Module([node])
2905 code = compiler(mod, cell_name, "exec")
2905 code = compiler(mod, cell_name, "exec")
2906 if self.run_code(code, result):
2906 if self.run_code(code, result):
2907 return True
2907 return True
2908
2908
2909 for i, node in enumerate(to_run_interactive):
2909 for i, node in enumerate(to_run_interactive):
2910 mod = ast.Interactive([node])
2910 mod = ast.Interactive([node])
2911 code = compiler(mod, cell_name, "single")
2911 code = compiler(mod, cell_name, "single")
2912 if self.run_code(code, result):
2912 if self.run_code(code, result):
2913 return True
2913 return True
2914
2914
2915 # Flush softspace
2915 # Flush softspace
2916 if softspace(sys.stdout, 0):
2916 if softspace(sys.stdout, 0):
2917 print()
2917 print()
2918
2918
2919 except:
2919 except:
2920 # It's possible to have exceptions raised here, typically by
2920 # It's possible to have exceptions raised here, typically by
2921 # compilation of odd code (such as a naked 'return' outside a
2921 # compilation of odd code (such as a naked 'return' outside a
2922 # function) that did parse but isn't valid. Typically the exception
2922 # function) that did parse but isn't valid. Typically the exception
2923 # is a SyntaxError, but it's safest just to catch anything and show
2923 # is a SyntaxError, but it's safest just to catch anything and show
2924 # the user a traceback.
2924 # the user a traceback.
2925
2925
2926 # We do only one try/except outside the loop to minimize the impact
2926 # We do only one try/except outside the loop to minimize the impact
2927 # on runtime, and also because if any node in the node list is
2927 # on runtime, and also because if any node in the node list is
2928 # broken, we should stop execution completely.
2928 # broken, we should stop execution completely.
2929 if result:
2929 if result:
2930 result.error_before_exec = sys.exc_info()[1]
2930 result.error_before_exec = sys.exc_info()[1]
2931 self.showtraceback()
2931 self.showtraceback()
2932 return True
2932 return True
2933
2933
2934 return False
2934 return False
2935
2935
2936 def run_code(self, code_obj, result=None):
2936 def run_code(self, code_obj, result=None):
2937 """Execute a code object.
2937 """Execute a code object.
2938
2938
2939 When an exception occurs, self.showtraceback() is called to display a
2939 When an exception occurs, self.showtraceback() is called to display a
2940 traceback.
2940 traceback.
2941
2941
2942 Parameters
2942 Parameters
2943 ----------
2943 ----------
2944 code_obj : code object
2944 code_obj : code object
2945 A compiled code object, to be executed
2945 A compiled code object, to be executed
2946 result : ExecutionResult, optional
2946 result : ExecutionResult, optional
2947 An object to store exceptions that occur during execution.
2947 An object to store exceptions that occur during execution.
2948
2948
2949 Returns
2949 Returns
2950 -------
2950 -------
2951 False : successful execution.
2951 False : successful execution.
2952 True : an error occurred.
2952 True : an error occurred.
2953 """
2953 """
2954 # Set our own excepthook in case the user code tries to call it
2954 # Set our own excepthook in case the user code tries to call it
2955 # directly, so that the IPython crash handler doesn't get triggered
2955 # directly, so that the IPython crash handler doesn't get triggered
2956 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2956 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2957
2957
2958 # we save the original sys.excepthook in the instance, in case config
2958 # we save the original sys.excepthook in the instance, in case config
2959 # code (such as magics) needs access to it.
2959 # code (such as magics) needs access to it.
2960 self.sys_excepthook = old_excepthook
2960 self.sys_excepthook = old_excepthook
2961 outflag = True # happens in more places, so it's easier as default
2961 outflag = True # happens in more places, so it's easier as default
2962 try:
2962 try:
2963 try:
2963 try:
2964 self.hooks.pre_run_code_hook()
2964 self.hooks.pre_run_code_hook()
2965 #rprint('Running code', repr(code_obj)) # dbg
2965 #rprint('Running code', repr(code_obj)) # dbg
2966 exec(code_obj, self.user_global_ns, self.user_ns)
2966 exec(code_obj, self.user_global_ns, self.user_ns)
2967 finally:
2967 finally:
2968 # Reset our crash handler in place
2968 # Reset our crash handler in place
2969 sys.excepthook = old_excepthook
2969 sys.excepthook = old_excepthook
2970 except SystemExit as e:
2970 except SystemExit as e:
2971 if result is not None:
2971 if result is not None:
2972 result.error_in_exec = e
2972 result.error_in_exec = e
2973 self.showtraceback(exception_only=True)
2973 self.showtraceback(exception_only=True)
2974 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2974 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2975 except self.custom_exceptions:
2975 except self.custom_exceptions:
2976 etype, value, tb = sys.exc_info()
2976 etype, value, tb = sys.exc_info()
2977 if result is not None:
2977 if result is not None:
2978 result.error_in_exec = value
2978 result.error_in_exec = value
2979 self.CustomTB(etype, value, tb)
2979 self.CustomTB(etype, value, tb)
2980 except:
2980 except:
2981 if result is not None:
2981 if result is not None:
2982 result.error_in_exec = sys.exc_info()[1]
2982 result.error_in_exec = sys.exc_info()[1]
2983 self.showtraceback(running_compiled_code=True)
2983 self.showtraceback(running_compiled_code=True)
2984 else:
2984 else:
2985 outflag = False
2985 outflag = False
2986 return outflag
2986 return outflag
2987
2987
2988 # For backwards compatibility
2988 # For backwards compatibility
2989 runcode = run_code
2989 runcode = run_code
2990
2990
2991 def check_complete(self, code):
2992 """Return whether a block of code is ready to execute, or should be continued
2993
2994 Parameters
2995 ----------
2996 source : string
2997 Python input code, which can be multiline.
2998
2999 Returns
3000 -------
3001 status : str
3002 One of 'complete', 'incomplete', or 'invalid' if source is not a
3003 prefix of valid code.
3004 indent : str
3005 When status is 'incomplete', this is some whitespace to insert on
3006 the next line of the prompt.
3007 """
3008 status, nspaces = self.input_transformer_manager.check_complete(code)
3009 return status, ' ' * (nspaces or 0)
3010
2991 #-------------------------------------------------------------------------
3011 #-------------------------------------------------------------------------
2992 # Things related to GUI support and pylab
3012 # Things related to GUI support and pylab
2993 #-------------------------------------------------------------------------
3013 #-------------------------------------------------------------------------
2994
3014
2995 active_eventloop = None
3015 active_eventloop = None
2996
3016
2997 def enable_gui(self, gui=None):
3017 def enable_gui(self, gui=None):
2998 raise NotImplementedError('Implement enable_gui in a subclass')
3018 raise NotImplementedError('Implement enable_gui in a subclass')
2999
3019
3000 def enable_matplotlib(self, gui=None):
3020 def enable_matplotlib(self, gui=None):
3001 """Enable interactive matplotlib and inline figure support.
3021 """Enable interactive matplotlib and inline figure support.
3002
3022
3003 This takes the following steps:
3023 This takes the following steps:
3004
3024
3005 1. select the appropriate eventloop and matplotlib backend
3025 1. select the appropriate eventloop and matplotlib backend
3006 2. set up matplotlib for interactive use with that backend
3026 2. set up matplotlib for interactive use with that backend
3007 3. configure formatters for inline figure display
3027 3. configure formatters for inline figure display
3008 4. enable the selected gui eventloop
3028 4. enable the selected gui eventloop
3009
3029
3010 Parameters
3030 Parameters
3011 ----------
3031 ----------
3012 gui : optional, string
3032 gui : optional, string
3013 If given, dictates the choice of matplotlib GUI backend to use
3033 If given, dictates the choice of matplotlib GUI backend to use
3014 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3034 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3015 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3035 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3016 matplotlib (as dictated by the matplotlib build-time options plus the
3036 matplotlib (as dictated by the matplotlib build-time options plus the
3017 user's matplotlibrc configuration file). Note that not all backends
3037 user's matplotlibrc configuration file). Note that not all backends
3018 make sense in all contexts, for example a terminal ipython can't
3038 make sense in all contexts, for example a terminal ipython can't
3019 display figures inline.
3039 display figures inline.
3020 """
3040 """
3021 from IPython.core import pylabtools as pt
3041 from IPython.core import pylabtools as pt
3022 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3042 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3023
3043
3024 if gui != 'inline':
3044 if gui != 'inline':
3025 # If we have our first gui selection, store it
3045 # If we have our first gui selection, store it
3026 if self.pylab_gui_select is None:
3046 if self.pylab_gui_select is None:
3027 self.pylab_gui_select = gui
3047 self.pylab_gui_select = gui
3028 # Otherwise if they are different
3048 # Otherwise if they are different
3029 elif gui != self.pylab_gui_select:
3049 elif gui != self.pylab_gui_select:
3030 print('Warning: Cannot change to a different GUI toolkit: %s.'
3050 print('Warning: Cannot change to a different GUI toolkit: %s.'
3031 ' Using %s instead.' % (gui, self.pylab_gui_select))
3051 ' Using %s instead.' % (gui, self.pylab_gui_select))
3032 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3052 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
3033
3053
3034 pt.activate_matplotlib(backend)
3054 pt.activate_matplotlib(backend)
3035 pt.configure_inline_support(self, backend)
3055 pt.configure_inline_support(self, backend)
3036
3056
3037 # Now we must activate the gui pylab wants to use, and fix %run to take
3057 # Now we must activate the gui pylab wants to use, and fix %run to take
3038 # plot updates into account
3058 # plot updates into account
3039 self.enable_gui(gui)
3059 self.enable_gui(gui)
3040 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3060 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3041 pt.mpl_runner(self.safe_execfile)
3061 pt.mpl_runner(self.safe_execfile)
3042
3062
3043 return gui, backend
3063 return gui, backend
3044
3064
3045 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3065 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3046 """Activate pylab support at runtime.
3066 """Activate pylab support at runtime.
3047
3067
3048 This turns on support for matplotlib, preloads into the interactive
3068 This turns on support for matplotlib, preloads into the interactive
3049 namespace all of numpy and pylab, and configures IPython to correctly
3069 namespace all of numpy and pylab, and configures IPython to correctly
3050 interact with the GUI event loop. The GUI backend to be used can be
3070 interact with the GUI event loop. The GUI backend to be used can be
3051 optionally selected with the optional ``gui`` argument.
3071 optionally selected with the optional ``gui`` argument.
3052
3072
3053 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3073 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3054
3074
3055 Parameters
3075 Parameters
3056 ----------
3076 ----------
3057 gui : optional, string
3077 gui : optional, string
3058 If given, dictates the choice of matplotlib GUI backend to use
3078 If given, dictates the choice of matplotlib GUI backend to use
3059 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3079 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3060 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3080 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3061 matplotlib (as dictated by the matplotlib build-time options plus the
3081 matplotlib (as dictated by the matplotlib build-time options plus the
3062 user's matplotlibrc configuration file). Note that not all backends
3082 user's matplotlibrc configuration file). Note that not all backends
3063 make sense in all contexts, for example a terminal ipython can't
3083 make sense in all contexts, for example a terminal ipython can't
3064 display figures inline.
3084 display figures inline.
3065 import_all : optional, bool, default: True
3085 import_all : optional, bool, default: True
3066 Whether to do `from numpy import *` and `from pylab import *`
3086 Whether to do `from numpy import *` and `from pylab import *`
3067 in addition to module imports.
3087 in addition to module imports.
3068 welcome_message : deprecated
3088 welcome_message : deprecated
3069 This argument is ignored, no welcome message will be displayed.
3089 This argument is ignored, no welcome message will be displayed.
3070 """
3090 """
3071 from IPython.core.pylabtools import import_pylab
3091 from IPython.core.pylabtools import import_pylab
3072
3092
3073 gui, backend = self.enable_matplotlib(gui)
3093 gui, backend = self.enable_matplotlib(gui)
3074
3094
3075 # We want to prevent the loading of pylab to pollute the user's
3095 # We want to prevent the loading of pylab to pollute the user's
3076 # namespace as shown by the %who* magics, so we execute the activation
3096 # namespace as shown by the %who* magics, so we execute the activation
3077 # code in an empty namespace, and we update *both* user_ns and
3097 # code in an empty namespace, and we update *both* user_ns and
3078 # user_ns_hidden with this information.
3098 # user_ns_hidden with this information.
3079 ns = {}
3099 ns = {}
3080 import_pylab(ns, import_all)
3100 import_pylab(ns, import_all)
3081 # warn about clobbered names
3101 # warn about clobbered names
3082 ignored = {"__builtins__"}
3102 ignored = {"__builtins__"}
3083 both = set(ns).intersection(self.user_ns).difference(ignored)
3103 both = set(ns).intersection(self.user_ns).difference(ignored)
3084 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3104 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3085 self.user_ns.update(ns)
3105 self.user_ns.update(ns)
3086 self.user_ns_hidden.update(ns)
3106 self.user_ns_hidden.update(ns)
3087 return gui, backend, clobbered
3107 return gui, backend, clobbered
3088
3108
3089 #-------------------------------------------------------------------------
3109 #-------------------------------------------------------------------------
3090 # Utilities
3110 # Utilities
3091 #-------------------------------------------------------------------------
3111 #-------------------------------------------------------------------------
3092
3112
3093 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3113 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3094 """Expand python variables in a string.
3114 """Expand python variables in a string.
3095
3115
3096 The depth argument indicates how many frames above the caller should
3116 The depth argument indicates how many frames above the caller should
3097 be walked to look for the local namespace where to expand variables.
3117 be walked to look for the local namespace where to expand variables.
3098
3118
3099 The global namespace for expansion is always the user's interactive
3119 The global namespace for expansion is always the user's interactive
3100 namespace.
3120 namespace.
3101 """
3121 """
3102 ns = self.user_ns.copy()
3122 ns = self.user_ns.copy()
3103 try:
3123 try:
3104 frame = sys._getframe(depth+1)
3124 frame = sys._getframe(depth+1)
3105 except ValueError:
3125 except ValueError:
3106 # This is thrown if there aren't that many frames on the stack,
3126 # This is thrown if there aren't that many frames on the stack,
3107 # e.g. if a script called run_line_magic() directly.
3127 # e.g. if a script called run_line_magic() directly.
3108 pass
3128 pass
3109 else:
3129 else:
3110 ns.update(frame.f_locals)
3130 ns.update(frame.f_locals)
3111
3131
3112 try:
3132 try:
3113 # We have to use .vformat() here, because 'self' is a valid and common
3133 # We have to use .vformat() here, because 'self' is a valid and common
3114 # name, and expanding **ns for .format() would make it collide with
3134 # name, and expanding **ns for .format() would make it collide with
3115 # the 'self' argument of the method.
3135 # the 'self' argument of the method.
3116 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3136 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3117 except Exception:
3137 except Exception:
3118 # if formatter couldn't format, just let it go untransformed
3138 # if formatter couldn't format, just let it go untransformed
3119 pass
3139 pass
3120 return cmd
3140 return cmd
3121
3141
3122 def mktempfile(self, data=None, prefix='ipython_edit_'):
3142 def mktempfile(self, data=None, prefix='ipython_edit_'):
3123 """Make a new tempfile and return its filename.
3143 """Make a new tempfile and return its filename.
3124
3144
3125 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3145 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3126 but it registers the created filename internally so ipython cleans it up
3146 but it registers the created filename internally so ipython cleans it up
3127 at exit time.
3147 at exit time.
3128
3148
3129 Optional inputs:
3149 Optional inputs:
3130
3150
3131 - data(None): if data is given, it gets written out to the temp file
3151 - data(None): if data is given, it gets written out to the temp file
3132 immediately, and the file is closed again."""
3152 immediately, and the file is closed again."""
3133
3153
3134 dirname = tempfile.mkdtemp(prefix=prefix)
3154 dirname = tempfile.mkdtemp(prefix=prefix)
3135 self.tempdirs.append(dirname)
3155 self.tempdirs.append(dirname)
3136
3156
3137 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3157 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3138 os.close(handle) # On Windows, there can only be one open handle on a file
3158 os.close(handle) # On Windows, there can only be one open handle on a file
3139 self.tempfiles.append(filename)
3159 self.tempfiles.append(filename)
3140
3160
3141 if data:
3161 if data:
3142 tmp_file = open(filename,'w')
3162 tmp_file = open(filename,'w')
3143 tmp_file.write(data)
3163 tmp_file.write(data)
3144 tmp_file.close()
3164 tmp_file.close()
3145 return filename
3165 return filename
3146
3166
3147 @undoc
3167 @undoc
3148 def write(self,data):
3168 def write(self,data):
3149 """DEPRECATED: Write a string to the default output"""
3169 """DEPRECATED: Write a string to the default output"""
3150 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3170 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3151 DeprecationWarning, stacklevel=2)
3171 DeprecationWarning, stacklevel=2)
3152 sys.stdout.write(data)
3172 sys.stdout.write(data)
3153
3173
3154 @undoc
3174 @undoc
3155 def write_err(self,data):
3175 def write_err(self,data):
3156 """DEPRECATED: Write a string to the default error output"""
3176 """DEPRECATED: Write a string to the default error output"""
3157 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3177 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3158 DeprecationWarning, stacklevel=2)
3178 DeprecationWarning, stacklevel=2)
3159 sys.stderr.write(data)
3179 sys.stderr.write(data)
3160
3180
3161 def ask_yes_no(self, prompt, default=None, interrupt=None):
3181 def ask_yes_no(self, prompt, default=None, interrupt=None):
3162 if self.quiet:
3182 if self.quiet:
3163 return True
3183 return True
3164 return ask_yes_no(prompt,default,interrupt)
3184 return ask_yes_no(prompt,default,interrupt)
3165
3185
3166 def show_usage(self):
3186 def show_usage(self):
3167 """Show a usage message"""
3187 """Show a usage message"""
3168 page.page(IPython.core.usage.interactive_usage)
3188 page.page(IPython.core.usage.interactive_usage)
3169
3189
3170 def extract_input_lines(self, range_str, raw=False):
3190 def extract_input_lines(self, range_str, raw=False):
3171 """Return as a string a set of input history slices.
3191 """Return as a string a set of input history slices.
3172
3192
3173 Parameters
3193 Parameters
3174 ----------
3194 ----------
3175 range_str : string
3195 range_str : string
3176 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3196 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3177 since this function is for use by magic functions which get their
3197 since this function is for use by magic functions which get their
3178 arguments as strings. The number before the / is the session
3198 arguments as strings. The number before the / is the session
3179 number: ~n goes n back from the current session.
3199 number: ~n goes n back from the current session.
3180
3200
3181 raw : bool, optional
3201 raw : bool, optional
3182 By default, the processed input is used. If this is true, the raw
3202 By default, the processed input is used. If this is true, the raw
3183 input history is used instead.
3203 input history is used instead.
3184
3204
3185 Notes
3205 Notes
3186 -----
3206 -----
3187
3207
3188 Slices can be described with two notations:
3208 Slices can be described with two notations:
3189
3209
3190 * ``N:M`` -> standard python form, means including items N...(M-1).
3210 * ``N:M`` -> standard python form, means including items N...(M-1).
3191 * ``N-M`` -> include items N..M (closed endpoint).
3211 * ``N-M`` -> include items N..M (closed endpoint).
3192 """
3212 """
3193 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3213 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3194 return "\n".join(x for _, _, x in lines)
3214 return "\n".join(x for _, _, x in lines)
3195
3215
3196 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3216 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3197 """Get a code string from history, file, url, or a string or macro.
3217 """Get a code string from history, file, url, or a string or macro.
3198
3218
3199 This is mainly used by magic functions.
3219 This is mainly used by magic functions.
3200
3220
3201 Parameters
3221 Parameters
3202 ----------
3222 ----------
3203
3223
3204 target : str
3224 target : str
3205
3225
3206 A string specifying code to retrieve. This will be tried respectively
3226 A string specifying code to retrieve. This will be tried respectively
3207 as: ranges of input history (see %history for syntax), url,
3227 as: ranges of input history (see %history for syntax), url,
3208 corresponding .py file, filename, or an expression evaluating to a
3228 corresponding .py file, filename, or an expression evaluating to a
3209 string or Macro in the user namespace.
3229 string or Macro in the user namespace.
3210
3230
3211 raw : bool
3231 raw : bool
3212 If true (default), retrieve raw history. Has no effect on the other
3232 If true (default), retrieve raw history. Has no effect on the other
3213 retrieval mechanisms.
3233 retrieval mechanisms.
3214
3234
3215 py_only : bool (default False)
3235 py_only : bool (default False)
3216 Only try to fetch python code, do not try alternative methods to decode file
3236 Only try to fetch python code, do not try alternative methods to decode file
3217 if unicode fails.
3237 if unicode fails.
3218
3238
3219 Returns
3239 Returns
3220 -------
3240 -------
3221 A string of code.
3241 A string of code.
3222
3242
3223 ValueError is raised if nothing is found, and TypeError if it evaluates
3243 ValueError is raised if nothing is found, and TypeError if it evaluates
3224 to an object of another type. In each case, .args[0] is a printable
3244 to an object of another type. In each case, .args[0] is a printable
3225 message.
3245 message.
3226 """
3246 """
3227 code = self.extract_input_lines(target, raw=raw) # Grab history
3247 code = self.extract_input_lines(target, raw=raw) # Grab history
3228 if code:
3248 if code:
3229 return code
3249 return code
3230 try:
3250 try:
3231 if target.startswith(('http://', 'https://')):
3251 if target.startswith(('http://', 'https://')):
3232 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3252 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3233 except UnicodeDecodeError:
3253 except UnicodeDecodeError:
3234 if not py_only :
3254 if not py_only :
3235 # Deferred import
3255 # Deferred import
3236 from urllib.request import urlopen
3256 from urllib.request import urlopen
3237 response = urlopen(target)
3257 response = urlopen(target)
3238 return response.read().decode('latin1')
3258 return response.read().decode('latin1')
3239 raise ValueError(("'%s' seem to be unreadable.") % target)
3259 raise ValueError(("'%s' seem to be unreadable.") % target)
3240
3260
3241 potential_target = [target]
3261 potential_target = [target]
3242 try :
3262 try :
3243 potential_target.insert(0,get_py_filename(target))
3263 potential_target.insert(0,get_py_filename(target))
3244 except IOError:
3264 except IOError:
3245 pass
3265 pass
3246
3266
3247 for tgt in potential_target :
3267 for tgt in potential_target :
3248 if os.path.isfile(tgt): # Read file
3268 if os.path.isfile(tgt): # Read file
3249 try :
3269 try :
3250 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3270 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3251 except UnicodeDecodeError :
3271 except UnicodeDecodeError :
3252 if not py_only :
3272 if not py_only :
3253 with io_open(tgt,'r', encoding='latin1') as f :
3273 with io_open(tgt,'r', encoding='latin1') as f :
3254 return f.read()
3274 return f.read()
3255 raise ValueError(("'%s' seem to be unreadable.") % target)
3275 raise ValueError(("'%s' seem to be unreadable.") % target)
3256 elif os.path.isdir(os.path.expanduser(tgt)):
3276 elif os.path.isdir(os.path.expanduser(tgt)):
3257 raise ValueError("'%s' is a directory, not a regular file." % target)
3277 raise ValueError("'%s' is a directory, not a regular file." % target)
3258
3278
3259 if search_ns:
3279 if search_ns:
3260 # Inspect namespace to load object source
3280 # Inspect namespace to load object source
3261 object_info = self.object_inspect(target, detail_level=1)
3281 object_info = self.object_inspect(target, detail_level=1)
3262 if object_info['found'] and object_info['source']:
3282 if object_info['found'] and object_info['source']:
3263 return object_info['source']
3283 return object_info['source']
3264
3284
3265 try: # User namespace
3285 try: # User namespace
3266 codeobj = eval(target, self.user_ns)
3286 codeobj = eval(target, self.user_ns)
3267 except Exception:
3287 except Exception:
3268 raise ValueError(("'%s' was not found in history, as a file, url, "
3288 raise ValueError(("'%s' was not found in history, as a file, url, "
3269 "nor in the user namespace.") % target)
3289 "nor in the user namespace.") % target)
3270
3290
3271 if isinstance(codeobj, str):
3291 if isinstance(codeobj, str):
3272 return codeobj
3292 return codeobj
3273 elif isinstance(codeobj, Macro):
3293 elif isinstance(codeobj, Macro):
3274 return codeobj.value
3294 return codeobj.value
3275
3295
3276 raise TypeError("%s is neither a string nor a macro." % target,
3296 raise TypeError("%s is neither a string nor a macro." % target,
3277 codeobj)
3297 codeobj)
3278
3298
3279 #-------------------------------------------------------------------------
3299 #-------------------------------------------------------------------------
3280 # Things related to IPython exiting
3300 # Things related to IPython exiting
3281 #-------------------------------------------------------------------------
3301 #-------------------------------------------------------------------------
3282 def atexit_operations(self):
3302 def atexit_operations(self):
3283 """This will be executed at the time of exit.
3303 """This will be executed at the time of exit.
3284
3304
3285 Cleanup operations and saving of persistent data that is done
3305 Cleanup operations and saving of persistent data that is done
3286 unconditionally by IPython should be performed here.
3306 unconditionally by IPython should be performed here.
3287
3307
3288 For things that may depend on startup flags or platform specifics (such
3308 For things that may depend on startup flags or platform specifics (such
3289 as having readline or not), register a separate atexit function in the
3309 as having readline or not), register a separate atexit function in the
3290 code that has the appropriate information, rather than trying to
3310 code that has the appropriate information, rather than trying to
3291 clutter
3311 clutter
3292 """
3312 """
3293 # Close the history session (this stores the end time and line count)
3313 # Close the history session (this stores the end time and line count)
3294 # this must be *before* the tempfile cleanup, in case of temporary
3314 # this must be *before* the tempfile cleanup, in case of temporary
3295 # history db
3315 # history db
3296 self.history_manager.end_session()
3316 self.history_manager.end_session()
3297
3317
3298 # Cleanup all tempfiles and folders left around
3318 # Cleanup all tempfiles and folders left around
3299 for tfile in self.tempfiles:
3319 for tfile in self.tempfiles:
3300 try:
3320 try:
3301 os.unlink(tfile)
3321 os.unlink(tfile)
3302 except OSError:
3322 except OSError:
3303 pass
3323 pass
3304
3324
3305 for tdir in self.tempdirs:
3325 for tdir in self.tempdirs:
3306 try:
3326 try:
3307 os.rmdir(tdir)
3327 os.rmdir(tdir)
3308 except OSError:
3328 except OSError:
3309 pass
3329 pass
3310
3330
3311 # Clear all user namespaces to release all references cleanly.
3331 # Clear all user namespaces to release all references cleanly.
3312 self.reset(new_session=False)
3332 self.reset(new_session=False)
3313
3333
3314 # Run user hooks
3334 # Run user hooks
3315 self.hooks.shutdown_hook()
3335 self.hooks.shutdown_hook()
3316
3336
3317 def cleanup(self):
3337 def cleanup(self):
3318 self.restore_sys_module_state()
3338 self.restore_sys_module_state()
3319
3339
3320
3340
3321 # Overridden in terminal subclass to change prompts
3341 # Overridden in terminal subclass to change prompts
3322 def switch_doctest_mode(self, mode):
3342 def switch_doctest_mode(self, mode):
3323 pass
3343 pass
3324
3344
3325
3345
3326 class InteractiveShellABC(metaclass=abc.ABCMeta):
3346 class InteractiveShellABC(metaclass=abc.ABCMeta):
3327 """An abstract base class for InteractiveShell."""
3347 """An abstract base class for InteractiveShell."""
3328
3348
3329 InteractiveShellABC.register(InteractiveShell)
3349 InteractiveShellABC.register(InteractiveShell)
@@ -1,1171 +1,1170 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Sphinx directive to support embedded IPython code.
3 Sphinx directive to support embedded IPython code.
4
4
5 This directive allows pasting of entire interactive IPython sessions, prompts
5 This directive allows pasting of entire interactive IPython sessions, prompts
6 and all, and their code will actually get re-executed at doc build time, with
6 and all, and their code will actually get re-executed at doc build time, with
7 all prompts renumbered sequentially. It also allows you to input code as a pure
7 all prompts renumbered sequentially. It also allows you to input code as a pure
8 python input by giving the argument python to the directive. The output looks
8 python input by giving the argument python to the directive. The output looks
9 like an interactive ipython section.
9 like an interactive ipython section.
10
10
11 To enable this directive, simply list it in your Sphinx ``conf.py`` file
11 To enable this directive, simply list it in your Sphinx ``conf.py`` file
12 (making sure the directory where you placed it is visible to sphinx, as is
12 (making sure the directory where you placed it is visible to sphinx, as is
13 needed for all Sphinx directives). For example, to enable syntax highlighting
13 needed for all Sphinx directives). For example, to enable syntax highlighting
14 and the IPython directive::
14 and the IPython directive::
15
15
16 extensions = ['IPython.sphinxext.ipython_console_highlighting',
16 extensions = ['IPython.sphinxext.ipython_console_highlighting',
17 'IPython.sphinxext.ipython_directive']
17 'IPython.sphinxext.ipython_directive']
18
18
19 The IPython directive outputs code-blocks with the language 'ipython'. So
19 The IPython directive outputs code-blocks with the language 'ipython'. So
20 if you do not have the syntax highlighting extension enabled as well, then
20 if you do not have the syntax highlighting extension enabled as well, then
21 all rendered code-blocks will be uncolored. By default this directive assumes
21 all rendered code-blocks will be uncolored. By default this directive assumes
22 that your prompts are unchanged IPython ones, but this can be customized.
22 that your prompts are unchanged IPython ones, but this can be customized.
23 The configurable options that can be placed in conf.py are:
23 The configurable options that can be placed in conf.py are:
24
24
25 ipython_savefig_dir:
25 ipython_savefig_dir:
26 The directory in which to save the figures. This is relative to the
26 The directory in which to save the figures. This is relative to the
27 Sphinx source directory. The default is `html_static_path`.
27 Sphinx source directory. The default is `html_static_path`.
28 ipython_rgxin:
28 ipython_rgxin:
29 The compiled regular expression to denote the start of IPython input
29 The compiled regular expression to denote the start of IPython input
30 lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
30 lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You
31 shouldn't need to change this.
31 shouldn't need to change this.
32 ipython_rgxout:
32 ipython_rgxout:
33 The compiled regular expression to denote the start of IPython output
33 The compiled regular expression to denote the start of IPython output
34 lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
34 lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You
35 shouldn't need to change this.
35 shouldn't need to change this.
36 ipython_promptin:
36 ipython_promptin:
37 The string to represent the IPython input prompt in the generated ReST.
37 The string to represent the IPython input prompt in the generated ReST.
38 The default is 'In [%d]:'. This expects that the line numbers are used
38 The default is 'In [%d]:'. This expects that the line numbers are used
39 in the prompt.
39 in the prompt.
40 ipython_promptout:
40 ipython_promptout:
41 The string to represent the IPython prompt in the generated ReST. The
41 The string to represent the IPython prompt in the generated ReST. The
42 default is 'Out [%d]:'. This expects that the line numbers are used
42 default is 'Out [%d]:'. This expects that the line numbers are used
43 in the prompt.
43 in the prompt.
44 ipython_mplbackend:
44 ipython_mplbackend:
45 The string which specifies if the embedded Sphinx shell should import
45 The string which specifies if the embedded Sphinx shell should import
46 Matplotlib and set the backend. The value specifies a backend that is
46 Matplotlib and set the backend. The value specifies a backend that is
47 passed to `matplotlib.use()` before any lines in `ipython_execlines` are
47 passed to `matplotlib.use()` before any lines in `ipython_execlines` are
48 executed. If not specified in conf.py, then the default value of 'agg' is
48 executed. If not specified in conf.py, then the default value of 'agg' is
49 used. To use the IPython directive without matplotlib as a dependency, set
49 used. To use the IPython directive without matplotlib as a dependency, set
50 the value to `None`. It may end up that matplotlib is still imported
50 the value to `None`. It may end up that matplotlib is still imported
51 if the user specifies so in `ipython_execlines` or makes use of the
51 if the user specifies so in `ipython_execlines` or makes use of the
52 @savefig pseudo decorator.
52 @savefig pseudo decorator.
53 ipython_execlines:
53 ipython_execlines:
54 A list of strings to be exec'd in the embedded Sphinx shell. Typical
54 A list of strings to be exec'd in the embedded Sphinx shell. Typical
55 usage is to make certain packages always available. Set this to an empty
55 usage is to make certain packages always available. Set this to an empty
56 list if you wish to have no imports always available. If specified in
56 list if you wish to have no imports always available. If specified in
57 conf.py as `None`, then it has the effect of making no imports available.
57 conf.py as `None`, then it has the effect of making no imports available.
58 If omitted from conf.py altogether, then the default value of
58 If omitted from conf.py altogether, then the default value of
59 ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
59 ['import numpy as np', 'import matplotlib.pyplot as plt'] is used.
60 ipython_holdcount
60 ipython_holdcount
61 When the @suppress pseudo-decorator is used, the execution count can be
61 When the @suppress pseudo-decorator is used, the execution count can be
62 incremented or not. The default behavior is to hold the execution count,
62 incremented or not. The default behavior is to hold the execution count,
63 corresponding to a value of `True`. Set this to `False` to increment
63 corresponding to a value of `True`. Set this to `False` to increment
64 the execution count after each suppressed command.
64 the execution count after each suppressed command.
65
65
66 As an example, to use the IPython directive when `matplotlib` is not available,
66 As an example, to use the IPython directive when `matplotlib` is not available,
67 one sets the backend to `None`::
67 one sets the backend to `None`::
68
68
69 ipython_mplbackend = None
69 ipython_mplbackend = None
70
70
71 An example usage of the directive is:
71 An example usage of the directive is:
72
72
73 .. code-block:: rst
73 .. code-block:: rst
74
74
75 .. ipython::
75 .. ipython::
76
76
77 In [1]: x = 1
77 In [1]: x = 1
78
78
79 In [2]: y = x**2
79 In [2]: y = x**2
80
80
81 In [3]: print(y)
81 In [3]: print(y)
82
82
83 See http://matplotlib.org/sampledoc/ipython_directive.html for additional
83 See http://matplotlib.org/sampledoc/ipython_directive.html for additional
84 documentation.
84 documentation.
85
85
86 Pseudo-Decorators
86 Pseudo-Decorators
87 =================
87 =================
88
88
89 Note: Only one decorator is supported per input. If more than one decorator
89 Note: Only one decorator is supported per input. If more than one decorator
90 is specified, then only the last one is used.
90 is specified, then only the last one is used.
91
91
92 In addition to the Pseudo-Decorators/options described at the above link,
92 In addition to the Pseudo-Decorators/options described at the above link,
93 several enhancements have been made. The directive will emit a message to the
93 several enhancements have been made. The directive will emit a message to the
94 console at build-time if code-execution resulted in an exception or warning.
94 console at build-time if code-execution resulted in an exception or warning.
95 You can suppress these on a per-block basis by specifying the :okexcept:
95 You can suppress these on a per-block basis by specifying the :okexcept:
96 or :okwarning: options:
96 or :okwarning: options:
97
97
98 .. code-block:: rst
98 .. code-block:: rst
99
99
100 .. ipython::
100 .. ipython::
101 :okexcept:
101 :okexcept:
102 :okwarning:
102 :okwarning:
103
103
104 In [1]: 1/0
104 In [1]: 1/0
105 In [2]: # raise warning.
105 In [2]: # raise warning.
106
106
107 To Do
107 To Do
108 -----
108 -----
109
109
110 - Turn the ad-hoc test() function into a real test suite.
110 - Turn the ad-hoc test() function into a real test suite.
111 - Break up ipython-specific functionality from matplotlib stuff into better
111 - Break up ipython-specific functionality from matplotlib stuff into better
112 separated code.
112 separated code.
113
113
114 Authors
114 Authors
115 -------
115 -------
116
116
117 - John D Hunter: original author.
117 - John D Hunter: original author.
118 - Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
118 - Fernando Perez: refactoring, documentation, cleanups, port to 0.11.
119 - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
119 - VΓ‘clavΕ milauer <eudoxos-AT-arcig.cz>: Prompt generalizations.
120 - Skipper Seabold, refactoring, cleanups, pure python addition
120 - Skipper Seabold, refactoring, cleanups, pure python addition
121 """
121 """
122
122
123 #-----------------------------------------------------------------------------
123 #-----------------------------------------------------------------------------
124 # Imports
124 # Imports
125 #-----------------------------------------------------------------------------
125 #-----------------------------------------------------------------------------
126
126
127 # Stdlib
127 # Stdlib
128 import atexit
128 import atexit
129 import errno
129 import errno
130 import os
130 import os
131 import re
131 import re
132 import sys
132 import sys
133 import tempfile
133 import tempfile
134 import ast
134 import ast
135 import warnings
135 import warnings
136 import shutil
136 import shutil
137 from io import StringIO
137 from io import StringIO
138
138
139 # Third-party
139 # Third-party
140 from docutils.parsers.rst import directives
140 from docutils.parsers.rst import directives
141 from docutils.parsers.rst import Directive
141 from docutils.parsers.rst import Directive
142
142
143 # Our own
143 # Our own
144 from traitlets.config import Config
144 from traitlets.config import Config
145 from IPython import InteractiveShell
145 from IPython import InteractiveShell
146 from IPython.core.profiledir import ProfileDir
146 from IPython.core.profiledir import ProfileDir
147
147
148 #-----------------------------------------------------------------------------
148 #-----------------------------------------------------------------------------
149 # Globals
149 # Globals
150 #-----------------------------------------------------------------------------
150 #-----------------------------------------------------------------------------
151 # for tokenizing blocks
151 # for tokenizing blocks
152 COMMENT, INPUT, OUTPUT = range(3)
152 COMMENT, INPUT, OUTPUT = range(3)
153
153
154 #-----------------------------------------------------------------------------
154 #-----------------------------------------------------------------------------
155 # Functions and class declarations
155 # Functions and class declarations
156 #-----------------------------------------------------------------------------
156 #-----------------------------------------------------------------------------
157
157
158 def block_parser(part, rgxin, rgxout, fmtin, fmtout):
158 def block_parser(part, rgxin, rgxout, fmtin, fmtout):
159 """
159 """
160 part is a string of ipython text, comprised of at most one
160 part is a string of ipython text, comprised of at most one
161 input, one output, comments, and blank lines. The block parser
161 input, one output, comments, and blank lines. The block parser
162 parses the text into a list of::
162 parses the text into a list of::
163
163
164 blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
164 blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
165
165
166 where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
166 where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
167 data is, depending on the type of token::
167 data is, depending on the type of token::
168
168
169 COMMENT : the comment string
169 COMMENT : the comment string
170
170
171 INPUT: the (DECORATOR, INPUT_LINE, REST) where
171 INPUT: the (DECORATOR, INPUT_LINE, REST) where
172 DECORATOR: the input decorator (or None)
172 DECORATOR: the input decorator (or None)
173 INPUT_LINE: the input as string (possibly multi-line)
173 INPUT_LINE: the input as string (possibly multi-line)
174 REST : any stdout generated by the input line (not OUTPUT)
174 REST : any stdout generated by the input line (not OUTPUT)
175
175
176 OUTPUT: the output string, possibly multi-line
176 OUTPUT: the output string, possibly multi-line
177
177
178 """
178 """
179 block = []
179 block = []
180 lines = part.split('\n')
180 lines = part.split('\n')
181 N = len(lines)
181 N = len(lines)
182 i = 0
182 i = 0
183 decorator = None
183 decorator = None
184 while 1:
184 while 1:
185
185
186 if i==N:
186 if i==N:
187 # nothing left to parse -- the last line
187 # nothing left to parse -- the last line
188 break
188 break
189
189
190 line = lines[i]
190 line = lines[i]
191 i += 1
191 i += 1
192 line_stripped = line.strip()
192 line_stripped = line.strip()
193 if line_stripped.startswith('#'):
193 if line_stripped.startswith('#'):
194 block.append((COMMENT, line))
194 block.append((COMMENT, line))
195 continue
195 continue
196
196
197 if line_stripped.startswith('@'):
197 if line_stripped.startswith('@'):
198 # Here is where we assume there is, at most, one decorator.
198 # Here is where we assume there is, at most, one decorator.
199 # Might need to rethink this.
199 # Might need to rethink this.
200 decorator = line_stripped
200 decorator = line_stripped
201 continue
201 continue
202
202
203 # does this look like an input line?
203 # does this look like an input line?
204 matchin = rgxin.match(line)
204 matchin = rgxin.match(line)
205 if matchin:
205 if matchin:
206 lineno, inputline = int(matchin.group(1)), matchin.group(2)
206 lineno, inputline = int(matchin.group(1)), matchin.group(2)
207
207
208 # the ....: continuation string
208 # the ....: continuation string
209 continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
209 continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
210 Nc = len(continuation)
210 Nc = len(continuation)
211 # input lines can continue on for more than one line, if
211 # input lines can continue on for more than one line, if
212 # we have a '\' line continuation char or a function call
212 # we have a '\' line continuation char or a function call
213 # echo line 'print'. The input line can only be
213 # echo line 'print'. The input line can only be
214 # terminated by the end of the block or an output line, so
214 # terminated by the end of the block or an output line, so
215 # we parse out the rest of the input line if it is
215 # we parse out the rest of the input line if it is
216 # multiline as well as any echo text
216 # multiline as well as any echo text
217
217
218 rest = []
218 rest = []
219 while i<N:
219 while i<N:
220
220
221 # look ahead; if the next line is blank, or a comment, or
221 # look ahead; if the next line is blank, or a comment, or
222 # an output line, we're done
222 # an output line, we're done
223
223
224 nextline = lines[i]
224 nextline = lines[i]
225 matchout = rgxout.match(nextline)
225 matchout = rgxout.match(nextline)
226 #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation))
226 #print "nextline=%s, continuation=%s, starts=%s"%(nextline, continuation, nextline.startswith(continuation))
227 if matchout or nextline.startswith('#'):
227 if matchout or nextline.startswith('#'):
228 break
228 break
229 elif nextline.startswith(continuation):
229 elif nextline.startswith(continuation):
230 # The default ipython_rgx* treat the space following the colon as optional.
230 # The default ipython_rgx* treat the space following the colon as optional.
231 # However, If the space is there we must consume it or code
231 # However, If the space is there we must consume it or code
232 # employing the cython_magic extension will fail to execute.
232 # employing the cython_magic extension will fail to execute.
233 #
233 #
234 # This works with the default ipython_rgx* patterns,
234 # This works with the default ipython_rgx* patterns,
235 # If you modify them, YMMV.
235 # If you modify them, YMMV.
236 nextline = nextline[Nc:]
236 nextline = nextline[Nc:]
237 if nextline and nextline[0] == ' ':
237 if nextline and nextline[0] == ' ':
238 nextline = nextline[1:]
238 nextline = nextline[1:]
239
239
240 inputline += '\n' + nextline
240 inputline += '\n' + nextline
241 else:
241 else:
242 rest.append(nextline)
242 rest.append(nextline)
243 i+= 1
243 i+= 1
244
244
245 block.append((INPUT, (decorator, inputline, '\n'.join(rest))))
245 block.append((INPUT, (decorator, inputline, '\n'.join(rest))))
246 continue
246 continue
247
247
248 # if it looks like an output line grab all the text to the end
248 # if it looks like an output line grab all the text to the end
249 # of the block
249 # of the block
250 matchout = rgxout.match(line)
250 matchout = rgxout.match(line)
251 if matchout:
251 if matchout:
252 lineno, output = int(matchout.group(1)), matchout.group(2)
252 lineno, output = int(matchout.group(1)), matchout.group(2)
253 if i<N-1:
253 if i<N-1:
254 output = '\n'.join([output] + lines[i:])
254 output = '\n'.join([output] + lines[i:])
255
255
256 block.append((OUTPUT, output))
256 block.append((OUTPUT, output))
257 break
257 break
258
258
259 return block
259 return block
260
260
261
261
262 class EmbeddedSphinxShell(object):
262 class EmbeddedSphinxShell(object):
263 """An embedded IPython instance to run inside Sphinx"""
263 """An embedded IPython instance to run inside Sphinx"""
264
264
265 def __init__(self, exec_lines=None):
265 def __init__(self, exec_lines=None):
266
266
267 self.cout = StringIO()
267 self.cout = StringIO()
268
268
269 if exec_lines is None:
269 if exec_lines is None:
270 exec_lines = []
270 exec_lines = []
271
271
272 # Create config object for IPython
272 # Create config object for IPython
273 config = Config()
273 config = Config()
274 config.HistoryManager.hist_file = ':memory:'
274 config.HistoryManager.hist_file = ':memory:'
275 config.InteractiveShell.autocall = False
275 config.InteractiveShell.autocall = False
276 config.InteractiveShell.autoindent = False
276 config.InteractiveShell.autoindent = False
277 config.InteractiveShell.colors = 'NoColor'
277 config.InteractiveShell.colors = 'NoColor'
278
278
279 # create a profile so instance history isn't saved
279 # create a profile so instance history isn't saved
280 tmp_profile_dir = tempfile.mkdtemp(prefix='profile_')
280 tmp_profile_dir = tempfile.mkdtemp(prefix='profile_')
281 profname = 'auto_profile_sphinx_build'
281 profname = 'auto_profile_sphinx_build'
282 pdir = os.path.join(tmp_profile_dir,profname)
282 pdir = os.path.join(tmp_profile_dir,profname)
283 profile = ProfileDir.create_profile_dir(pdir)
283 profile = ProfileDir.create_profile_dir(pdir)
284
284
285 # Create and initialize global ipython, but don't start its mainloop.
285 # Create and initialize global ipython, but don't start its mainloop.
286 # This will persist across different EmbeddedSphinxShell instances.
286 # This will persist across different EmbeddedSphinxShell instances.
287 IP = InteractiveShell.instance(config=config, profile_dir=profile)
287 IP = InteractiveShell.instance(config=config, profile_dir=profile)
288 atexit.register(self.cleanup)
288 atexit.register(self.cleanup)
289
289
290 # Store a few parts of IPython we'll need.
290 # Store a few parts of IPython we'll need.
291 self.IP = IP
291 self.IP = IP
292 self.user_ns = self.IP.user_ns
292 self.user_ns = self.IP.user_ns
293 self.user_global_ns = self.IP.user_global_ns
293 self.user_global_ns = self.IP.user_global_ns
294 self.input_transformer_mgr = self.IP.input_transformer_manager
295
294
296 self.lines_waiting = []
295 self.lines_waiting = []
297 self.input = ''
296 self.input = ''
298 self.output = ''
297 self.output = ''
299 self.tmp_profile_dir = tmp_profile_dir
298 self.tmp_profile_dir = tmp_profile_dir
300
299
301 self.is_verbatim = False
300 self.is_verbatim = False
302 self.is_doctest = False
301 self.is_doctest = False
303 self.is_suppress = False
302 self.is_suppress = False
304
303
305 # Optionally, provide more detailed information to shell.
304 # Optionally, provide more detailed information to shell.
306 # this is assigned by the SetUp method of IPythonDirective
305 # this is assigned by the SetUp method of IPythonDirective
307 # to point at itself.
306 # to point at itself.
308 #
307 #
309 # So, you can access handy things at self.directive.state
308 # So, you can access handy things at self.directive.state
310 self.directive = None
309 self.directive = None
311
310
312 # on the first call to the savefig decorator, we'll import
311 # on the first call to the savefig decorator, we'll import
313 # pyplot as plt so we can make a call to the plt.gcf().savefig
312 # pyplot as plt so we can make a call to the plt.gcf().savefig
314 self._pyplot_imported = False
313 self._pyplot_imported = False
315
314
316 # Prepopulate the namespace.
315 # Prepopulate the namespace.
317 for line in exec_lines:
316 for line in exec_lines:
318 self.process_input_line(line, store_history=False)
317 self.process_input_line(line, store_history=False)
319
318
320 def cleanup(self):
319 def cleanup(self):
321 shutil.rmtree(self.tmp_profile_dir, ignore_errors=True)
320 shutil.rmtree(self.tmp_profile_dir, ignore_errors=True)
322
321
323 def clear_cout(self):
322 def clear_cout(self):
324 self.cout.seek(0)
323 self.cout.seek(0)
325 self.cout.truncate(0)
324 self.cout.truncate(0)
326
325
327 def process_input_line(self, line, store_history=True):
326 def process_input_line(self, line, store_history=True):
328 """process the input, capturing stdout"""
327 """process the input, capturing stdout"""
329
328
330 stdout = sys.stdout
329 stdout = sys.stdout
331 try:
330 try:
332 sys.stdout = self.cout
331 sys.stdout = self.cout
333 self.lines_waiting.append(line)
332 self.lines_waiting.append(line)
334 if self.input_transformer_mgr.check_complete()[0] != 'incomplete':
333 if self.IP.check_complete()[0] != 'incomplete':
335 source_raw = ''.join(self.lines_waiting)
334 source_raw = ''.join(self.lines_waiting)
336 self.lines_waiting = []
335 self.lines_waiting = []
337 self.IP.run_cell(source_raw, store_history=store_history)
336 self.IP.run_cell(source_raw, store_history=store_history)
338 finally:
337 finally:
339 sys.stdout = stdout
338 sys.stdout = stdout
340
339
341 def process_image(self, decorator):
340 def process_image(self, decorator):
342 """
341 """
343 # build out an image directive like
342 # build out an image directive like
344 # .. image:: somefile.png
343 # .. image:: somefile.png
345 # :width 4in
344 # :width 4in
346 #
345 #
347 # from an input like
346 # from an input like
348 # savefig somefile.png width=4in
347 # savefig somefile.png width=4in
349 """
348 """
350 savefig_dir = self.savefig_dir
349 savefig_dir = self.savefig_dir
351 source_dir = self.source_dir
350 source_dir = self.source_dir
352 saveargs = decorator.split(' ')
351 saveargs = decorator.split(' ')
353 filename = saveargs[1]
352 filename = saveargs[1]
354 # insert relative path to image file in source (as absolute path for Sphinx)
353 # insert relative path to image file in source (as absolute path for Sphinx)
355 outfile = '/' + os.path.relpath(os.path.join(savefig_dir,filename),
354 outfile = '/' + os.path.relpath(os.path.join(savefig_dir,filename),
356 source_dir)
355 source_dir)
357
356
358 imagerows = ['.. image:: %s'%outfile]
357 imagerows = ['.. image:: %s'%outfile]
359
358
360 for kwarg in saveargs[2:]:
359 for kwarg in saveargs[2:]:
361 arg, val = kwarg.split('=')
360 arg, val = kwarg.split('=')
362 arg = arg.strip()
361 arg = arg.strip()
363 val = val.strip()
362 val = val.strip()
364 imagerows.append(' :%s: %s'%(arg, val))
363 imagerows.append(' :%s: %s'%(arg, val))
365
364
366 image_file = os.path.basename(outfile) # only return file name
365 image_file = os.path.basename(outfile) # only return file name
367 image_directive = '\n'.join(imagerows)
366 image_directive = '\n'.join(imagerows)
368 return image_file, image_directive
367 return image_file, image_directive
369
368
370 # Callbacks for each type of token
369 # Callbacks for each type of token
371 def process_input(self, data, input_prompt, lineno):
370 def process_input(self, data, input_prompt, lineno):
372 """
371 """
373 Process data block for INPUT token.
372 Process data block for INPUT token.
374
373
375 """
374 """
376 decorator, input, rest = data
375 decorator, input, rest = data
377 image_file = None
376 image_file = None
378 image_directive = None
377 image_directive = None
379
378
380 is_verbatim = decorator=='@verbatim' or self.is_verbatim
379 is_verbatim = decorator=='@verbatim' or self.is_verbatim
381 is_doctest = (decorator is not None and \
380 is_doctest = (decorator is not None and \
382 decorator.startswith('@doctest')) or self.is_doctest
381 decorator.startswith('@doctest')) or self.is_doctest
383 is_suppress = decorator=='@suppress' or self.is_suppress
382 is_suppress = decorator=='@suppress' or self.is_suppress
384 is_okexcept = decorator=='@okexcept' or self.is_okexcept
383 is_okexcept = decorator=='@okexcept' or self.is_okexcept
385 is_okwarning = decorator=='@okwarning' or self.is_okwarning
384 is_okwarning = decorator=='@okwarning' or self.is_okwarning
386 is_savefig = decorator is not None and \
385 is_savefig = decorator is not None and \
387 decorator.startswith('@savefig')
386 decorator.startswith('@savefig')
388
387
389 input_lines = input.split('\n')
388 input_lines = input.split('\n')
390 if len(input_lines) > 1:
389 if len(input_lines) > 1:
391 if input_lines[-1] != "":
390 if input_lines[-1] != "":
392 input_lines.append('') # make sure there's a blank line
391 input_lines.append('') # make sure there's a blank line
393 # so splitter buffer gets reset
392 # so splitter buffer gets reset
394
393
395 continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
394 continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2))
396
395
397 if is_savefig:
396 if is_savefig:
398 image_file, image_directive = self.process_image(decorator)
397 image_file, image_directive = self.process_image(decorator)
399
398
400 ret = []
399 ret = []
401 is_semicolon = False
400 is_semicolon = False
402
401
403 # Hold the execution count, if requested to do so.
402 # Hold the execution count, if requested to do so.
404 if is_suppress and self.hold_count:
403 if is_suppress and self.hold_count:
405 store_history = False
404 store_history = False
406 else:
405 else:
407 store_history = True
406 store_history = True
408
407
409 # Note: catch_warnings is not thread safe
408 # Note: catch_warnings is not thread safe
410 with warnings.catch_warnings(record=True) as ws:
409 with warnings.catch_warnings(record=True) as ws:
411 for i, line in enumerate(input_lines):
410 for i, line in enumerate(input_lines):
412 if line.endswith(';'):
411 if line.endswith(';'):
413 is_semicolon = True
412 is_semicolon = True
414
413
415 if i == 0:
414 if i == 0:
416 # process the first input line
415 # process the first input line
417 if is_verbatim:
416 if is_verbatim:
418 self.process_input_line('')
417 self.process_input_line('')
419 self.IP.execution_count += 1 # increment it anyway
418 self.IP.execution_count += 1 # increment it anyway
420 else:
419 else:
421 # only submit the line in non-verbatim mode
420 # only submit the line in non-verbatim mode
422 self.process_input_line(line, store_history=store_history)
421 self.process_input_line(line, store_history=store_history)
423 formatted_line = '%s %s'%(input_prompt, line)
422 formatted_line = '%s %s'%(input_prompt, line)
424 else:
423 else:
425 # process a continuation line
424 # process a continuation line
426 if not is_verbatim:
425 if not is_verbatim:
427 self.process_input_line(line, store_history=store_history)
426 self.process_input_line(line, store_history=store_history)
428
427
429 formatted_line = '%s %s'%(continuation, line)
428 formatted_line = '%s %s'%(continuation, line)
430
429
431 if not is_suppress:
430 if not is_suppress:
432 ret.append(formatted_line)
431 ret.append(formatted_line)
433
432
434 if not is_suppress and len(rest.strip()) and is_verbatim:
433 if not is_suppress and len(rest.strip()) and is_verbatim:
435 # The "rest" is the standard output of the input. This needs to be
434 # The "rest" is the standard output of the input. This needs to be
436 # added when in verbatim mode. If there is no "rest", then we don't
435 # added when in verbatim mode. If there is no "rest", then we don't
437 # add it, as the new line will be added by the processed output.
436 # add it, as the new line will be added by the processed output.
438 ret.append(rest)
437 ret.append(rest)
439
438
440 # Fetch the processed output. (This is not the submitted output.)
439 # Fetch the processed output. (This is not the submitted output.)
441 self.cout.seek(0)
440 self.cout.seek(0)
442 processed_output = self.cout.read()
441 processed_output = self.cout.read()
443 if not is_suppress and not is_semicolon:
442 if not is_suppress and not is_semicolon:
444 #
443 #
445 # In IPythonDirective.run, the elements of `ret` are eventually
444 # In IPythonDirective.run, the elements of `ret` are eventually
446 # combined such that '' entries correspond to newlines. So if
445 # combined such that '' entries correspond to newlines. So if
447 # `processed_output` is equal to '', then the adding it to `ret`
446 # `processed_output` is equal to '', then the adding it to `ret`
448 # ensures that there is a blank line between consecutive inputs
447 # ensures that there is a blank line between consecutive inputs
449 # that have no outputs, as in:
448 # that have no outputs, as in:
450 #
449 #
451 # In [1]: x = 4
450 # In [1]: x = 4
452 #
451 #
453 # In [2]: x = 5
452 # In [2]: x = 5
454 #
453 #
455 # When there is processed output, it has a '\n' at the tail end. So
454 # When there is processed output, it has a '\n' at the tail end. So
456 # adding the output to `ret` will provide the necessary spacing
455 # adding the output to `ret` will provide the necessary spacing
457 # between consecutive input/output blocks, as in:
456 # between consecutive input/output blocks, as in:
458 #
457 #
459 # In [1]: x
458 # In [1]: x
460 # Out[1]: 5
459 # Out[1]: 5
461 #
460 #
462 # In [2]: x
461 # In [2]: x
463 # Out[2]: 5
462 # Out[2]: 5
464 #
463 #
465 # When there is stdout from the input, it also has a '\n' at the
464 # When there is stdout from the input, it also has a '\n' at the
466 # tail end, and so this ensures proper spacing as well. E.g.:
465 # tail end, and so this ensures proper spacing as well. E.g.:
467 #
466 #
468 # In [1]: print x
467 # In [1]: print x
469 # 5
468 # 5
470 #
469 #
471 # In [2]: x = 5
470 # In [2]: x = 5
472 #
471 #
473 # When in verbatim mode, `processed_output` is empty (because
472 # When in verbatim mode, `processed_output` is empty (because
474 # nothing was passed to IP. Sometimes the submitted code block has
473 # nothing was passed to IP. Sometimes the submitted code block has
475 # an Out[] portion and sometimes it does not. When it does not, we
474 # an Out[] portion and sometimes it does not. When it does not, we
476 # need to ensure proper spacing, so we have to add '' to `ret`.
475 # need to ensure proper spacing, so we have to add '' to `ret`.
477 # However, if there is an Out[] in the submitted code, then we do
476 # However, if there is an Out[] in the submitted code, then we do
478 # not want to add a newline as `process_output` has stuff to add.
477 # not want to add a newline as `process_output` has stuff to add.
479 # The difficulty is that `process_input` doesn't know if
478 # The difficulty is that `process_input` doesn't know if
480 # `process_output` will be called---so it doesn't know if there is
479 # `process_output` will be called---so it doesn't know if there is
481 # Out[] in the code block. The requires that we include a hack in
480 # Out[] in the code block. The requires that we include a hack in
482 # `process_block`. See the comments there.
481 # `process_block`. See the comments there.
483 #
482 #
484 ret.append(processed_output)
483 ret.append(processed_output)
485 elif is_semicolon:
484 elif is_semicolon:
486 # Make sure there is a newline after the semicolon.
485 # Make sure there is a newline after the semicolon.
487 ret.append('')
486 ret.append('')
488
487
489 # context information
488 # context information
490 filename = "Unknown"
489 filename = "Unknown"
491 lineno = 0
490 lineno = 0
492 if self.directive.state:
491 if self.directive.state:
493 filename = self.directive.state.document.current_source
492 filename = self.directive.state.document.current_source
494 lineno = self.directive.state.document.current_line
493 lineno = self.directive.state.document.current_line
495
494
496 # output any exceptions raised during execution to stdout
495 # output any exceptions raised during execution to stdout
497 # unless :okexcept: has been specified.
496 # unless :okexcept: has been specified.
498 if not is_okexcept and "Traceback" in processed_output:
497 if not is_okexcept and "Traceback" in processed_output:
499 s = "\nException in %s at block ending on line %s\n" % (filename, lineno)
498 s = "\nException in %s at block ending on line %s\n" % (filename, lineno)
500 s += "Specify :okexcept: as an option in the ipython:: block to suppress this message\n"
499 s += "Specify :okexcept: as an option in the ipython:: block to suppress this message\n"
501 sys.stdout.write('\n\n>>>' + ('-' * 73))
500 sys.stdout.write('\n\n>>>' + ('-' * 73))
502 sys.stdout.write(s)
501 sys.stdout.write(s)
503 sys.stdout.write(processed_output)
502 sys.stdout.write(processed_output)
504 sys.stdout.write('<<<' + ('-' * 73) + '\n\n')
503 sys.stdout.write('<<<' + ('-' * 73) + '\n\n')
505
504
506 # output any warning raised during execution to stdout
505 # output any warning raised during execution to stdout
507 # unless :okwarning: has been specified.
506 # unless :okwarning: has been specified.
508 if not is_okwarning:
507 if not is_okwarning:
509 for w in ws:
508 for w in ws:
510 s = "\nWarning in %s at block ending on line %s\n" % (filename, lineno)
509 s = "\nWarning in %s at block ending on line %s\n" % (filename, lineno)
511 s += "Specify :okwarning: as an option in the ipython:: block to suppress this message\n"
510 s += "Specify :okwarning: as an option in the ipython:: block to suppress this message\n"
512 sys.stdout.write('\n\n>>>' + ('-' * 73))
511 sys.stdout.write('\n\n>>>' + ('-' * 73))
513 sys.stdout.write(s)
512 sys.stdout.write(s)
514 sys.stdout.write(('-' * 76) + '\n')
513 sys.stdout.write(('-' * 76) + '\n')
515 s=warnings.formatwarning(w.message, w.category,
514 s=warnings.formatwarning(w.message, w.category,
516 w.filename, w.lineno, w.line)
515 w.filename, w.lineno, w.line)
517 sys.stdout.write(s)
516 sys.stdout.write(s)
518 sys.stdout.write('<<<' + ('-' * 73) + '\n')
517 sys.stdout.write('<<<' + ('-' * 73) + '\n')
519
518
520 self.cout.truncate(0)
519 self.cout.truncate(0)
521
520
522 return (ret, input_lines, processed_output,
521 return (ret, input_lines, processed_output,
523 is_doctest, decorator, image_file, image_directive)
522 is_doctest, decorator, image_file, image_directive)
524
523
525
524
526 def process_output(self, data, output_prompt, input_lines, output,
525 def process_output(self, data, output_prompt, input_lines, output,
527 is_doctest, decorator, image_file):
526 is_doctest, decorator, image_file):
528 """
527 """
529 Process data block for OUTPUT token.
528 Process data block for OUTPUT token.
530
529
531 """
530 """
532 # Recall: `data` is the submitted output, and `output` is the processed
531 # Recall: `data` is the submitted output, and `output` is the processed
533 # output from `input_lines`.
532 # output from `input_lines`.
534
533
535 TAB = ' ' * 4
534 TAB = ' ' * 4
536
535
537 if is_doctest and output is not None:
536 if is_doctest and output is not None:
538
537
539 found = output # This is the processed output
538 found = output # This is the processed output
540 found = found.strip()
539 found = found.strip()
541 submitted = data.strip()
540 submitted = data.strip()
542
541
543 if self.directive is None:
542 if self.directive is None:
544 source = 'Unavailable'
543 source = 'Unavailable'
545 content = 'Unavailable'
544 content = 'Unavailable'
546 else:
545 else:
547 source = self.directive.state.document.current_source
546 source = self.directive.state.document.current_source
548 content = self.directive.content
547 content = self.directive.content
549 # Add tabs and join into a single string.
548 # Add tabs and join into a single string.
550 content = '\n'.join([TAB + line for line in content])
549 content = '\n'.join([TAB + line for line in content])
551
550
552 # Make sure the output contains the output prompt.
551 # Make sure the output contains the output prompt.
553 ind = found.find(output_prompt)
552 ind = found.find(output_prompt)
554 if ind < 0:
553 if ind < 0:
555 e = ('output does not contain output prompt\n\n'
554 e = ('output does not contain output prompt\n\n'
556 'Document source: {0}\n\n'
555 'Document source: {0}\n\n'
557 'Raw content: \n{1}\n\n'
556 'Raw content: \n{1}\n\n'
558 'Input line(s):\n{TAB}{2}\n\n'
557 'Input line(s):\n{TAB}{2}\n\n'
559 'Output line(s):\n{TAB}{3}\n\n')
558 'Output line(s):\n{TAB}{3}\n\n')
560 e = e.format(source, content, '\n'.join(input_lines),
559 e = e.format(source, content, '\n'.join(input_lines),
561 repr(found), TAB=TAB)
560 repr(found), TAB=TAB)
562 raise RuntimeError(e)
561 raise RuntimeError(e)
563 found = found[len(output_prompt):].strip()
562 found = found[len(output_prompt):].strip()
564
563
565 # Handle the actual doctest comparison.
564 # Handle the actual doctest comparison.
566 if decorator.strip() == '@doctest':
565 if decorator.strip() == '@doctest':
567 # Standard doctest
566 # Standard doctest
568 if found != submitted:
567 if found != submitted:
569 e = ('doctest failure\n\n'
568 e = ('doctest failure\n\n'
570 'Document source: {0}\n\n'
569 'Document source: {0}\n\n'
571 'Raw content: \n{1}\n\n'
570 'Raw content: \n{1}\n\n'
572 'On input line(s):\n{TAB}{2}\n\n'
571 'On input line(s):\n{TAB}{2}\n\n'
573 'we found output:\n{TAB}{3}\n\n'
572 'we found output:\n{TAB}{3}\n\n'
574 'instead of the expected:\n{TAB}{4}\n\n')
573 'instead of the expected:\n{TAB}{4}\n\n')
575 e = e.format(source, content, '\n'.join(input_lines),
574 e = e.format(source, content, '\n'.join(input_lines),
576 repr(found), repr(submitted), TAB=TAB)
575 repr(found), repr(submitted), TAB=TAB)
577 raise RuntimeError(e)
576 raise RuntimeError(e)
578 else:
577 else:
579 self.custom_doctest(decorator, input_lines, found, submitted)
578 self.custom_doctest(decorator, input_lines, found, submitted)
580
579
581 # When in verbatim mode, this holds additional submitted output
580 # When in verbatim mode, this holds additional submitted output
582 # to be written in the final Sphinx output.
581 # to be written in the final Sphinx output.
583 # https://github.com/ipython/ipython/issues/5776
582 # https://github.com/ipython/ipython/issues/5776
584 out_data = []
583 out_data = []
585
584
586 is_verbatim = decorator=='@verbatim' or self.is_verbatim
585 is_verbatim = decorator=='@verbatim' or self.is_verbatim
587 if is_verbatim and data.strip():
586 if is_verbatim and data.strip():
588 # Note that `ret` in `process_block` has '' as its last element if
587 # Note that `ret` in `process_block` has '' as its last element if
589 # the code block was in verbatim mode. So if there is no submitted
588 # the code block was in verbatim mode. So if there is no submitted
590 # output, then we will have proper spacing only if we do not add
589 # output, then we will have proper spacing only if we do not add
591 # an additional '' to `out_data`. This is why we condition on
590 # an additional '' to `out_data`. This is why we condition on
592 # `and data.strip()`.
591 # `and data.strip()`.
593
592
594 # The submitted output has no output prompt. If we want the
593 # The submitted output has no output prompt. If we want the
595 # prompt and the code to appear, we need to join them now
594 # prompt and the code to appear, we need to join them now
596 # instead of adding them separately---as this would create an
595 # instead of adding them separately---as this would create an
597 # undesired newline. How we do this ultimately depends on the
596 # undesired newline. How we do this ultimately depends on the
598 # format of the output regex. I'll do what works for the default
597 # format of the output regex. I'll do what works for the default
599 # prompt for now, and we might have to adjust if it doesn't work
598 # prompt for now, and we might have to adjust if it doesn't work
600 # in other cases. Finally, the submitted output does not have
599 # in other cases. Finally, the submitted output does not have
601 # a trailing newline, so we must add it manually.
600 # a trailing newline, so we must add it manually.
602 out_data.append("{0} {1}\n".format(output_prompt, data))
601 out_data.append("{0} {1}\n".format(output_prompt, data))
603
602
604 return out_data
603 return out_data
605
604
606 def process_comment(self, data):
605 def process_comment(self, data):
607 """Process data fPblock for COMMENT token."""
606 """Process data fPblock for COMMENT token."""
608 if not self.is_suppress:
607 if not self.is_suppress:
609 return [data]
608 return [data]
610
609
611 def save_image(self, image_file):
610 def save_image(self, image_file):
612 """
611 """
613 Saves the image file to disk.
612 Saves the image file to disk.
614 """
613 """
615 self.ensure_pyplot()
614 self.ensure_pyplot()
616 command = 'plt.gcf().savefig("%s")'%image_file
615 command = 'plt.gcf().savefig("%s")'%image_file
617 #print 'SAVEFIG', command # dbg
616 #print 'SAVEFIG', command # dbg
618 self.process_input_line('bookmark ipy_thisdir', store_history=False)
617 self.process_input_line('bookmark ipy_thisdir', store_history=False)
619 self.process_input_line('cd -b ipy_savedir', store_history=False)
618 self.process_input_line('cd -b ipy_savedir', store_history=False)
620 self.process_input_line(command, store_history=False)
619 self.process_input_line(command, store_history=False)
621 self.process_input_line('cd -b ipy_thisdir', store_history=False)
620 self.process_input_line('cd -b ipy_thisdir', store_history=False)
622 self.process_input_line('bookmark -d ipy_thisdir', store_history=False)
621 self.process_input_line('bookmark -d ipy_thisdir', store_history=False)
623 self.clear_cout()
622 self.clear_cout()
624
623
625 def process_block(self, block):
624 def process_block(self, block):
626 """
625 """
627 process block from the block_parser and return a list of processed lines
626 process block from the block_parser and return a list of processed lines
628 """
627 """
629 ret = []
628 ret = []
630 output = None
629 output = None
631 input_lines = None
630 input_lines = None
632 lineno = self.IP.execution_count
631 lineno = self.IP.execution_count
633
632
634 input_prompt = self.promptin % lineno
633 input_prompt = self.promptin % lineno
635 output_prompt = self.promptout % lineno
634 output_prompt = self.promptout % lineno
636 image_file = None
635 image_file = None
637 image_directive = None
636 image_directive = None
638
637
639 found_input = False
638 found_input = False
640 for token, data in block:
639 for token, data in block:
641 if token == COMMENT:
640 if token == COMMENT:
642 out_data = self.process_comment(data)
641 out_data = self.process_comment(data)
643 elif token == INPUT:
642 elif token == INPUT:
644 found_input = True
643 found_input = True
645 (out_data, input_lines, output, is_doctest,
644 (out_data, input_lines, output, is_doctest,
646 decorator, image_file, image_directive) = \
645 decorator, image_file, image_directive) = \
647 self.process_input(data, input_prompt, lineno)
646 self.process_input(data, input_prompt, lineno)
648 elif token == OUTPUT:
647 elif token == OUTPUT:
649 if not found_input:
648 if not found_input:
650
649
651 TAB = ' ' * 4
650 TAB = ' ' * 4
652 linenumber = 0
651 linenumber = 0
653 source = 'Unavailable'
652 source = 'Unavailable'
654 content = 'Unavailable'
653 content = 'Unavailable'
655 if self.directive:
654 if self.directive:
656 linenumber = self.directive.state.document.current_line
655 linenumber = self.directive.state.document.current_line
657 source = self.directive.state.document.current_source
656 source = self.directive.state.document.current_source
658 content = self.directive.content
657 content = self.directive.content
659 # Add tabs and join into a single string.
658 # Add tabs and join into a single string.
660 content = '\n'.join([TAB + line for line in content])
659 content = '\n'.join([TAB + line for line in content])
661
660
662 e = ('\n\nInvalid block: Block contains an output prompt '
661 e = ('\n\nInvalid block: Block contains an output prompt '
663 'without an input prompt.\n\n'
662 'without an input prompt.\n\n'
664 'Document source: {0}\n\n'
663 'Document source: {0}\n\n'
665 'Content begins at line {1}: \n\n{2}\n\n'
664 'Content begins at line {1}: \n\n{2}\n\n'
666 'Problematic block within content: \n\n{TAB}{3}\n\n')
665 'Problematic block within content: \n\n{TAB}{3}\n\n')
667 e = e.format(source, linenumber, content, block, TAB=TAB)
666 e = e.format(source, linenumber, content, block, TAB=TAB)
668
667
669 # Write, rather than include in exception, since Sphinx
668 # Write, rather than include in exception, since Sphinx
670 # will truncate tracebacks.
669 # will truncate tracebacks.
671 sys.stdout.write(e)
670 sys.stdout.write(e)
672 raise RuntimeError('An invalid block was detected.')
671 raise RuntimeError('An invalid block was detected.')
673
672
674 out_data = \
673 out_data = \
675 self.process_output(data, output_prompt, input_lines,
674 self.process_output(data, output_prompt, input_lines,
676 output, is_doctest, decorator,
675 output, is_doctest, decorator,
677 image_file)
676 image_file)
678 if out_data:
677 if out_data:
679 # Then there was user submitted output in verbatim mode.
678 # Then there was user submitted output in verbatim mode.
680 # We need to remove the last element of `ret` that was
679 # We need to remove the last element of `ret` that was
681 # added in `process_input`, as it is '' and would introduce
680 # added in `process_input`, as it is '' and would introduce
682 # an undesirable newline.
681 # an undesirable newline.
683 assert(ret[-1] == '')
682 assert(ret[-1] == '')
684 del ret[-1]
683 del ret[-1]
685
684
686 if out_data:
685 if out_data:
687 ret.extend(out_data)
686 ret.extend(out_data)
688
687
689 # save the image files
688 # save the image files
690 if image_file is not None:
689 if image_file is not None:
691 self.save_image(image_file)
690 self.save_image(image_file)
692
691
693 return ret, image_directive
692 return ret, image_directive
694
693
695 def ensure_pyplot(self):
694 def ensure_pyplot(self):
696 """
695 """
697 Ensures that pyplot has been imported into the embedded IPython shell.
696 Ensures that pyplot has been imported into the embedded IPython shell.
698
697
699 Also, makes sure to set the backend appropriately if not set already.
698 Also, makes sure to set the backend appropriately if not set already.
700
699
701 """
700 """
702 # We are here if the @figure pseudo decorator was used. Thus, it's
701 # We are here if the @figure pseudo decorator was used. Thus, it's
703 # possible that we could be here even if python_mplbackend were set to
702 # possible that we could be here even if python_mplbackend were set to
704 # `None`. That's also strange and perhaps worthy of raising an
703 # `None`. That's also strange and perhaps worthy of raising an
705 # exception, but for now, we just set the backend to 'agg'.
704 # exception, but for now, we just set the backend to 'agg'.
706
705
707 if not self._pyplot_imported:
706 if not self._pyplot_imported:
708 if 'matplotlib.backends' not in sys.modules:
707 if 'matplotlib.backends' not in sys.modules:
709 # Then ipython_matplotlib was set to None but there was a
708 # Then ipython_matplotlib was set to None but there was a
710 # call to the @figure decorator (and ipython_execlines did
709 # call to the @figure decorator (and ipython_execlines did
711 # not set a backend).
710 # not set a backend).
712 #raise Exception("No backend was set, but @figure was used!")
711 #raise Exception("No backend was set, but @figure was used!")
713 import matplotlib
712 import matplotlib
714 matplotlib.use('agg')
713 matplotlib.use('agg')
715
714
716 # Always import pyplot into embedded shell.
715 # Always import pyplot into embedded shell.
717 self.process_input_line('import matplotlib.pyplot as plt',
716 self.process_input_line('import matplotlib.pyplot as plt',
718 store_history=False)
717 store_history=False)
719 self._pyplot_imported = True
718 self._pyplot_imported = True
720
719
721 def process_pure_python(self, content):
720 def process_pure_python(self, content):
722 """
721 """
723 content is a list of strings. it is unedited directive content
722 content is a list of strings. it is unedited directive content
724
723
725 This runs it line by line in the InteractiveShell, prepends
724 This runs it line by line in the InteractiveShell, prepends
726 prompts as needed capturing stderr and stdout, then returns
725 prompts as needed capturing stderr and stdout, then returns
727 the content as a list as if it were ipython code
726 the content as a list as if it were ipython code
728 """
727 """
729 output = []
728 output = []
730 savefig = False # keep up with this to clear figure
729 savefig = False # keep up with this to clear figure
731 multiline = False # to handle line continuation
730 multiline = False # to handle line continuation
732 multiline_start = None
731 multiline_start = None
733 fmtin = self.promptin
732 fmtin = self.promptin
734
733
735 ct = 0
734 ct = 0
736
735
737 for lineno, line in enumerate(content):
736 for lineno, line in enumerate(content):
738
737
739 line_stripped = line.strip()
738 line_stripped = line.strip()
740 if not len(line):
739 if not len(line):
741 output.append(line)
740 output.append(line)
742 continue
741 continue
743
742
744 # handle decorators
743 # handle decorators
745 if line_stripped.startswith('@'):
744 if line_stripped.startswith('@'):
746 output.extend([line])
745 output.extend([line])
747 if 'savefig' in line:
746 if 'savefig' in line:
748 savefig = True # and need to clear figure
747 savefig = True # and need to clear figure
749 continue
748 continue
750
749
751 # handle comments
750 # handle comments
752 if line_stripped.startswith('#'):
751 if line_stripped.startswith('#'):
753 output.extend([line])
752 output.extend([line])
754 continue
753 continue
755
754
756 # deal with lines checking for multiline
755 # deal with lines checking for multiline
757 continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2))
756 continuation = u' %s:'% ''.join(['.']*(len(str(ct))+2))
758 if not multiline:
757 if not multiline:
759 modified = u"%s %s" % (fmtin % ct, line_stripped)
758 modified = u"%s %s" % (fmtin % ct, line_stripped)
760 output.append(modified)
759 output.append(modified)
761 ct += 1
760 ct += 1
762 try:
761 try:
763 ast.parse(line_stripped)
762 ast.parse(line_stripped)
764 output.append(u'')
763 output.append(u'')
765 except Exception: # on a multiline
764 except Exception: # on a multiline
766 multiline = True
765 multiline = True
767 multiline_start = lineno
766 multiline_start = lineno
768 else: # still on a multiline
767 else: # still on a multiline
769 modified = u'%s %s' % (continuation, line)
768 modified = u'%s %s' % (continuation, line)
770 output.append(modified)
769 output.append(modified)
771
770
772 # if the next line is indented, it should be part of multiline
771 # if the next line is indented, it should be part of multiline
773 if len(content) > lineno + 1:
772 if len(content) > lineno + 1:
774 nextline = content[lineno + 1]
773 nextline = content[lineno + 1]
775 if len(nextline) - len(nextline.lstrip()) > 3:
774 if len(nextline) - len(nextline.lstrip()) > 3:
776 continue
775 continue
777 try:
776 try:
778 mod = ast.parse(
777 mod = ast.parse(
779 '\n'.join(content[multiline_start:lineno+1]))
778 '\n'.join(content[multiline_start:lineno+1]))
780 if isinstance(mod.body[0], ast.FunctionDef):
779 if isinstance(mod.body[0], ast.FunctionDef):
781 # check to see if we have the whole function
780 # check to see if we have the whole function
782 for element in mod.body[0].body:
781 for element in mod.body[0].body:
783 if isinstance(element, ast.Return):
782 if isinstance(element, ast.Return):
784 multiline = False
783 multiline = False
785 else:
784 else:
786 output.append(u'')
785 output.append(u'')
787 multiline = False
786 multiline = False
788 except Exception:
787 except Exception:
789 pass
788 pass
790
789
791 if savefig: # clear figure if plotted
790 if savefig: # clear figure if plotted
792 self.ensure_pyplot()
791 self.ensure_pyplot()
793 self.process_input_line('plt.clf()', store_history=False)
792 self.process_input_line('plt.clf()', store_history=False)
794 self.clear_cout()
793 self.clear_cout()
795 savefig = False
794 savefig = False
796
795
797 return output
796 return output
798
797
799 def custom_doctest(self, decorator, input_lines, found, submitted):
798 def custom_doctest(self, decorator, input_lines, found, submitted):
800 """
799 """
801 Perform a specialized doctest.
800 Perform a specialized doctest.
802
801
803 """
802 """
804 from .custom_doctests import doctests
803 from .custom_doctests import doctests
805
804
806 args = decorator.split()
805 args = decorator.split()
807 doctest_type = args[1]
806 doctest_type = args[1]
808 if doctest_type in doctests:
807 if doctest_type in doctests:
809 doctests[doctest_type](self, args, input_lines, found, submitted)
808 doctests[doctest_type](self, args, input_lines, found, submitted)
810 else:
809 else:
811 e = "Invalid option to @doctest: {0}".format(doctest_type)
810 e = "Invalid option to @doctest: {0}".format(doctest_type)
812 raise Exception(e)
811 raise Exception(e)
813
812
814
813
815 class IPythonDirective(Directive):
814 class IPythonDirective(Directive):
816
815
817 has_content = True
816 has_content = True
818 required_arguments = 0
817 required_arguments = 0
819 optional_arguments = 4 # python, suppress, verbatim, doctest
818 optional_arguments = 4 # python, suppress, verbatim, doctest
820 final_argumuent_whitespace = True
819 final_argumuent_whitespace = True
821 option_spec = { 'python': directives.unchanged,
820 option_spec = { 'python': directives.unchanged,
822 'suppress' : directives.flag,
821 'suppress' : directives.flag,
823 'verbatim' : directives.flag,
822 'verbatim' : directives.flag,
824 'doctest' : directives.flag,
823 'doctest' : directives.flag,
825 'okexcept': directives.flag,
824 'okexcept': directives.flag,
826 'okwarning': directives.flag
825 'okwarning': directives.flag
827 }
826 }
828
827
829 shell = None
828 shell = None
830
829
831 seen_docs = set()
830 seen_docs = set()
832
831
833 def get_config_options(self):
832 def get_config_options(self):
834 # contains sphinx configuration variables
833 # contains sphinx configuration variables
835 config = self.state.document.settings.env.config
834 config = self.state.document.settings.env.config
836
835
837 # get config variables to set figure output directory
836 # get config variables to set figure output directory
838 savefig_dir = config.ipython_savefig_dir
837 savefig_dir = config.ipython_savefig_dir
839 source_dir = self.state.document.settings.env.srcdir
838 source_dir = self.state.document.settings.env.srcdir
840 savefig_dir = os.path.join(source_dir, savefig_dir)
839 savefig_dir = os.path.join(source_dir, savefig_dir)
841
840
842 # get regex and prompt stuff
841 # get regex and prompt stuff
843 rgxin = config.ipython_rgxin
842 rgxin = config.ipython_rgxin
844 rgxout = config.ipython_rgxout
843 rgxout = config.ipython_rgxout
845 promptin = config.ipython_promptin
844 promptin = config.ipython_promptin
846 promptout = config.ipython_promptout
845 promptout = config.ipython_promptout
847 mplbackend = config.ipython_mplbackend
846 mplbackend = config.ipython_mplbackend
848 exec_lines = config.ipython_execlines
847 exec_lines = config.ipython_execlines
849 hold_count = config.ipython_holdcount
848 hold_count = config.ipython_holdcount
850
849
851 return (savefig_dir, source_dir, rgxin, rgxout,
850 return (savefig_dir, source_dir, rgxin, rgxout,
852 promptin, promptout, mplbackend, exec_lines, hold_count)
851 promptin, promptout, mplbackend, exec_lines, hold_count)
853
852
854 def setup(self):
853 def setup(self):
855 # Get configuration values.
854 # Get configuration values.
856 (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout,
855 (savefig_dir, source_dir, rgxin, rgxout, promptin, promptout,
857 mplbackend, exec_lines, hold_count) = self.get_config_options()
856 mplbackend, exec_lines, hold_count) = self.get_config_options()
858
857
859 try:
858 try:
860 os.makedirs(savefig_dir)
859 os.makedirs(savefig_dir)
861 except OSError as e:
860 except OSError as e:
862 if e.errno != errno.EEXIST:
861 if e.errno != errno.EEXIST:
863 raise
862 raise
864
863
865 if self.shell is None:
864 if self.shell is None:
866 # We will be here many times. However, when the
865 # We will be here many times. However, when the
867 # EmbeddedSphinxShell is created, its interactive shell member
866 # EmbeddedSphinxShell is created, its interactive shell member
868 # is the same for each instance.
867 # is the same for each instance.
869
868
870 if mplbackend and 'matplotlib.backends' not in sys.modules:
869 if mplbackend and 'matplotlib.backends' not in sys.modules:
871 import matplotlib
870 import matplotlib
872 matplotlib.use(mplbackend)
871 matplotlib.use(mplbackend)
873
872
874 # Must be called after (potentially) importing matplotlib and
873 # Must be called after (potentially) importing matplotlib and
875 # setting its backend since exec_lines might import pylab.
874 # setting its backend since exec_lines might import pylab.
876 self.shell = EmbeddedSphinxShell(exec_lines)
875 self.shell = EmbeddedSphinxShell(exec_lines)
877
876
878 # Store IPython directive to enable better error messages
877 # Store IPython directive to enable better error messages
879 self.shell.directive = self
878 self.shell.directive = self
880
879
881 # reset the execution count if we haven't processed this doc
880 # reset the execution count if we haven't processed this doc
882 #NOTE: this may be borked if there are multiple seen_doc tmp files
881 #NOTE: this may be borked if there are multiple seen_doc tmp files
883 #check time stamp?
882 #check time stamp?
884 if not self.state.document.current_source in self.seen_docs:
883 if not self.state.document.current_source in self.seen_docs:
885 self.shell.IP.history_manager.reset()
884 self.shell.IP.history_manager.reset()
886 self.shell.IP.execution_count = 1
885 self.shell.IP.execution_count = 1
887 self.seen_docs.add(self.state.document.current_source)
886 self.seen_docs.add(self.state.document.current_source)
888
887
889 # and attach to shell so we don't have to pass them around
888 # and attach to shell so we don't have to pass them around
890 self.shell.rgxin = rgxin
889 self.shell.rgxin = rgxin
891 self.shell.rgxout = rgxout
890 self.shell.rgxout = rgxout
892 self.shell.promptin = promptin
891 self.shell.promptin = promptin
893 self.shell.promptout = promptout
892 self.shell.promptout = promptout
894 self.shell.savefig_dir = savefig_dir
893 self.shell.savefig_dir = savefig_dir
895 self.shell.source_dir = source_dir
894 self.shell.source_dir = source_dir
896 self.shell.hold_count = hold_count
895 self.shell.hold_count = hold_count
897
896
898 # setup bookmark for saving figures directory
897 # setup bookmark for saving figures directory
899 self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir,
898 self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir,
900 store_history=False)
899 store_history=False)
901 self.shell.clear_cout()
900 self.shell.clear_cout()
902
901
903 return rgxin, rgxout, promptin, promptout
902 return rgxin, rgxout, promptin, promptout
904
903
905 def teardown(self):
904 def teardown(self):
906 # delete last bookmark
905 # delete last bookmark
907 self.shell.process_input_line('bookmark -d ipy_savedir',
906 self.shell.process_input_line('bookmark -d ipy_savedir',
908 store_history=False)
907 store_history=False)
909 self.shell.clear_cout()
908 self.shell.clear_cout()
910
909
911 def run(self):
910 def run(self):
912 debug = False
911 debug = False
913
912
914 #TODO, any reason block_parser can't be a method of embeddable shell
913 #TODO, any reason block_parser can't be a method of embeddable shell
915 # then we wouldn't have to carry these around
914 # then we wouldn't have to carry these around
916 rgxin, rgxout, promptin, promptout = self.setup()
915 rgxin, rgxout, promptin, promptout = self.setup()
917
916
918 options = self.options
917 options = self.options
919 self.shell.is_suppress = 'suppress' in options
918 self.shell.is_suppress = 'suppress' in options
920 self.shell.is_doctest = 'doctest' in options
919 self.shell.is_doctest = 'doctest' in options
921 self.shell.is_verbatim = 'verbatim' in options
920 self.shell.is_verbatim = 'verbatim' in options
922 self.shell.is_okexcept = 'okexcept' in options
921 self.shell.is_okexcept = 'okexcept' in options
923 self.shell.is_okwarning = 'okwarning' in options
922 self.shell.is_okwarning = 'okwarning' in options
924
923
925 # handle pure python code
924 # handle pure python code
926 if 'python' in self.arguments:
925 if 'python' in self.arguments:
927 content = self.content
926 content = self.content
928 self.content = self.shell.process_pure_python(content)
927 self.content = self.shell.process_pure_python(content)
929
928
930 # parts consists of all text within the ipython-block.
929 # parts consists of all text within the ipython-block.
931 # Each part is an input/output block.
930 # Each part is an input/output block.
932 parts = '\n'.join(self.content).split('\n\n')
931 parts = '\n'.join(self.content).split('\n\n')
933
932
934 lines = ['.. code-block:: ipython', '']
933 lines = ['.. code-block:: ipython', '']
935 figures = []
934 figures = []
936
935
937 for part in parts:
936 for part in parts:
938 block = block_parser(part, rgxin, rgxout, promptin, promptout)
937 block = block_parser(part, rgxin, rgxout, promptin, promptout)
939 if len(block):
938 if len(block):
940 rows, figure = self.shell.process_block(block)
939 rows, figure = self.shell.process_block(block)
941 for row in rows:
940 for row in rows:
942 lines.extend([' {0}'.format(line)
941 lines.extend([' {0}'.format(line)
943 for line in row.split('\n')])
942 for line in row.split('\n')])
944
943
945 if figure is not None:
944 if figure is not None:
946 figures.append(figure)
945 figures.append(figure)
947
946
948 for figure in figures:
947 for figure in figures:
949 lines.append('')
948 lines.append('')
950 lines.extend(figure.split('\n'))
949 lines.extend(figure.split('\n'))
951 lines.append('')
950 lines.append('')
952
951
953 if len(lines) > 2:
952 if len(lines) > 2:
954 if debug:
953 if debug:
955 print('\n'.join(lines))
954 print('\n'.join(lines))
956 else:
955 else:
957 # This has to do with input, not output. But if we comment
956 # This has to do with input, not output. But if we comment
958 # these lines out, then no IPython code will appear in the
957 # these lines out, then no IPython code will appear in the
959 # final output.
958 # final output.
960 self.state_machine.insert_input(
959 self.state_machine.insert_input(
961 lines, self.state_machine.input_lines.source(0))
960 lines, self.state_machine.input_lines.source(0))
962
961
963 # cleanup
962 # cleanup
964 self.teardown()
963 self.teardown()
965
964
966 return []
965 return []
967
966
968 # Enable as a proper Sphinx directive
967 # Enable as a proper Sphinx directive
969 def setup(app):
968 def setup(app):
970 setup.app = app
969 setup.app = app
971
970
972 app.add_directive('ipython', IPythonDirective)
971 app.add_directive('ipython', IPythonDirective)
973 app.add_config_value('ipython_savefig_dir', 'savefig', 'env')
972 app.add_config_value('ipython_savefig_dir', 'savefig', 'env')
974 app.add_config_value('ipython_rgxin',
973 app.add_config_value('ipython_rgxin',
975 re.compile('In \[(\d+)\]:\s?(.*)\s*'), 'env')
974 re.compile('In \[(\d+)\]:\s?(.*)\s*'), 'env')
976 app.add_config_value('ipython_rgxout',
975 app.add_config_value('ipython_rgxout',
977 re.compile('Out\[(\d+)\]:\s?(.*)\s*'), 'env')
976 re.compile('Out\[(\d+)\]:\s?(.*)\s*'), 'env')
978 app.add_config_value('ipython_promptin', 'In [%d]:', 'env')
977 app.add_config_value('ipython_promptin', 'In [%d]:', 'env')
979 app.add_config_value('ipython_promptout', 'Out[%d]:', 'env')
978 app.add_config_value('ipython_promptout', 'Out[%d]:', 'env')
980
979
981 # We could just let matplotlib pick whatever is specified as the default
980 # We could just let matplotlib pick whatever is specified as the default
982 # backend in the matplotlibrc file, but this would cause issues if the
981 # backend in the matplotlibrc file, but this would cause issues if the
983 # backend didn't work in headless environments. For this reason, 'agg'
982 # backend didn't work in headless environments. For this reason, 'agg'
984 # is a good default backend choice.
983 # is a good default backend choice.
985 app.add_config_value('ipython_mplbackend', 'agg', 'env')
984 app.add_config_value('ipython_mplbackend', 'agg', 'env')
986
985
987 # If the user sets this config value to `None`, then EmbeddedSphinxShell's
986 # If the user sets this config value to `None`, then EmbeddedSphinxShell's
988 # __init__ method will treat it as [].
987 # __init__ method will treat it as [].
989 execlines = ['import numpy as np', 'import matplotlib.pyplot as plt']
988 execlines = ['import numpy as np', 'import matplotlib.pyplot as plt']
990 app.add_config_value('ipython_execlines', execlines, 'env')
989 app.add_config_value('ipython_execlines', execlines, 'env')
991
990
992 app.add_config_value('ipython_holdcount', True, 'env')
991 app.add_config_value('ipython_holdcount', True, 'env')
993
992
994 metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
993 metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
995 return metadata
994 return metadata
996
995
997 # Simple smoke test, needs to be converted to a proper automatic test.
996 # Simple smoke test, needs to be converted to a proper automatic test.
998 def test():
997 def test():
999
998
1000 examples = [
999 examples = [
1001 r"""
1000 r"""
1002 In [9]: pwd
1001 In [9]: pwd
1003 Out[9]: '/home/jdhunter/py4science/book'
1002 Out[9]: '/home/jdhunter/py4science/book'
1004
1003
1005 In [10]: cd bookdata/
1004 In [10]: cd bookdata/
1006 /home/jdhunter/py4science/book/bookdata
1005 /home/jdhunter/py4science/book/bookdata
1007
1006
1008 In [2]: from pylab import *
1007 In [2]: from pylab import *
1009
1008
1010 In [2]: ion()
1009 In [2]: ion()
1011
1010
1012 In [3]: im = imread('stinkbug.png')
1011 In [3]: im = imread('stinkbug.png')
1013
1012
1014 @savefig mystinkbug.png width=4in
1013 @savefig mystinkbug.png width=4in
1015 In [4]: imshow(im)
1014 In [4]: imshow(im)
1016 Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>
1015 Out[4]: <matplotlib.image.AxesImage object at 0x39ea850>
1017
1016
1018 """,
1017 """,
1019 r"""
1018 r"""
1020
1019
1021 In [1]: x = 'hello world'
1020 In [1]: x = 'hello world'
1022
1021
1023 # string methods can be
1022 # string methods can be
1024 # used to alter the string
1023 # used to alter the string
1025 @doctest
1024 @doctest
1026 In [2]: x.upper()
1025 In [2]: x.upper()
1027 Out[2]: 'HELLO WORLD'
1026 Out[2]: 'HELLO WORLD'
1028
1027
1029 @verbatim
1028 @verbatim
1030 In [3]: x.st<TAB>
1029 In [3]: x.st<TAB>
1031 x.startswith x.strip
1030 x.startswith x.strip
1032 """,
1031 """,
1033 r"""
1032 r"""
1034
1033
1035 In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
1034 In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\
1036 .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
1035 .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv'
1037
1036
1038 In [131]: print url.split('&')
1037 In [131]: print url.split('&')
1039 ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']
1038 ['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv']
1040
1039
1041 In [60]: import urllib
1040 In [60]: import urllib
1042
1041
1043 """,
1042 """,
1044 r"""\
1043 r"""\
1045
1044
1046 In [133]: import numpy.random
1045 In [133]: import numpy.random
1047
1046
1048 @suppress
1047 @suppress
1049 In [134]: numpy.random.seed(2358)
1048 In [134]: numpy.random.seed(2358)
1050
1049
1051 @doctest
1050 @doctest
1052 In [135]: numpy.random.rand(10,2)
1051 In [135]: numpy.random.rand(10,2)
1053 Out[135]:
1052 Out[135]:
1054 array([[ 0.64524308, 0.59943846],
1053 array([[ 0.64524308, 0.59943846],
1055 [ 0.47102322, 0.8715456 ],
1054 [ 0.47102322, 0.8715456 ],
1056 [ 0.29370834, 0.74776844],
1055 [ 0.29370834, 0.74776844],
1057 [ 0.99539577, 0.1313423 ],
1056 [ 0.99539577, 0.1313423 ],
1058 [ 0.16250302, 0.21103583],
1057 [ 0.16250302, 0.21103583],
1059 [ 0.81626524, 0.1312433 ],
1058 [ 0.81626524, 0.1312433 ],
1060 [ 0.67338089, 0.72302393],
1059 [ 0.67338089, 0.72302393],
1061 [ 0.7566368 , 0.07033696],
1060 [ 0.7566368 , 0.07033696],
1062 [ 0.22591016, 0.77731835],
1061 [ 0.22591016, 0.77731835],
1063 [ 0.0072729 , 0.34273127]])
1062 [ 0.0072729 , 0.34273127]])
1064
1063
1065 """,
1064 """,
1066
1065
1067 r"""
1066 r"""
1068 In [106]: print x
1067 In [106]: print x
1069 jdh
1068 jdh
1070
1069
1071 In [109]: for i in range(10):
1070 In [109]: for i in range(10):
1072 .....: print i
1071 .....: print i
1073 .....:
1072 .....:
1074 .....:
1073 .....:
1075 0
1074 0
1076 1
1075 1
1077 2
1076 2
1078 3
1077 3
1079 4
1078 4
1080 5
1079 5
1081 6
1080 6
1082 7
1081 7
1083 8
1082 8
1084 9
1083 9
1085 """,
1084 """,
1086
1085
1087 r"""
1086 r"""
1088
1087
1089 In [144]: from pylab import *
1088 In [144]: from pylab import *
1090
1089
1091 In [145]: ion()
1090 In [145]: ion()
1092
1091
1093 # use a semicolon to suppress the output
1092 # use a semicolon to suppress the output
1094 @savefig test_hist.png width=4in
1093 @savefig test_hist.png width=4in
1095 In [151]: hist(np.random.randn(10000), 100);
1094 In [151]: hist(np.random.randn(10000), 100);
1096
1095
1097
1096
1098 @savefig test_plot.png width=4in
1097 @savefig test_plot.png width=4in
1099 In [151]: plot(np.random.randn(10000), 'o');
1098 In [151]: plot(np.random.randn(10000), 'o');
1100 """,
1099 """,
1101
1100
1102 r"""
1101 r"""
1103 # use a semicolon to suppress the output
1102 # use a semicolon to suppress the output
1104 In [151]: plt.clf()
1103 In [151]: plt.clf()
1105
1104
1106 @savefig plot_simple.png width=4in
1105 @savefig plot_simple.png width=4in
1107 In [151]: plot([1,2,3])
1106 In [151]: plot([1,2,3])
1108
1107
1109 @savefig hist_simple.png width=4in
1108 @savefig hist_simple.png width=4in
1110 In [151]: hist(np.random.randn(10000), 100);
1109 In [151]: hist(np.random.randn(10000), 100);
1111
1110
1112 """,
1111 """,
1113 r"""
1112 r"""
1114 # update the current fig
1113 # update the current fig
1115 In [151]: ylabel('number')
1114 In [151]: ylabel('number')
1116
1115
1117 In [152]: title('normal distribution')
1116 In [152]: title('normal distribution')
1118
1117
1119
1118
1120 @savefig hist_with_text.png
1119 @savefig hist_with_text.png
1121 In [153]: grid(True)
1120 In [153]: grid(True)
1122
1121
1123 @doctest float
1122 @doctest float
1124 In [154]: 0.1 + 0.2
1123 In [154]: 0.1 + 0.2
1125 Out[154]: 0.3
1124 Out[154]: 0.3
1126
1125
1127 @doctest float
1126 @doctest float
1128 In [155]: np.arange(16).reshape(4,4)
1127 In [155]: np.arange(16).reshape(4,4)
1129 Out[155]:
1128 Out[155]:
1130 array([[ 0, 1, 2, 3],
1129 array([[ 0, 1, 2, 3],
1131 [ 4, 5, 6, 7],
1130 [ 4, 5, 6, 7],
1132 [ 8, 9, 10, 11],
1131 [ 8, 9, 10, 11],
1133 [12, 13, 14, 15]])
1132 [12, 13, 14, 15]])
1134
1133
1135 In [1]: x = np.arange(16, dtype=float).reshape(4,4)
1134 In [1]: x = np.arange(16, dtype=float).reshape(4,4)
1136
1135
1137 In [2]: x[0,0] = np.inf
1136 In [2]: x[0,0] = np.inf
1138
1137
1139 In [3]: x[0,1] = np.nan
1138 In [3]: x[0,1] = np.nan
1140
1139
1141 @doctest float
1140 @doctest float
1142 In [4]: x
1141 In [4]: x
1143 Out[4]:
1142 Out[4]:
1144 array([[ inf, nan, 2., 3.],
1143 array([[ inf, nan, 2., 3.],
1145 [ 4., 5., 6., 7.],
1144 [ 4., 5., 6., 7.],
1146 [ 8., 9., 10., 11.],
1145 [ 8., 9., 10., 11.],
1147 [ 12., 13., 14., 15.]])
1146 [ 12., 13., 14., 15.]])
1148
1147
1149
1148
1150 """,
1149 """,
1151 ]
1150 ]
1152 # skip local-file depending first example:
1151 # skip local-file depending first example:
1153 examples = examples[1:]
1152 examples = examples[1:]
1154
1153
1155 #ipython_directive.DEBUG = True # dbg
1154 #ipython_directive.DEBUG = True # dbg
1156 #options = dict(suppress=True) # dbg
1155 #options = dict(suppress=True) # dbg
1157 options = {}
1156 options = {}
1158 for example in examples:
1157 for example in examples:
1159 content = example.split('\n')
1158 content = example.split('\n')
1160 IPythonDirective('debug', arguments=None, options=options,
1159 IPythonDirective('debug', arguments=None, options=options,
1161 content=content, lineno=0,
1160 content=content, lineno=0,
1162 content_offset=None, block_text=None,
1161 content_offset=None, block_text=None,
1163 state=None, state_machine=None,
1162 state=None, state_machine=None,
1164 )
1163 )
1165
1164
1166 # Run test suite as a script
1165 # Run test suite as a script
1167 if __name__=='__main__':
1166 if __name__=='__main__':
1168 if not os.path.isdir('_static'):
1167 if not os.path.isdir('_static'):
1169 os.mkdir('_static')
1168 os.mkdir('_static')
1170 test()
1169 test()
1171 print('All OK? Check figures in _static/')
1170 print('All OK? Check figures in _static/')
@@ -1,541 +1,540 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2
2
3 import os
3 import os
4 import sys
4 import sys
5 import warnings
5 import warnings
6 from warnings import warn
6 from warnings import warn
7
7
8 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
8 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
9 from IPython.utils import io
9 from IPython.utils import io
10 from IPython.utils.py3compat import input
10 from IPython.utils.py3compat import input
11 from IPython.utils.terminal import toggle_set_term_title, set_term_title
11 from IPython.utils.terminal import toggle_set_term_title, set_term_title
12 from IPython.utils.process import abbrev_cwd
12 from IPython.utils.process import abbrev_cwd
13 from traitlets import (
13 from traitlets import (
14 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
14 Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union,
15 Any,
15 Any,
16 )
16 )
17
17
18 from prompt_toolkit.document import Document
18 from prompt_toolkit.document import Document
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
19 from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
20 from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
21 from prompt_toolkit.history import InMemoryHistory
21 from prompt_toolkit.history import InMemoryHistory
22 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
22 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
23 from prompt_toolkit.interface import CommandLineInterface
23 from prompt_toolkit.interface import CommandLineInterface
24 from prompt_toolkit.key_binding.manager import KeyBindingManager
24 from prompt_toolkit.key_binding.manager import KeyBindingManager
25 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
25 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
26 from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
26 from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
27
27
28 from pygments.styles import get_style_by_name
28 from pygments.styles import get_style_by_name
29 from pygments.style import Style
29 from pygments.style import Style
30 from pygments.token import Token
30 from pygments.token import Token
31
31
32 from .debugger import TerminalPdb, Pdb
32 from .debugger import TerminalPdb, Pdb
33 from .magics import TerminalMagics
33 from .magics import TerminalMagics
34 from .pt_inputhooks import get_inputhook_name_and_func
34 from .pt_inputhooks import get_inputhook_name_and_func
35 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
35 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
36 from .ptutils import IPythonPTCompleter, IPythonPTLexer
36 from .ptutils import IPythonPTCompleter, IPythonPTLexer
37 from .shortcuts import register_ipython_shortcuts
37 from .shortcuts import register_ipython_shortcuts
38
38
39 DISPLAY_BANNER_DEPRECATED = object()
39 DISPLAY_BANNER_DEPRECATED = object()
40
40
41
41
42 class _NoStyle(Style): pass
42 class _NoStyle(Style): pass
43
43
44
44
45
45
46 _style_overrides_light_bg = {
46 _style_overrides_light_bg = {
47 Token.Prompt: '#0000ff',
47 Token.Prompt: '#0000ff',
48 Token.PromptNum: '#0000ee bold',
48 Token.PromptNum: '#0000ee bold',
49 Token.OutPrompt: '#cc0000',
49 Token.OutPrompt: '#cc0000',
50 Token.OutPromptNum: '#bb0000 bold',
50 Token.OutPromptNum: '#bb0000 bold',
51 }
51 }
52
52
53 _style_overrides_linux = {
53 _style_overrides_linux = {
54 Token.Prompt: '#00cc00',
54 Token.Prompt: '#00cc00',
55 Token.PromptNum: '#00bb00 bold',
55 Token.PromptNum: '#00bb00 bold',
56 Token.OutPrompt: '#cc0000',
56 Token.OutPrompt: '#cc0000',
57 Token.OutPromptNum: '#bb0000 bold',
57 Token.OutPromptNum: '#bb0000 bold',
58 }
58 }
59
59
60 def get_default_editor():
60 def get_default_editor():
61 try:
61 try:
62 return os.environ['EDITOR']
62 return os.environ['EDITOR']
63 except KeyError:
63 except KeyError:
64 pass
64 pass
65 except UnicodeError:
65 except UnicodeError:
66 warn("$EDITOR environment variable is not pure ASCII. Using platform "
66 warn("$EDITOR environment variable is not pure ASCII. Using platform "
67 "default editor.")
67 "default editor.")
68
68
69 if os.name == 'posix':
69 if os.name == 'posix':
70 return 'vi' # the only one guaranteed to be there!
70 return 'vi' # the only one guaranteed to be there!
71 else:
71 else:
72 return 'notepad' # same in Windows!
72 return 'notepad' # same in Windows!
73
73
74 # conservatively check for tty
74 # conservatively check for tty
75 # overridden streams can result in things like:
75 # overridden streams can result in things like:
76 # - sys.stdin = None
76 # - sys.stdin = None
77 # - no isatty method
77 # - no isatty method
78 for _name in ('stdin', 'stdout', 'stderr'):
78 for _name in ('stdin', 'stdout', 'stderr'):
79 _stream = getattr(sys, _name)
79 _stream = getattr(sys, _name)
80 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
80 if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
81 _is_tty = False
81 _is_tty = False
82 break
82 break
83 else:
83 else:
84 _is_tty = True
84 _is_tty = True
85
85
86
86
87 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
87 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
88
88
89 class TerminalInteractiveShell(InteractiveShell):
89 class TerminalInteractiveShell(InteractiveShell):
90 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
90 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
91 'to reserve for the completion menu'
91 'to reserve for the completion menu'
92 ).tag(config=True)
92 ).tag(config=True)
93
93
94 def _space_for_menu_changed(self, old, new):
94 def _space_for_menu_changed(self, old, new):
95 self._update_layout()
95 self._update_layout()
96
96
97 pt_cli = None
97 pt_cli = None
98 debugger_history = None
98 debugger_history = None
99 _pt_app = None
99 _pt_app = None
100
100
101 simple_prompt = Bool(_use_simple_prompt,
101 simple_prompt = Bool(_use_simple_prompt,
102 help="""Use `raw_input` for the REPL, without completion and prompt colors.
102 help="""Use `raw_input` for the REPL, without completion and prompt colors.
103
103
104 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
104 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
105 IPython own testing machinery, and emacs inferior-shell integration through elpy.
105 IPython own testing machinery, and emacs inferior-shell integration through elpy.
106
106
107 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
107 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
108 environment variable is set, or the current terminal is not a tty."""
108 environment variable is set, or the current terminal is not a tty."""
109 ).tag(config=True)
109 ).tag(config=True)
110
110
111 @property
111 @property
112 def debugger_cls(self):
112 def debugger_cls(self):
113 return Pdb if self.simple_prompt else TerminalPdb
113 return Pdb if self.simple_prompt else TerminalPdb
114
114
115 confirm_exit = Bool(True,
115 confirm_exit = Bool(True,
116 help="""
116 help="""
117 Set to confirm when you try to exit IPython with an EOF (Control-D
117 Set to confirm when you try to exit IPython with an EOF (Control-D
118 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
118 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
119 you can force a direct exit without any confirmation.""",
119 you can force a direct exit without any confirmation.""",
120 ).tag(config=True)
120 ).tag(config=True)
121
121
122 editing_mode = Unicode('emacs',
122 editing_mode = Unicode('emacs',
123 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
123 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
124 ).tag(config=True)
124 ).tag(config=True)
125
125
126 mouse_support = Bool(False,
126 mouse_support = Bool(False,
127 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
127 help="Enable mouse support in the prompt\n(Note: prevents selecting text with the mouse)"
128 ).tag(config=True)
128 ).tag(config=True)
129
129
130 # We don't load the list of styles for the help string, because loading
130 # We don't load the list of styles for the help string, because loading
131 # Pygments plugins takes time and can cause unexpected errors.
131 # Pygments plugins takes time and can cause unexpected errors.
132 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
132 highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
133 help="""The name or class of a Pygments style to use for syntax
133 help="""The name or class of a Pygments style to use for syntax
134 highlighting. To see available styles, run `pygmentize -L styles`."""
134 highlighting. To see available styles, run `pygmentize -L styles`."""
135 ).tag(config=True)
135 ).tag(config=True)
136
136
137
137
138 @observe('highlighting_style')
138 @observe('highlighting_style')
139 @observe('colors')
139 @observe('colors')
140 def _highlighting_style_changed(self, change):
140 def _highlighting_style_changed(self, change):
141 self.refresh_style()
141 self.refresh_style()
142
142
143 def refresh_style(self):
143 def refresh_style(self):
144 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
144 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
145
145
146
146
147 highlighting_style_overrides = Dict(
147 highlighting_style_overrides = Dict(
148 help="Override highlighting format for specific tokens"
148 help="Override highlighting format for specific tokens"
149 ).tag(config=True)
149 ).tag(config=True)
150
150
151 true_color = Bool(False,
151 true_color = Bool(False,
152 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
152 help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
153 "If your terminal supports true color, the following command "
153 "If your terminal supports true color, the following command "
154 "should print 'TRUECOLOR' in orange: "
154 "should print 'TRUECOLOR' in orange: "
155 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
155 "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
156 ).tag(config=True)
156 ).tag(config=True)
157
157
158 editor = Unicode(get_default_editor(),
158 editor = Unicode(get_default_editor(),
159 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
159 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
160 ).tag(config=True)
160 ).tag(config=True)
161
161
162 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
162 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
163
163
164 prompts = Instance(Prompts)
164 prompts = Instance(Prompts)
165
165
166 @default('prompts')
166 @default('prompts')
167 def _prompts_default(self):
167 def _prompts_default(self):
168 return self.prompts_class(self)
168 return self.prompts_class(self)
169
169
170 @observe('prompts')
170 @observe('prompts')
171 def _(self, change):
171 def _(self, change):
172 self._update_layout()
172 self._update_layout()
173
173
174 @default('displayhook_class')
174 @default('displayhook_class')
175 def _displayhook_class_default(self):
175 def _displayhook_class_default(self):
176 return RichPromptDisplayHook
176 return RichPromptDisplayHook
177
177
178 term_title = Bool(True,
178 term_title = Bool(True,
179 help="Automatically set the terminal title"
179 help="Automatically set the terminal title"
180 ).tag(config=True)
180 ).tag(config=True)
181
181
182 term_title_format = Unicode("IPython: {cwd}",
182 term_title_format = Unicode("IPython: {cwd}",
183 help="Customize the terminal title format. This is a python format string. " +
183 help="Customize the terminal title format. This is a python format string. " +
184 "Available substitutions are: {cwd}."
184 "Available substitutions are: {cwd}."
185 ).tag(config=True)
185 ).tag(config=True)
186
186
187 display_completions = Enum(('column', 'multicolumn','readlinelike'),
187 display_completions = Enum(('column', 'multicolumn','readlinelike'),
188 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
188 help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
189 "'readlinelike'. These options are for `prompt_toolkit`, see "
189 "'readlinelike'. These options are for `prompt_toolkit`, see "
190 "`prompt_toolkit` documentation for more information."
190 "`prompt_toolkit` documentation for more information."
191 ),
191 ),
192 default_value='multicolumn').tag(config=True)
192 default_value='multicolumn').tag(config=True)
193
193
194 highlight_matching_brackets = Bool(True,
194 highlight_matching_brackets = Bool(True,
195 help="Highlight matching brackets.",
195 help="Highlight matching brackets.",
196 ).tag(config=True)
196 ).tag(config=True)
197
197
198 extra_open_editor_shortcuts = Bool(False,
198 extra_open_editor_shortcuts = Bool(False,
199 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
199 help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
200 "This is in addition to the F2 binding, which is always enabled."
200 "This is in addition to the F2 binding, which is always enabled."
201 ).tag(config=True)
201 ).tag(config=True)
202
202
203 handle_return = Any(None,
203 handle_return = Any(None,
204 help="Provide an alternative handler to be called when the user presses "
204 help="Provide an alternative handler to be called when the user presses "
205 "Return. This is an advanced option intended for debugging, which "
205 "Return. This is an advanced option intended for debugging, which "
206 "may be changed or removed in later releases."
206 "may be changed or removed in later releases."
207 ).tag(config=True)
207 ).tag(config=True)
208
208
209 enable_history_search = Bool(True,
209 enable_history_search = Bool(True,
210 help="Allows to enable/disable the prompt toolkit history search"
210 help="Allows to enable/disable the prompt toolkit history search"
211 ).tag(config=True)
211 ).tag(config=True)
212
212
213 @observe('term_title')
213 @observe('term_title')
214 def init_term_title(self, change=None):
214 def init_term_title(self, change=None):
215 # Enable or disable the terminal title.
215 # Enable or disable the terminal title.
216 if self.term_title:
216 if self.term_title:
217 toggle_set_term_title(True)
217 toggle_set_term_title(True)
218 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
218 set_term_title(self.term_title_format.format(cwd=abbrev_cwd()))
219 else:
219 else:
220 toggle_set_term_title(False)
220 toggle_set_term_title(False)
221
221
222 def init_display_formatter(self):
222 def init_display_formatter(self):
223 super(TerminalInteractiveShell, self).init_display_formatter()
223 super(TerminalInteractiveShell, self).init_display_formatter()
224 # terminal only supports plain text
224 # terminal only supports plain text
225 self.display_formatter.active_types = ['text/plain']
225 self.display_formatter.active_types = ['text/plain']
226 # disable `_ipython_display_`
226 # disable `_ipython_display_`
227 self.display_formatter.ipython_display_formatter.enabled = False
227 self.display_formatter.ipython_display_formatter.enabled = False
228
228
229 def init_prompt_toolkit_cli(self):
229 def init_prompt_toolkit_cli(self):
230 if self.simple_prompt:
230 if self.simple_prompt:
231 # Fall back to plain non-interactive output for tests.
231 # Fall back to plain non-interactive output for tests.
232 # This is very limited.
232 # This is very limited.
233 def prompt():
233 def prompt():
234 itm = self.input_transformer_manager
235 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
234 prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
236 lines = [input(prompt_text)]
235 lines = [input(prompt_text)]
237 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
236 prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
238 while itm.check_complete('\n'.join(lines))[0] == 'incomplete':
237 while self.check_complete('\n'.join(lines))[0] == 'incomplete':
239 lines.append( input(prompt_continuation) )
238 lines.append( input(prompt_continuation) )
240 return '\n'.join(lines)
239 return '\n'.join(lines)
241 self.prompt_for_code = prompt
240 self.prompt_for_code = prompt
242 return
241 return
243
242
244 # Set up keyboard shortcuts
243 # Set up keyboard shortcuts
245 kbmanager = KeyBindingManager.for_prompt(
244 kbmanager = KeyBindingManager.for_prompt(
246 enable_open_in_editor=self.extra_open_editor_shortcuts,
245 enable_open_in_editor=self.extra_open_editor_shortcuts,
247 )
246 )
248 register_ipython_shortcuts(kbmanager.registry, self)
247 register_ipython_shortcuts(kbmanager.registry, self)
249
248
250 # Pre-populate history from IPython's history database
249 # Pre-populate history from IPython's history database
251 history = InMemoryHistory()
250 history = InMemoryHistory()
252 last_cell = u""
251 last_cell = u""
253 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
252 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
254 include_latest=True):
253 include_latest=True):
255 # Ignore blank lines and consecutive duplicates
254 # Ignore blank lines and consecutive duplicates
256 cell = cell.rstrip()
255 cell = cell.rstrip()
257 if cell and (cell != last_cell):
256 if cell and (cell != last_cell):
258 history.append(cell)
257 history.append(cell)
259 last_cell = cell
258 last_cell = cell
260
259
261 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
260 self._style = self._make_style_from_name_or_cls(self.highlighting_style)
262 self.style = DynamicStyle(lambda: self._style)
261 self.style = DynamicStyle(lambda: self._style)
263
262
264 editing_mode = getattr(EditingMode, self.editing_mode.upper())
263 editing_mode = getattr(EditingMode, self.editing_mode.upper())
265
264
266 def patch_stdout(**kwargs):
265 def patch_stdout(**kwargs):
267 return self.pt_cli.patch_stdout_context(**kwargs)
266 return self.pt_cli.patch_stdout_context(**kwargs)
268
267
269 self._pt_app = create_prompt_application(
268 self._pt_app = create_prompt_application(
270 editing_mode=editing_mode,
269 editing_mode=editing_mode,
271 key_bindings_registry=kbmanager.registry,
270 key_bindings_registry=kbmanager.registry,
272 history=history,
271 history=history,
273 completer=IPythonPTCompleter(shell=self,
272 completer=IPythonPTCompleter(shell=self,
274 patch_stdout=patch_stdout),
273 patch_stdout=patch_stdout),
275 enable_history_search=self.enable_history_search,
274 enable_history_search=self.enable_history_search,
276 style=self.style,
275 style=self.style,
277 mouse_support=self.mouse_support,
276 mouse_support=self.mouse_support,
278 **self._layout_options()
277 **self._layout_options()
279 )
278 )
280 self._eventloop = create_eventloop(self.inputhook)
279 self._eventloop = create_eventloop(self.inputhook)
281 self.pt_cli = CommandLineInterface(
280 self.pt_cli = CommandLineInterface(
282 self._pt_app, eventloop=self._eventloop,
281 self._pt_app, eventloop=self._eventloop,
283 output=create_output(true_color=self.true_color))
282 output=create_output(true_color=self.true_color))
284
283
285 def _make_style_from_name_or_cls(self, name_or_cls):
284 def _make_style_from_name_or_cls(self, name_or_cls):
286 """
285 """
287 Small wrapper that make an IPython compatible style from a style name
286 Small wrapper that make an IPython compatible style from a style name
288
287
289 We need that to add style for prompt ... etc.
288 We need that to add style for prompt ... etc.
290 """
289 """
291 style_overrides = {}
290 style_overrides = {}
292 if name_or_cls == 'legacy':
291 if name_or_cls == 'legacy':
293 legacy = self.colors.lower()
292 legacy = self.colors.lower()
294 if legacy == 'linux':
293 if legacy == 'linux':
295 style_cls = get_style_by_name('monokai')
294 style_cls = get_style_by_name('monokai')
296 style_overrides = _style_overrides_linux
295 style_overrides = _style_overrides_linux
297 elif legacy == 'lightbg':
296 elif legacy == 'lightbg':
298 style_overrides = _style_overrides_light_bg
297 style_overrides = _style_overrides_light_bg
299 style_cls = get_style_by_name('pastie')
298 style_cls = get_style_by_name('pastie')
300 elif legacy == 'neutral':
299 elif legacy == 'neutral':
301 # The default theme needs to be visible on both a dark background
300 # The default theme needs to be visible on both a dark background
302 # and a light background, because we can't tell what the terminal
301 # and a light background, because we can't tell what the terminal
303 # looks like. These tweaks to the default theme help with that.
302 # looks like. These tweaks to the default theme help with that.
304 style_cls = get_style_by_name('default')
303 style_cls = get_style_by_name('default')
305 style_overrides.update({
304 style_overrides.update({
306 Token.Number: '#007700',
305 Token.Number: '#007700',
307 Token.Operator: 'noinherit',
306 Token.Operator: 'noinherit',
308 Token.String: '#BB6622',
307 Token.String: '#BB6622',
309 Token.Name.Function: '#2080D0',
308 Token.Name.Function: '#2080D0',
310 Token.Name.Class: 'bold #2080D0',
309 Token.Name.Class: 'bold #2080D0',
311 Token.Name.Namespace: 'bold #2080D0',
310 Token.Name.Namespace: 'bold #2080D0',
312 Token.Prompt: '#009900',
311 Token.Prompt: '#009900',
313 Token.PromptNum: '#00ff00 bold',
312 Token.PromptNum: '#00ff00 bold',
314 Token.OutPrompt: '#990000',
313 Token.OutPrompt: '#990000',
315 Token.OutPromptNum: '#ff0000 bold',
314 Token.OutPromptNum: '#ff0000 bold',
316 })
315 })
317
316
318 # Hack: Due to limited color support on the Windows console
317 # Hack: Due to limited color support on the Windows console
319 # the prompt colors will be wrong without this
318 # the prompt colors will be wrong without this
320 if os.name == 'nt':
319 if os.name == 'nt':
321 style_overrides.update({
320 style_overrides.update({
322 Token.Prompt: '#ansidarkgreen',
321 Token.Prompt: '#ansidarkgreen',
323 Token.PromptNum: '#ansigreen bold',
322 Token.PromptNum: '#ansigreen bold',
324 Token.OutPrompt: '#ansidarkred',
323 Token.OutPrompt: '#ansidarkred',
325 Token.OutPromptNum: '#ansired bold',
324 Token.OutPromptNum: '#ansired bold',
326 })
325 })
327 elif legacy =='nocolor':
326 elif legacy =='nocolor':
328 style_cls=_NoStyle
327 style_cls=_NoStyle
329 style_overrides = {}
328 style_overrides = {}
330 else :
329 else :
331 raise ValueError('Got unknown colors: ', legacy)
330 raise ValueError('Got unknown colors: ', legacy)
332 else :
331 else :
333 if isinstance(name_or_cls, str):
332 if isinstance(name_or_cls, str):
334 style_cls = get_style_by_name(name_or_cls)
333 style_cls = get_style_by_name(name_or_cls)
335 else:
334 else:
336 style_cls = name_or_cls
335 style_cls = name_or_cls
337 style_overrides = {
336 style_overrides = {
338 Token.Prompt: '#009900',
337 Token.Prompt: '#009900',
339 Token.PromptNum: '#00ff00 bold',
338 Token.PromptNum: '#00ff00 bold',
340 Token.OutPrompt: '#990000',
339 Token.OutPrompt: '#990000',
341 Token.OutPromptNum: '#ff0000 bold',
340 Token.OutPromptNum: '#ff0000 bold',
342 }
341 }
343 style_overrides.update(self.highlighting_style_overrides)
342 style_overrides.update(self.highlighting_style_overrides)
344 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
343 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
345 style_dict=style_overrides)
344 style_dict=style_overrides)
346
345
347 return style
346 return style
348
347
349 def _layout_options(self):
348 def _layout_options(self):
350 """
349 """
351 Return the current layout option for the current Terminal InteractiveShell
350 Return the current layout option for the current Terminal InteractiveShell
352 """
351 """
353 return {
352 return {
354 'lexer':IPythonPTLexer(),
353 'lexer':IPythonPTLexer(),
355 'reserve_space_for_menu':self.space_for_menu,
354 'reserve_space_for_menu':self.space_for_menu,
356 'get_prompt_tokens':self.prompts.in_prompt_tokens,
355 'get_prompt_tokens':self.prompts.in_prompt_tokens,
357 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
356 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
358 'multiline':True,
357 'multiline':True,
359 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
358 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
360
359
361 # Highlight matching brackets, but only when this setting is
360 # Highlight matching brackets, but only when this setting is
362 # enabled, and only when the DEFAULT_BUFFER has the focus.
361 # enabled, and only when the DEFAULT_BUFFER has the focus.
363 'extra_input_processors': [ConditionalProcessor(
362 'extra_input_processors': [ConditionalProcessor(
364 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
363 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
365 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
364 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
366 Condition(lambda cli: self.highlight_matching_brackets))],
365 Condition(lambda cli: self.highlight_matching_brackets))],
367 }
366 }
368
367
369 def _update_layout(self):
368 def _update_layout(self):
370 """
369 """
371 Ask for a re computation of the application layout, if for example ,
370 Ask for a re computation of the application layout, if for example ,
372 some configuration options have changed.
371 some configuration options have changed.
373 """
372 """
374 if self._pt_app:
373 if self._pt_app:
375 self._pt_app.layout = create_prompt_layout(**self._layout_options())
374 self._pt_app.layout = create_prompt_layout(**self._layout_options())
376
375
377 def prompt_for_code(self):
376 def prompt_for_code(self):
378 with self.pt_cli.patch_stdout_context(raw=True):
377 with self.pt_cli.patch_stdout_context(raw=True):
379 document = self.pt_cli.run(
378 document = self.pt_cli.run(
380 pre_run=self.pre_prompt, reset_current_buffer=True)
379 pre_run=self.pre_prompt, reset_current_buffer=True)
381 return document.text
380 return document.text
382
381
383 def enable_win_unicode_console(self):
382 def enable_win_unicode_console(self):
384 if sys.version_info >= (3, 6):
383 if sys.version_info >= (3, 6):
385 # Since PEP 528, Python uses the unicode APIs for the Windows
384 # Since PEP 528, Python uses the unicode APIs for the Windows
386 # console by default, so WUC shouldn't be needed.
385 # console by default, so WUC shouldn't be needed.
387 return
386 return
388
387
389 import win_unicode_console
388 import win_unicode_console
390 win_unicode_console.enable()
389 win_unicode_console.enable()
391
390
392 def init_io(self):
391 def init_io(self):
393 if sys.platform not in {'win32', 'cli'}:
392 if sys.platform not in {'win32', 'cli'}:
394 return
393 return
395
394
396 self.enable_win_unicode_console()
395 self.enable_win_unicode_console()
397
396
398 import colorama
397 import colorama
399 colorama.init()
398 colorama.init()
400
399
401 # For some reason we make these wrappers around stdout/stderr.
400 # For some reason we make these wrappers around stdout/stderr.
402 # For now, we need to reset them so all output gets coloured.
401 # For now, we need to reset them so all output gets coloured.
403 # https://github.com/ipython/ipython/issues/8669
402 # https://github.com/ipython/ipython/issues/8669
404 # io.std* are deprecated, but don't show our own deprecation warnings
403 # io.std* are deprecated, but don't show our own deprecation warnings
405 # during initialization of the deprecated API.
404 # during initialization of the deprecated API.
406 with warnings.catch_warnings():
405 with warnings.catch_warnings():
407 warnings.simplefilter('ignore', DeprecationWarning)
406 warnings.simplefilter('ignore', DeprecationWarning)
408 io.stdout = io.IOStream(sys.stdout)
407 io.stdout = io.IOStream(sys.stdout)
409 io.stderr = io.IOStream(sys.stderr)
408 io.stderr = io.IOStream(sys.stderr)
410
409
411 def init_magics(self):
410 def init_magics(self):
412 super(TerminalInteractiveShell, self).init_magics()
411 super(TerminalInteractiveShell, self).init_magics()
413 self.register_magics(TerminalMagics)
412 self.register_magics(TerminalMagics)
414
413
415 def init_alias(self):
414 def init_alias(self):
416 # The parent class defines aliases that can be safely used with any
415 # The parent class defines aliases that can be safely used with any
417 # frontend.
416 # frontend.
418 super(TerminalInteractiveShell, self).init_alias()
417 super(TerminalInteractiveShell, self).init_alias()
419
418
420 # Now define aliases that only make sense on the terminal, because they
419 # Now define aliases that only make sense on the terminal, because they
421 # need direct access to the console in a way that we can't emulate in
420 # need direct access to the console in a way that we can't emulate in
422 # GUI or web frontend
421 # GUI or web frontend
423 if os.name == 'posix':
422 if os.name == 'posix':
424 for cmd in ['clear', 'more', 'less', 'man']:
423 for cmd in ['clear', 'more', 'less', 'man']:
425 self.alias_manager.soft_define_alias(cmd, cmd)
424 self.alias_manager.soft_define_alias(cmd, cmd)
426
425
427
426
428 def __init__(self, *args, **kwargs):
427 def __init__(self, *args, **kwargs):
429 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
428 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
430 self.init_prompt_toolkit_cli()
429 self.init_prompt_toolkit_cli()
431 self.init_term_title()
430 self.init_term_title()
432 self.keep_running = True
431 self.keep_running = True
433
432
434 self.debugger_history = InMemoryHistory()
433 self.debugger_history = InMemoryHistory()
435
434
436 def ask_exit(self):
435 def ask_exit(self):
437 self.keep_running = False
436 self.keep_running = False
438
437
439 rl_next_input = None
438 rl_next_input = None
440
439
441 def pre_prompt(self):
440 def pre_prompt(self):
442 if self.rl_next_input:
441 if self.rl_next_input:
443 # We can't set the buffer here, because it will be reset just after
442 # We can't set the buffer here, because it will be reset just after
444 # this. Adding a callable to pre_run_callables does what we need
443 # this. Adding a callable to pre_run_callables does what we need
445 # after the buffer is reset.
444 # after the buffer is reset.
446 s = self.rl_next_input
445 s = self.rl_next_input
447 def set_doc():
446 def set_doc():
448 self.pt_cli.application.buffer.document = Document(s)
447 self.pt_cli.application.buffer.document = Document(s)
449 if hasattr(self.pt_cli, 'pre_run_callables'):
448 if hasattr(self.pt_cli, 'pre_run_callables'):
450 self.pt_cli.pre_run_callables.append(set_doc)
449 self.pt_cli.pre_run_callables.append(set_doc)
451 else:
450 else:
452 # Older version of prompt_toolkit; it's OK to set the document
451 # Older version of prompt_toolkit; it's OK to set the document
453 # directly here.
452 # directly here.
454 set_doc()
453 set_doc()
455 self.rl_next_input = None
454 self.rl_next_input = None
456
455
457 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
456 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
458
457
459 if display_banner is not DISPLAY_BANNER_DEPRECATED:
458 if display_banner is not DISPLAY_BANNER_DEPRECATED:
460 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
459 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
461
460
462 self.keep_running = True
461 self.keep_running = True
463 while self.keep_running:
462 while self.keep_running:
464 print(self.separate_in, end='')
463 print(self.separate_in, end='')
465
464
466 try:
465 try:
467 code = self.prompt_for_code()
466 code = self.prompt_for_code()
468 except EOFError:
467 except EOFError:
469 if (not self.confirm_exit) \
468 if (not self.confirm_exit) \
470 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
469 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
471 self.ask_exit()
470 self.ask_exit()
472
471
473 else:
472 else:
474 if code:
473 if code:
475 self.run_cell(code, store_history=True)
474 self.run_cell(code, store_history=True)
476
475
477 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
476 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
478 # An extra layer of protection in case someone mashing Ctrl-C breaks
477 # An extra layer of protection in case someone mashing Ctrl-C breaks
479 # out of our internal code.
478 # out of our internal code.
480 if display_banner is not DISPLAY_BANNER_DEPRECATED:
479 if display_banner is not DISPLAY_BANNER_DEPRECATED:
481 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
480 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
482 while True:
481 while True:
483 try:
482 try:
484 self.interact()
483 self.interact()
485 break
484 break
486 except KeyboardInterrupt as e:
485 except KeyboardInterrupt as e:
487 print("\n%s escaped interact()\n" % type(e).__name__)
486 print("\n%s escaped interact()\n" % type(e).__name__)
488 finally:
487 finally:
489 # An interrupt during the eventloop will mess up the
488 # An interrupt during the eventloop will mess up the
490 # internal state of the prompt_toolkit library.
489 # internal state of the prompt_toolkit library.
491 # Stopping the eventloop fixes this, see
490 # Stopping the eventloop fixes this, see
492 # https://github.com/ipython/ipython/pull/9867
491 # https://github.com/ipython/ipython/pull/9867
493 if hasattr(self, '_eventloop'):
492 if hasattr(self, '_eventloop'):
494 self._eventloop.stop()
493 self._eventloop.stop()
495
494
496 _inputhook = None
495 _inputhook = None
497 def inputhook(self, context):
496 def inputhook(self, context):
498 if self._inputhook is not None:
497 if self._inputhook is not None:
499 self._inputhook(context)
498 self._inputhook(context)
500
499
501 active_eventloop = None
500 active_eventloop = None
502 def enable_gui(self, gui=None):
501 def enable_gui(self, gui=None):
503 if gui:
502 if gui:
504 self.active_eventloop, self._inputhook =\
503 self.active_eventloop, self._inputhook =\
505 get_inputhook_name_and_func(gui)
504 get_inputhook_name_and_func(gui)
506 else:
505 else:
507 self.active_eventloop = self._inputhook = None
506 self.active_eventloop = self._inputhook = None
508
507
509 # Run !system commands directly, not through pipes, so terminal programs
508 # Run !system commands directly, not through pipes, so terminal programs
510 # work correctly.
509 # work correctly.
511 system = InteractiveShell.system_raw
510 system = InteractiveShell.system_raw
512
511
513 def auto_rewrite_input(self, cmd):
512 def auto_rewrite_input(self, cmd):
514 """Overridden from the parent class to use fancy rewriting prompt"""
513 """Overridden from the parent class to use fancy rewriting prompt"""
515 if not self.show_rewritten_input:
514 if not self.show_rewritten_input:
516 return
515 return
517
516
518 tokens = self.prompts.rewrite_prompt_tokens()
517 tokens = self.prompts.rewrite_prompt_tokens()
519 if self.pt_cli:
518 if self.pt_cli:
520 self.pt_cli.print_tokens(tokens)
519 self.pt_cli.print_tokens(tokens)
521 print(cmd)
520 print(cmd)
522 else:
521 else:
523 prompt = ''.join(s for t, s in tokens)
522 prompt = ''.join(s for t, s in tokens)
524 print(prompt, cmd, sep='')
523 print(prompt, cmd, sep='')
525
524
526 _prompts_before = None
525 _prompts_before = None
527 def switch_doctest_mode(self, mode):
526 def switch_doctest_mode(self, mode):
528 """Switch prompts to classic for %doctest_mode"""
527 """Switch prompts to classic for %doctest_mode"""
529 if mode:
528 if mode:
530 self._prompts_before = self.prompts
529 self._prompts_before = self.prompts
531 self.prompts = ClassicPrompts(self)
530 self.prompts = ClassicPrompts(self)
532 elif self._prompts_before:
531 elif self._prompts_before:
533 self.prompts = self._prompts_before
532 self.prompts = self._prompts_before
534 self._prompts_before = None
533 self._prompts_before = None
535 self._update_layout()
534 self._update_layout()
536
535
537
536
538 InteractiveShellABC.register(TerminalInteractiveShell)
537 InteractiveShellABC.register(TerminalInteractiveShell)
539
538
540 if __name__ == '__main__':
539 if __name__ == '__main__':
541 TerminalInteractiveShell.instance().interact()
540 TerminalInteractiveShell.instance().interact()
@@ -1,256 +1,256 b''
1 """
1 """
2 Module to define and register Terminal IPython shortcuts with
2 Module to define and register Terminal IPython shortcuts with
3 :mod:`prompt_toolkit`
3 :mod:`prompt_toolkit`
4 """
4 """
5
5
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9 import warnings
9 import warnings
10 import signal
10 import signal
11 import sys
11 import sys
12 from typing import Callable
12 from typing import Callable
13
13
14
14
15 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
15 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
16 from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
16 from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
17 ViInsertMode, EmacsInsertMode, HasCompletions)
17 ViInsertMode, EmacsInsertMode, HasCompletions)
18 from prompt_toolkit.filters.cli import ViMode, ViNavigationMode
18 from prompt_toolkit.filters.cli import ViMode, ViNavigationMode
19 from prompt_toolkit.keys import Keys
19 from prompt_toolkit.keys import Keys
20 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
20 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
21
21
22 from IPython.utils.decorators import undoc
22 from IPython.utils.decorators import undoc
23
23
24 @undoc
24 @undoc
25 @Condition
25 @Condition
26 def cursor_in_leading_ws(cli):
26 def cursor_in_leading_ws(cli):
27 before = cli.application.buffer.document.current_line_before_cursor
27 before = cli.application.buffer.document.current_line_before_cursor
28 return (not before) or before.isspace()
28 return (not before) or before.isspace()
29
29
30 def register_ipython_shortcuts(registry, shell):
30 def register_ipython_shortcuts(registry, shell):
31 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
31 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
32 insert_mode = ViInsertMode() | EmacsInsertMode()
32 insert_mode = ViInsertMode() | EmacsInsertMode()
33
33
34 if getattr(shell, 'handle_return', None):
34 if getattr(shell, 'handle_return', None):
35 return_handler = shell.handle_return(shell)
35 return_handler = shell.handle_return(shell)
36 else:
36 else:
37 return_handler = newline_or_execute_outer(shell)
37 return_handler = newline_or_execute_outer(shell)
38
38
39 # Ctrl+J == Enter, seemingly
39 # Ctrl+J == Enter, seemingly
40 registry.add_binding(Keys.ControlJ,
40 registry.add_binding(Keys.ControlJ,
41 filter=(HasFocus(DEFAULT_BUFFER)
41 filter=(HasFocus(DEFAULT_BUFFER)
42 & ~HasSelection()
42 & ~HasSelection()
43 & insert_mode
43 & insert_mode
44 ))(return_handler)
44 ))(return_handler)
45
45
46 registry.add_binding(Keys.ControlBackslash)(force_exit)
46 registry.add_binding(Keys.ControlBackslash)(force_exit)
47
47
48 registry.add_binding(Keys.ControlP,
48 registry.add_binding(Keys.ControlP,
49 filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
49 filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
50 ))(previous_history_or_previous_completion)
50 ))(previous_history_or_previous_completion)
51
51
52 registry.add_binding(Keys.ControlN,
52 registry.add_binding(Keys.ControlN,
53 filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
53 filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
54 ))(next_history_or_next_completion)
54 ))(next_history_or_next_completion)
55
55
56 registry.add_binding(Keys.ControlG,
56 registry.add_binding(Keys.ControlG,
57 filter=(HasFocus(DEFAULT_BUFFER) & HasCompletions()
57 filter=(HasFocus(DEFAULT_BUFFER) & HasCompletions()
58 ))(dismiss_completion)
58 ))(dismiss_completion)
59
59
60 registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)
60 registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)
61 )(reset_buffer)
61 )(reset_buffer)
62
62
63 registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)
63 registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)
64 )(reset_search_buffer)
64 )(reset_search_buffer)
65
65
66 supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
66 supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
67 registry.add_binding(Keys.ControlZ, filter=supports_suspend
67 registry.add_binding(Keys.ControlZ, filter=supports_suspend
68 )(suspend_to_bg)
68 )(suspend_to_bg)
69
69
70 # Ctrl+I == Tab
70 # Ctrl+I == Tab
71 registry.add_binding(Keys.ControlI,
71 registry.add_binding(Keys.ControlI,
72 filter=(HasFocus(DEFAULT_BUFFER)
72 filter=(HasFocus(DEFAULT_BUFFER)
73 & ~HasSelection()
73 & ~HasSelection()
74 & insert_mode
74 & insert_mode
75 & cursor_in_leading_ws
75 & cursor_in_leading_ws
76 ))(indent_buffer)
76 ))(indent_buffer)
77
77
78 registry.add_binding(Keys.ControlO,
78 registry.add_binding(Keys.ControlO,
79 filter=(HasFocus(DEFAULT_BUFFER)
79 filter=(HasFocus(DEFAULT_BUFFER)
80 & EmacsInsertMode()))(newline_autoindent_outer(shell.input_transformer_manager))
80 & EmacsInsertMode()))(newline_autoindent_outer(shell.input_transformer_manager))
81
81
82 registry.add_binding(Keys.F2,
82 registry.add_binding(Keys.F2,
83 filter=HasFocus(DEFAULT_BUFFER)
83 filter=HasFocus(DEFAULT_BUFFER)
84 )(open_input_in_editor)
84 )(open_input_in_editor)
85
85
86 if shell.display_completions == 'readlinelike':
86 if shell.display_completions == 'readlinelike':
87 registry.add_binding(Keys.ControlI,
87 registry.add_binding(Keys.ControlI,
88 filter=(HasFocus(DEFAULT_BUFFER)
88 filter=(HasFocus(DEFAULT_BUFFER)
89 & ~HasSelection()
89 & ~HasSelection()
90 & insert_mode
90 & insert_mode
91 & ~cursor_in_leading_ws
91 & ~cursor_in_leading_ws
92 ))(display_completions_like_readline)
92 ))(display_completions_like_readline)
93
93
94 if sys.platform == 'win32':
94 if sys.platform == 'win32':
95 registry.add_binding(Keys.ControlV,
95 registry.add_binding(Keys.ControlV,
96 filter=(
96 filter=(
97 HasFocus(
97 HasFocus(
98 DEFAULT_BUFFER) & ~ViMode()
98 DEFAULT_BUFFER) & ~ViMode()
99 ))(win_paste)
99 ))(win_paste)
100
100
101
101
102 def newline_or_execute_outer(shell):
102 def newline_or_execute_outer(shell):
103 def newline_or_execute(event):
103 def newline_or_execute(event):
104 """When the user presses return, insert a newline or execute the code."""
104 """When the user presses return, insert a newline or execute the code."""
105 b = event.current_buffer
105 b = event.current_buffer
106 d = b.document
106 d = b.document
107
107
108 if b.complete_state:
108 if b.complete_state:
109 cc = b.complete_state.current_completion
109 cc = b.complete_state.current_completion
110 if cc:
110 if cc:
111 b.apply_completion(cc)
111 b.apply_completion(cc)
112 else:
112 else:
113 b.cancel_completion()
113 b.cancel_completion()
114 return
114 return
115
115
116 # If there's only one line, treat it as if the cursor is at the end.
116 # If there's only one line, treat it as if the cursor is at the end.
117 # See https://github.com/ipython/ipython/issues/10425
117 # See https://github.com/ipython/ipython/issues/10425
118 if d.line_count == 1:
118 if d.line_count == 1:
119 check_text = d.text
119 check_text = d.text
120 else:
120 else:
121 check_text = d.text[:d.cursor_position]
121 check_text = d.text[:d.cursor_position]
122 status, indent = shell.input_transformer_manager.check_complete(check_text + '\n')
122 status, indent = shell.check_complete(check_text)
123
123
124 if not (d.on_last_line or
124 if not (d.on_last_line or
125 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
125 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
126 ):
126 ):
127 b.insert_text('\n' + (' ' * (indent or 0)))
127 b.insert_text('\n' + indent)
128 return
128 return
129
129
130 if (status != 'incomplete') and b.accept_action.is_returnable:
130 if (status != 'incomplete') and b.accept_action.is_returnable:
131 b.accept_action.validate_and_handle(event.cli, b)
131 b.accept_action.validate_and_handle(event.cli, b)
132 else:
132 else:
133 b.insert_text('\n' + (' ' * (indent or 0)))
133 b.insert_text('\n' + indent)
134 return newline_or_execute
134 return newline_or_execute
135
135
136
136
137 def previous_history_or_previous_completion(event):
137 def previous_history_or_previous_completion(event):
138 """
138 """
139 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
139 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
140
140
141 If completer is open this still select previous completion.
141 If completer is open this still select previous completion.
142 """
142 """
143 event.current_buffer.auto_up()
143 event.current_buffer.auto_up()
144
144
145
145
146 def next_history_or_next_completion(event):
146 def next_history_or_next_completion(event):
147 """
147 """
148 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
148 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
149
149
150 If completer is open this still select next completion.
150 If completer is open this still select next completion.
151 """
151 """
152 event.current_buffer.auto_down()
152 event.current_buffer.auto_down()
153
153
154
154
155 def dismiss_completion(event):
155 def dismiss_completion(event):
156 b = event.current_buffer
156 b = event.current_buffer
157 if b.complete_state:
157 if b.complete_state:
158 b.cancel_completion()
158 b.cancel_completion()
159
159
160
160
161 def reset_buffer(event):
161 def reset_buffer(event):
162 b = event.current_buffer
162 b = event.current_buffer
163 if b.complete_state:
163 if b.complete_state:
164 b.cancel_completion()
164 b.cancel_completion()
165 else:
165 else:
166 b.reset()
166 b.reset()
167
167
168
168
169 def reset_search_buffer(event):
169 def reset_search_buffer(event):
170 if event.current_buffer.document.text:
170 if event.current_buffer.document.text:
171 event.current_buffer.reset()
171 event.current_buffer.reset()
172 else:
172 else:
173 event.cli.push_focus(DEFAULT_BUFFER)
173 event.cli.push_focus(DEFAULT_BUFFER)
174
174
175 def suspend_to_bg(event):
175 def suspend_to_bg(event):
176 event.cli.suspend_to_background()
176 event.cli.suspend_to_background()
177
177
178 def force_exit(event):
178 def force_exit(event):
179 """
179 """
180 Force exit (with a non-zero return value)
180 Force exit (with a non-zero return value)
181 """
181 """
182 sys.exit("Quit")
182 sys.exit("Quit")
183
183
184 def indent_buffer(event):
184 def indent_buffer(event):
185 event.current_buffer.insert_text(' ' * 4)
185 event.current_buffer.insert_text(' ' * 4)
186
186
187 @undoc
187 @undoc
188 def newline_with_copy_margin(event):
188 def newline_with_copy_margin(event):
189 """
189 """
190 DEPRECATED since IPython 6.0
190 DEPRECATED since IPython 6.0
191
191
192 See :any:`newline_autoindent_outer` for a replacement.
192 See :any:`newline_autoindent_outer` for a replacement.
193
193
194 Preserve margin and cursor position when using
194 Preserve margin and cursor position when using
195 Control-O to insert a newline in EMACS mode
195 Control-O to insert a newline in EMACS mode
196 """
196 """
197 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
197 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
198 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
198 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
199 DeprecationWarning, stacklevel=2)
199 DeprecationWarning, stacklevel=2)
200
200
201 b = event.current_buffer
201 b = event.current_buffer
202 cursor_start_pos = b.document.cursor_position_col
202 cursor_start_pos = b.document.cursor_position_col
203 b.newline(copy_margin=True)
203 b.newline(copy_margin=True)
204 b.cursor_up(count=1)
204 b.cursor_up(count=1)
205 cursor_end_pos = b.document.cursor_position_col
205 cursor_end_pos = b.document.cursor_position_col
206 if cursor_start_pos != cursor_end_pos:
206 if cursor_start_pos != cursor_end_pos:
207 pos_diff = cursor_start_pos - cursor_end_pos
207 pos_diff = cursor_start_pos - cursor_end_pos
208 b.cursor_right(count=pos_diff)
208 b.cursor_right(count=pos_diff)
209
209
210 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
210 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
211 """
211 """
212 Return a function suitable for inserting a indented newline after the cursor.
212 Return a function suitable for inserting a indented newline after the cursor.
213
213
214 Fancier version of deprecated ``newline_with_copy_margin`` which should
214 Fancier version of deprecated ``newline_with_copy_margin`` which should
215 compute the correct indentation of the inserted line. That is to say, indent
215 compute the correct indentation of the inserted line. That is to say, indent
216 by 4 extra space after a function definition, class definition, context
216 by 4 extra space after a function definition, class definition, context
217 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
217 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
218 """
218 """
219
219
220 def newline_autoindent(event):
220 def newline_autoindent(event):
221 """insert a newline after the cursor indented appropriately."""
221 """insert a newline after the cursor indented appropriately."""
222 b = event.current_buffer
222 b = event.current_buffer
223 d = b.document
223 d = b.document
224
224
225 if b.complete_state:
225 if b.complete_state:
226 b.cancel_completion()
226 b.cancel_completion()
227 text = d.text[:d.cursor_position] + '\n'
227 text = d.text[:d.cursor_position] + '\n'
228 _, indent = inputsplitter.check_complete(text)
228 _, indent = inputsplitter.check_complete(text)
229 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
229 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
230
230
231 return newline_autoindent
231 return newline_autoindent
232
232
233
233
234 def open_input_in_editor(event):
234 def open_input_in_editor(event):
235 event.cli.current_buffer.tempfile_suffix = ".py"
235 event.cli.current_buffer.tempfile_suffix = ".py"
236 event.cli.current_buffer.open_in_editor(event.cli)
236 event.cli.current_buffer.open_in_editor(event.cli)
237
237
238
238
239 if sys.platform == 'win32':
239 if sys.platform == 'win32':
240 from IPython.core.error import TryNext
240 from IPython.core.error import TryNext
241 from IPython.lib.clipboard import (ClipboardEmpty,
241 from IPython.lib.clipboard import (ClipboardEmpty,
242 win32_clipboard_get,
242 win32_clipboard_get,
243 tkinter_clipboard_get)
243 tkinter_clipboard_get)
244
244
245 @undoc
245 @undoc
246 def win_paste(event):
246 def win_paste(event):
247 try:
247 try:
248 text = win32_clipboard_get()
248 text = win32_clipboard_get()
249 except TryNext:
249 except TryNext:
250 try:
250 try:
251 text = tkinter_clipboard_get()
251 text = tkinter_clipboard_get()
252 except (TryNext, ClipboardEmpty):
252 except (TryNext, ClipboardEmpty):
253 return
253 return
254 except ClipboardEmpty:
254 except ClipboardEmpty:
255 return
255 return
256 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
256 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
@@ -1,293 +1,293 b''
1 =======================
1 =======================
2 Specific config details
2 Specific config details
3 =======================
3 =======================
4
4
5 .. _custom_prompts:
5 .. _custom_prompts:
6
6
7 Custom Prompts
7 Custom Prompts
8 ==============
8 ==============
9
9
10 .. versionchanged:: 5.0
10 .. versionchanged:: 5.0
11
11
12 From IPython 5, prompts are produced as a list of Pygments tokens, which are
12 From IPython 5, prompts are produced as a list of Pygments tokens, which are
13 tuples of (token_type, text). You can customise prompts by writing a method
13 tuples of (token_type, text). You can customise prompts by writing a method
14 which generates a list of tokens.
14 which generates a list of tokens.
15
15
16 There are four kinds of prompt:
16 There are four kinds of prompt:
17
17
18 * The **in** prompt is shown before the first line of input
18 * The **in** prompt is shown before the first line of input
19 (default like ``In [1]:``).
19 (default like ``In [1]:``).
20 * The **continuation** prompt is shown before further lines of input
20 * The **continuation** prompt is shown before further lines of input
21 (default like ``...:``).
21 (default like ``...:``).
22 * The **rewrite** prompt is shown to highlight how special syntax has been
22 * The **rewrite** prompt is shown to highlight how special syntax has been
23 interpreted (default like ``----->``).
23 interpreted (default like ``----->``).
24 * The **out** prompt is shown before the result from evaluating the input
24 * The **out** prompt is shown before the result from evaluating the input
25 (default like ``Out[1]:``).
25 (default like ``Out[1]:``).
26
26
27 Custom prompts are supplied together as a class. If you want to customise only
27 Custom prompts are supplied together as a class. If you want to customise only
28 some of the prompts, inherit from :class:`IPython.terminal.prompts.Prompts`,
28 some of the prompts, inherit from :class:`IPython.terminal.prompts.Prompts`,
29 which defines the defaults. The required interface is like this:
29 which defines the defaults. The required interface is like this:
30
30
31 .. class:: MyPrompts(shell)
31 .. class:: MyPrompts(shell)
32
32
33 Prompt style definition. *shell* is a reference to the
33 Prompt style definition. *shell* is a reference to the
34 :class:`~.TerminalInteractiveShell` instance.
34 :class:`~.TerminalInteractiveShell` instance.
35
35
36 .. method:: in_prompt_tokens(cli=None)
36 .. method:: in_prompt_tokens(cli=None)
37 continuation_prompt_tokens(self, cli=None, width=None)
37 continuation_prompt_tokens(self, cli=None, width=None)
38 rewrite_prompt_tokens()
38 rewrite_prompt_tokens()
39 out_prompt_tokens()
39 out_prompt_tokens()
40
40
41 Return the respective prompts as lists of ``(token_type, text)`` tuples.
41 Return the respective prompts as lists of ``(token_type, text)`` tuples.
42
42
43 For continuation prompts, *width* is an integer representing the width of
43 For continuation prompts, *width* is an integer representing the width of
44 the prompt area in terminal columns.
44 the prompt area in terminal columns.
45
45
46 *cli*, where used, is the prompt_toolkit ``CommandLineInterface`` instance.
46 *cli*, where used, is the prompt_toolkit ``CommandLineInterface`` instance.
47 This is mainly for compatibility with the API prompt_toolkit expects.
47 This is mainly for compatibility with the API prompt_toolkit expects.
48
48
49 Here is an example Prompt class that will show the current working directory
49 Here is an example Prompt class that will show the current working directory
50 in the input prompt:
50 in the input prompt:
51
51
52 .. code-block:: python
52 .. code-block:: python
53
53
54 from IPython.terminal.prompts import Prompts, Token
54 from IPython.terminal.prompts import Prompts, Token
55 import os
55 import os
56
56
57 class MyPrompt(Prompts):
57 class MyPrompt(Prompts):
58 def in_prompt_tokens(self, cli=None):
58 def in_prompt_tokens(self, cli=None):
59 return [(Token, os.getcwd()),
59 return [(Token, os.getcwd()),
60 (Token.Prompt, ' >>>')]
60 (Token.Prompt, ' >>>')]
61
61
62 To set the new prompt, assign it to the ``prompts`` attribute of the IPython
62 To set the new prompt, assign it to the ``prompts`` attribute of the IPython
63 shell:
63 shell:
64
64
65 .. code-block:: python
65 .. code-block:: python
66
66
67 In [2]: ip = get_ipython()
67 In [2]: ip = get_ipython()
68 ...: ip.prompts = MyPrompt(ip)
68 ...: ip.prompts = MyPrompt(ip)
69
69
70 /home/bob >>> # it works
70 /home/bob >>> # it works
71
71
72 See ``IPython/example/utils/cwd_prompt.py`` for an example of how to write an
72 See ``IPython/example/utils/cwd_prompt.py`` for an example of how to write an
73 extensions to customise prompts.
73 extensions to customise prompts.
74
74
75 Inside IPython or in a startup script, you can use a custom prompts class
75 Inside IPython or in a startup script, you can use a custom prompts class
76 by setting ``get_ipython().prompts`` to an *instance* of the class.
76 by setting ``get_ipython().prompts`` to an *instance* of the class.
77 In configuration, ``TerminalInteractiveShell.prompts_class`` may be set to
77 In configuration, ``TerminalInteractiveShell.prompts_class`` may be set to
78 either the class object, or a string of its full importable name.
78 either the class object, or a string of its full importable name.
79
79
80 To include invisible terminal control sequences in a prompt, use
80 To include invisible terminal control sequences in a prompt, use
81 ``Token.ZeroWidthEscape`` as the token type. Tokens with this type are ignored
81 ``Token.ZeroWidthEscape`` as the token type. Tokens with this type are ignored
82 when calculating the width.
82 when calculating the width.
83
83
84 Colours in the prompt are determined by the token types and the highlighting
84 Colours in the prompt are determined by the token types and the highlighting
85 style; see below for more details. The tokens used in the default prompts are
85 style; see below for more details. The tokens used in the default prompts are
86 ``Prompt``, ``PromptNum``, ``OutPrompt`` and ``OutPromptNum``.
86 ``Prompt``, ``PromptNum``, ``OutPrompt`` and ``OutPromptNum``.
87
87
88 .. _termcolour:
88 .. _termcolour:
89
89
90 Terminal Colors
90 Terminal Colors
91 ===============
91 ===============
92
92
93 .. versionchanged:: 5.0
93 .. versionchanged:: 5.0
94
94
95 There are two main configuration options controlling colours.
95 There are two main configuration options controlling colours.
96
96
97 ``InteractiveShell.colors`` sets the colour of tracebacks and object info (the
97 ``InteractiveShell.colors`` sets the colour of tracebacks and object info (the
98 output from e.g. ``zip?``). It may also affect other things if the option below
98 output from e.g. ``zip?``). It may also affect other things if the option below
99 is set to ``'legacy'``. It has four case-insensitive values:
99 is set to ``'legacy'``. It has four case-insensitive values:
100 ``'nocolor', 'neutral', 'linux', 'lightbg'``. The default is *neutral*, which
100 ``'nocolor', 'neutral', 'linux', 'lightbg'``. The default is *neutral*, which
101 should be legible on either dark or light terminal backgrounds. *linux* is
101 should be legible on either dark or light terminal backgrounds. *linux* is
102 optimised for dark backgrounds and *lightbg* for light ones.
102 optimised for dark backgrounds and *lightbg* for light ones.
103
103
104 ``TerminalInteractiveShell.highlighting_style`` determines prompt colours and
104 ``TerminalInteractiveShell.highlighting_style`` determines prompt colours and
105 syntax highlighting. It takes the name (as a string) or class (as a subclass of
105 syntax highlighting. It takes the name (as a string) or class (as a subclass of
106 ``pygments.style.Style``) of a Pygments style, or the special value ``'legacy'``
106 ``pygments.style.Style``) of a Pygments style, or the special value ``'legacy'``
107 to pick a style in accordance with ``InteractiveShell.colors``.
107 to pick a style in accordance with ``InteractiveShell.colors``.
108
108
109 You can see the Pygments styles available on your system by running::
109 You can see the Pygments styles available on your system by running::
110
110
111 import pygments
111 import pygments
112 list(pygments.styles.get_all_styles())
112 list(pygments.styles.get_all_styles())
113
113
114 Additionally, ``TerminalInteractiveShell.highlighting_style_overrides`` can override
114 Additionally, ``TerminalInteractiveShell.highlighting_style_overrides`` can override
115 specific styles in the highlighting. It should be a dictionary mapping Pygments
115 specific styles in the highlighting. It should be a dictionary mapping Pygments
116 token types to strings defining the style. See `Pygments' documentation
116 token types to strings defining the style. See `Pygments' documentation
117 <http://pygments.org/docs/styles/#creating-own-styles>`__ for the language used
117 <http://pygments.org/docs/styles/#creating-own-styles>`__ for the language used
118 to define styles.
118 to define styles.
119
119
120 Colors in the pager
120 Colors in the pager
121 -------------------
121 -------------------
122
122
123 On some systems, the default pager has problems with ANSI colour codes.
123 On some systems, the default pager has problems with ANSI colour codes.
124 To configure your default pager to allow these:
124 To configure your default pager to allow these:
125
125
126 1. Set the environment PAGER variable to ``less``.
126 1. Set the environment PAGER variable to ``less``.
127 2. Set the environment LESS variable to ``-r`` (plus any other options
127 2. Set the environment LESS variable to ``-r`` (plus any other options
128 you always want to pass to less by default). This tells less to
128 you always want to pass to less by default). This tells less to
129 properly interpret control sequences, which is how color
129 properly interpret control sequences, which is how color
130 information is given to your terminal.
130 information is given to your terminal.
131
131
132 .. _editors:
132 .. _editors:
133
133
134 Editor configuration
134 Editor configuration
135 ====================
135 ====================
136
136
137 IPython can integrate with text editors in a number of different ways:
137 IPython can integrate with text editors in a number of different ways:
138
138
139 * Editors (such as `(X)Emacs`_, vim_ and TextMate_) can
139 * Editors (such as `(X)Emacs`_, vim_ and TextMate_) can
140 send code to IPython for execution.
140 send code to IPython for execution.
141
141
142 * IPython's ``%edit`` magic command can open an editor of choice to edit
142 * IPython's ``%edit`` magic command can open an editor of choice to edit
143 a code block.
143 a code block.
144
144
145 The %edit command (and its alias %ed) will invoke the editor set in your
145 The %edit command (and its alias %ed) will invoke the editor set in your
146 environment as :envvar:`EDITOR`. If this variable is not set, it will default
146 environment as :envvar:`EDITOR`. If this variable is not set, it will default
147 to vi under Linux/Unix and to notepad under Windows. You may want to set this
147 to vi under Linux/Unix and to notepad under Windows. You may want to set this
148 variable properly and to a lightweight editor which doesn't take too long to
148 variable properly and to a lightweight editor which doesn't take too long to
149 start (that is, something other than a new instance of Emacs). This way you
149 start (that is, something other than a new instance of Emacs). This way you
150 can edit multi-line code quickly and with the power of a real editor right
150 can edit multi-line code quickly and with the power of a real editor right
151 inside IPython.
151 inside IPython.
152
152
153 You can also control the editor by setting :attr:`TerminalInteractiveShell.editor`
153 You can also control the editor by setting :attr:`TerminalInteractiveShell.editor`
154 in :file:`ipython_config.py`.
154 in :file:`ipython_config.py`.
155
155
156 Vim
156 Vim
157 ---
157 ---
158
158
159 Paul Ivanov's `vim-ipython <https://github.com/ivanov/vim-ipython>`_ provides
159 Paul Ivanov's `vim-ipython <https://github.com/ivanov/vim-ipython>`_ provides
160 powerful IPython integration for vim.
160 powerful IPython integration for vim.
161
161
162 .. _emacs:
162 .. _emacs:
163
163
164 (X)Emacs
164 (X)Emacs
165 --------
165 --------
166
166
167 If you are a dedicated Emacs user, and want to use Emacs when IPython's
167 If you are a dedicated Emacs user, and want to use Emacs when IPython's
168 ``%edit`` magic command is called you should set up the Emacs server so that
168 ``%edit`` magic command is called you should set up the Emacs server so that
169 new requests are handled by the original process. This means that almost no
169 new requests are handled by the original process. This means that almost no
170 time is spent in handling the request (assuming an Emacs process is already
170 time is spent in handling the request (assuming an Emacs process is already
171 running). For this to work, you need to set your EDITOR environment variable
171 running). For this to work, you need to set your EDITOR environment variable
172 to 'emacsclient'. The code below, supplied by Francois Pinard, can then be
172 to 'emacsclient'. The code below, supplied by Francois Pinard, can then be
173 used in your :file:`.emacs` file to enable the server:
173 used in your :file:`.emacs` file to enable the server:
174
174
175 .. code-block:: common-lisp
175 .. code-block:: common-lisp
176
176
177 (defvar server-buffer-clients)
177 (defvar server-buffer-clients)
178 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
178 (when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm))
179 (server-start)
179 (server-start)
180 (defun fp-kill-server-with-buffer-routine ()
180 (defun fp-kill-server-with-buffer-routine ()
181 (and server-buffer-clients (server-done)))
181 (and server-buffer-clients (server-done)))
182 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
182 (add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine))
183
183
184 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran,
184 Thanks to the work of Alexander Schmolck and Prabhu Ramachandran,
185 currently (X)Emacs and IPython get along very well in other ways.
185 currently (X)Emacs and IPython get along very well in other ways.
186
186
187 With (X)EMacs >= 24, You can enable IPython in python-mode with:
187 With (X)EMacs >= 24, You can enable IPython in python-mode with:
188
188
189 .. code-block:: common-lisp
189 .. code-block:: common-lisp
190
190
191 (require 'python)
191 (require 'python)
192 (setq python-shell-interpreter "ipython")
192 (setq python-shell-interpreter "ipython")
193
193
194 .. _`(X)Emacs`: http://www.gnu.org/software/emacs/
194 .. _`(X)Emacs`: http://www.gnu.org/software/emacs/
195 .. _TextMate: http://macromates.com/
195 .. _TextMate: http://macromates.com/
196 .. _vim: http://www.vim.org/
196 .. _vim: http://www.vim.org/
197
197
198 .. _custom_keyboard_shortcuts:
198 .. _custom_keyboard_shortcuts:
199
199
200 Keyboard Shortcuts
200 Keyboard Shortcuts
201 ==================
201 ==================
202
202
203 .. versionchanged:: 5.0
203 .. versionchanged:: 5.0
204
204
205 You can customise keyboard shortcuts for terminal IPython. Put code like this in
205 You can customise keyboard shortcuts for terminal IPython. Put code like this in
206 a :ref:`startup file <startup_files>`::
206 a :ref:`startup file <startup_files>`::
207
207
208 from IPython import get_ipython
208 from IPython import get_ipython
209 from prompt_toolkit.enums import DEFAULT_BUFFER
209 from prompt_toolkit.enums import DEFAULT_BUFFER
210 from prompt_toolkit.keys import Keys
210 from prompt_toolkit.keys import Keys
211 from prompt_toolkit.filters import HasFocus, HasSelection, ViInsertMode, EmacsInsertMode
211 from prompt_toolkit.filters import HasFocus, HasSelection, ViInsertMode, EmacsInsertMode
212
212
213 ip = get_ipython()
213 ip = get_ipython()
214 insert_mode = ViInsertMode() | EmacsInsertMode()
214 insert_mode = ViInsertMode() | EmacsInsertMode()
215
215
216 def insert_unexpected(event):
216 def insert_unexpected(event):
217 buf = event.current_buffer
217 buf = event.current_buffer
218 buf.insert_text('The Spanish Inquisition')
218 buf.insert_text('The Spanish Inquisition')
219
219
220 # Register the shortcut if IPython is using prompt_toolkit
220 # Register the shortcut if IPython is using prompt_toolkit
221 if getattr(ip, 'pt_cli'):
221 if getattr(ip, 'pt_cli'):
222 registry = ip.pt_cli.application.key_bindings_registry
222 registry = ip.pt_cli.application.key_bindings_registry
223 registry.add_binding(Keys.ControlN,
223 registry.add_binding(Keys.ControlN,
224 filter=(HasFocus(DEFAULT_BUFFER)
224 filter=(HasFocus(DEFAULT_BUFFER)
225 & ~HasSelection()
225 & ~HasSelection()
226 & insert_mode))(insert_unexpected)
226 & insert_mode))(insert_unexpected)
227
227
228 For more information on filters and what you can do with the ``event`` object,
228 For more information on filters and what you can do with the ``event`` object,
229 `see the prompt_toolkit docs
229 `see the prompt_toolkit docs
230 <http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#adding-custom-key-bindings>`__.
230 <http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#adding-custom-key-bindings>`__.
231
231
232
232
233 Enter to execute
233 Enter to execute
234 ----------------
234 ----------------
235
235
236 In the Terminal IPython shell – which by default uses the ``prompt_toolkit``
236 In the Terminal IPython shell – which by default uses the ``prompt_toolkit``
237 interface, the semantic meaning of pressing the :kbd:`Enter` key can be
237 interface, the semantic meaning of pressing the :kbd:`Enter` key can be
238 ambiguous. In some case :kbd:`Enter` should execute code, and in others it
238 ambiguous. In some case :kbd:`Enter` should execute code, and in others it
239 should add a new line. IPython uses heuristics to decide whether to execute or
239 should add a new line. IPython uses heuristics to decide whether to execute or
240 insert a new line at cursor position. For example, if we detect that the current
240 insert a new line at cursor position. For example, if we detect that the current
241 code is not valid Python, then the user is likely editing code and the right
241 code is not valid Python, then the user is likely editing code and the right
242 behavior is to likely to insert a new line. If the current code is a simple
242 behavior is to likely to insert a new line. If the current code is a simple
243 statement like `ord('*')`, then the right behavior is likely to execute. Though
243 statement like `ord('*')`, then the right behavior is likely to execute. Though
244 the exact desired semantics often varies from users to users.
244 the exact desired semantics often varies from users to users.
245
245
246 As the exact behavior of :kbd:`Enter` is ambiguous, it has been special cased
246 As the exact behavior of :kbd:`Enter` is ambiguous, it has been special cased
247 to allow users to completely configure the behavior they like. Hence you can
247 to allow users to completely configure the behavior they like. Hence you can
248 have enter always execute code. If you prefer fancier behavior, you need to get
248 have enter always execute code. If you prefer fancier behavior, you need to get
249 your hands dirty and read the ``prompt_toolkit`` and IPython documentation
249 your hands dirty and read the ``prompt_toolkit`` and IPython documentation
250 though. See :ghpull:`10500`, set the
250 though. See :ghpull:`10500`, set the
251 ``c.TerminalInteractiveShell.handle_return`` option and get inspiration from the
251 ``c.TerminalInteractiveShell.handle_return`` option and get inspiration from the
252 following example that only auto-executes the input if it begins with a bang or
252 following example that only auto-executes the input if it begins with a bang or
253 a modulo character (``!`` or ``%``). To use the following code, add it to your
253 a modulo character (``!`` or ``%``). To use the following code, add it to your
254 IPython configuration::
254 IPython configuration::
255
255
256 def custom_return(shell):
256 def custom_return(shell):
257
257
258 """This function is required by the API. It takes a reference to
258 """This function is required by the API. It takes a reference to
259 the shell, which is the same thing `get_ipython()` evaluates to.
259 the shell, which is the same thing `get_ipython()` evaluates to.
260 This function must return a function that handles each keypress
260 This function must return a function that handles each keypress
261 event. That function, named `handle` here, references `shell`
261 event. That function, named `handle` here, references `shell`
262 by closure."""
262 by closure."""
263
263
264 def handle(event):
264 def handle(event):
265
265
266 """This function is called each time `Enter` is pressed,
266 """This function is called each time `Enter` is pressed,
267 and takes a reference to a Prompt Toolkit event object.
267 and takes a reference to a Prompt Toolkit event object.
268 If the current input starts with a bang or modulo, then
268 If the current input starts with a bang or modulo, then
269 the input is executed, otherwise a newline is entered,
269 the input is executed, otherwise a newline is entered,
270 followed by any spaces needed to auto-indent."""
270 followed by any spaces needed to auto-indent."""
271
271
272 # set up a few handy references to nested items...
272 # set up a few handy references to nested items...
273
273
274 buffer = event.current_buffer
274 buffer = event.current_buffer
275 document = buffer.document
275 document = buffer.document
276 text = document.text
276 text = document.text
277
277
278 if text.startswith('!') or text.startswith('%'): # execute the input...
278 if text.startswith('!') or text.startswith('%'): # execute the input...
279
279
280 buffer.accept_action.validate_and_handle(event.cli, buffer)
280 buffer.accept_action.validate_and_handle(event.cli, buffer)
281
281
282 else: # insert a newline with auto-indentation...
282 else: # insert a newline with auto-indentation...
283
283
284 if document.line_count > 1: text = text[:document.cursor_position]
284 if document.line_count > 1: text = text[:document.cursor_position]
285 indent = shell.input_transformer_manager.check_complete(text)[1] or 0
285 indent = shell.check_complete(text)[1]
286 buffer.insert_text('\n' + ' ' * indent)
286 buffer.insert_text('\n' + indent)
287
287
288 # if you just wanted a plain newline without any indentation, you
288 # if you just wanted a plain newline without any indentation, you
289 # could use `buffer.insert_text('\n')` instead of the lines above
289 # could use `buffer.insert_text('\n')` instead of the lines above
290
290
291 return handle
291 return handle
292
292
293 c.TerminalInteractiveShell.handle_return = custom_return
293 c.TerminalInteractiveShell.handle_return = custom_return
General Comments 0
You need to be logged in to leave comments. Login now