##// END OF EJS Templates
Merge pull request #2002 from bfroehle/lsmagic_docs...
Fernando Perez -
r7654:edaad4c7 merge
parent child Browse files
Show More
@@ -1,592 +1,616 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Stdlib
17 # Stdlib
18 import os
18 import os
19 import re
19 import re
20 import sys
20 import sys
21 import types
21 import types
22 from getopt import getopt, GetoptError
22 from getopt import getopt, GetoptError
23
23
24 # Our own
24 # Our own
25 from IPython.config.configurable import Configurable
25 from IPython.config.configurable import Configurable
26 from IPython.core import oinspect
26 from IPython.core import oinspect
27 from IPython.core.error import UsageError
27 from IPython.core.error import UsageError
28 from IPython.core.inputsplitter import ESC_MAGIC
28 from IPython.core.inputsplitter import ESC_MAGIC
29 from IPython.external.decorator import decorator
29 from IPython.external.decorator import decorator
30 from IPython.utils.ipstruct import Struct
30 from IPython.utils.ipstruct import Struct
31 from IPython.utils.process import arg_split
31 from IPython.utils.process import arg_split
32 from IPython.utils.text import dedent
32 from IPython.utils.text import dedent
33 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
33 from IPython.utils.traitlets import Bool, Dict, Instance, MetaHasTraits
34 from IPython.utils.warn import error, warn
34 from IPython.utils.warn import error, warn
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Globals
37 # Globals
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 # A dict we'll use for each class that has magics, used as temporary storage to
40 # A dict we'll use for each class that has magics, used as temporary storage to
41 # pass information between the @line/cell_magic method decorators and the
41 # pass information between the @line/cell_magic method decorators and the
42 # @magics_class class decorator, because the method decorators have no
42 # @magics_class class decorator, because the method decorators have no
43 # access to the class when they run. See for more details:
43 # access to the class when they run. See for more details:
44 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
44 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
45
45
46 magics = dict(line={}, cell={})
46 magics = dict(line={}, cell={})
47
47
48 magic_kinds = ('line', 'cell')
48 magic_kinds = ('line', 'cell')
49 magic_spec = ('line', 'cell', 'line_cell')
49 magic_spec = ('line', 'cell', 'line_cell')
50
50
51 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
52 # Utility classes and functions
52 # Utility classes and functions
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54
54
55 class Bunch: pass
55 class Bunch: pass
56
56
57
57
58 def on_off(tag):
58 def on_off(tag):
59 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
60 return ['OFF','ON'][tag]
60 return ['OFF','ON'][tag]
61
61
62
62
63 def compress_dhist(dh):
63 def compress_dhist(dh):
64 """Compress a directory history into a new one with at most 20 entries.
64 """Compress a directory history into a new one with at most 20 entries.
65
65
66 Return a new list made from the first and last 10 elements of dhist after
66 Return a new list made from the first and last 10 elements of dhist after
67 removal of duplicates.
67 removal of duplicates.
68 """
68 """
69 head, tail = dh[:-10], dh[-10:]
69 head, tail = dh[:-10], dh[-10:]
70
70
71 newhead = []
71 newhead = []
72 done = set()
72 done = set()
73 for h in head:
73 for h in head:
74 if h in done:
74 if h in done:
75 continue
75 continue
76 newhead.append(h)
76 newhead.append(h)
77 done.add(h)
77 done.add(h)
78
78
79 return newhead + tail
79 return newhead + tail
80
80
81
81
82 def needs_local_scope(func):
82 def needs_local_scope(func):
83 """Decorator to mark magic functions which need to local scope to run."""
83 """Decorator to mark magic functions which need to local scope to run."""
84 func.needs_local_scope = True
84 func.needs_local_scope = True
85 return func
85 return func
86
86
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88 # Class and method decorators for registering magics
88 # Class and method decorators for registering magics
89 #-----------------------------------------------------------------------------
89 #-----------------------------------------------------------------------------
90
90
91 def magics_class(cls):
91 def magics_class(cls):
92 """Class decorator for all subclasses of the main Magics class.
92 """Class decorator for all subclasses of the main Magics class.
93
93
94 Any class that subclasses Magics *must* also apply this decorator, to
94 Any class that subclasses Magics *must* also apply this decorator, to
95 ensure that all the methods that have been decorated as line/cell magics
95 ensure that all the methods that have been decorated as line/cell magics
96 get correctly registered in the class instance. This is necessary because
96 get correctly registered in the class instance. This is necessary because
97 when method decorators run, the class does not exist yet, so they
97 when method decorators run, the class does not exist yet, so they
98 temporarily store their information into a module global. Application of
98 temporarily store their information into a module global. Application of
99 this class decorator copies that global data to the class instance and
99 this class decorator copies that global data to the class instance and
100 clears the global.
100 clears the global.
101
101
102 Obviously, this mechanism is not thread-safe, which means that the
102 Obviously, this mechanism is not thread-safe, which means that the
103 *creation* of subclasses of Magic should only be done in a single-thread
103 *creation* of subclasses of Magic should only be done in a single-thread
104 context. Instantiation of the classes has no restrictions. Given that
104 context. Instantiation of the classes has no restrictions. Given that
105 these classes are typically created at IPython startup time and before user
105 these classes are typically created at IPython startup time and before user
106 application code becomes active, in practice this should not pose any
106 application code becomes active, in practice this should not pose any
107 problems.
107 problems.
108 """
108 """
109 cls.registered = True
109 cls.registered = True
110 cls.magics = dict(line = magics['line'],
110 cls.magics = dict(line = magics['line'],
111 cell = magics['cell'])
111 cell = magics['cell'])
112 magics['line'] = {}
112 magics['line'] = {}
113 magics['cell'] = {}
113 magics['cell'] = {}
114 return cls
114 return cls
115
115
116
116
117 def record_magic(dct, magic_kind, magic_name, func):
117 def record_magic(dct, magic_kind, magic_name, func):
118 """Utility function to store a function as a magic of a specific kind.
118 """Utility function to store a function as a magic of a specific kind.
119
119
120 Parameters
120 Parameters
121 ----------
121 ----------
122 dct : dict
122 dct : dict
123 A dictionary with 'line' and 'cell' subdicts.
123 A dictionary with 'line' and 'cell' subdicts.
124
124
125 magic_kind : str
125 magic_kind : str
126 Kind of magic to be stored.
126 Kind of magic to be stored.
127
127
128 magic_name : str
128 magic_name : str
129 Key to store the magic as.
129 Key to store the magic as.
130
130
131 func : function
131 func : function
132 Callable object to store.
132 Callable object to store.
133 """
133 """
134 if magic_kind == 'line_cell':
134 if magic_kind == 'line_cell':
135 dct['line'][magic_name] = dct['cell'][magic_name] = func
135 dct['line'][magic_name] = dct['cell'][magic_name] = func
136 else:
136 else:
137 dct[magic_kind][magic_name] = func
137 dct[magic_kind][magic_name] = func
138
138
139
139
140 def validate_type(magic_kind):
140 def validate_type(magic_kind):
141 """Ensure that the given magic_kind is valid.
141 """Ensure that the given magic_kind is valid.
142
142
143 Check that the given magic_kind is one of the accepted spec types (stored
143 Check that the given magic_kind is one of the accepted spec types (stored
144 in the global `magic_spec`), raise ValueError otherwise.
144 in the global `magic_spec`), raise ValueError otherwise.
145 """
145 """
146 if magic_kind not in magic_spec:
146 if magic_kind not in magic_spec:
147 raise ValueError('magic_kind must be one of %s, %s given' %
147 raise ValueError('magic_kind must be one of %s, %s given' %
148 magic_kinds, magic_kind)
148 magic_kinds, magic_kind)
149
149
150
150
151 # The docstrings for the decorator below will be fairly similar for the two
151 # The docstrings for the decorator below will be fairly similar for the two
152 # types (method and function), so we generate them here once and reuse the
152 # types (method and function), so we generate them here once and reuse the
153 # templates below.
153 # templates below.
154 _docstring_template = \
154 _docstring_template = \
155 """Decorate the given {0} as {1} magic.
155 """Decorate the given {0} as {1} magic.
156
156
157 The decorator can be used with or without arguments, as follows.
157 The decorator can be used with or without arguments, as follows.
158
158
159 i) without arguments: it will create a {1} magic named as the {0} being
159 i) without arguments: it will create a {1} magic named as the {0} being
160 decorated::
160 decorated::
161
161
162 @deco
162 @deco
163 def foo(...)
163 def foo(...)
164
164
165 will create a {1} magic named `foo`.
165 will create a {1} magic named `foo`.
166
166
167 ii) with one string argument: which will be used as the actual name of the
167 ii) with one string argument: which will be used as the actual name of the
168 resulting magic::
168 resulting magic::
169
169
170 @deco('bar')
170 @deco('bar')
171 def foo(...)
171 def foo(...)
172
172
173 will create a {1} magic named `bar`.
173 will create a {1} magic named `bar`.
174 """
174 """
175
175
176 # These two are decorator factories. While they are conceptually very similar,
176 # These two are decorator factories. While they are conceptually very similar,
177 # there are enough differences in the details that it's simpler to have them
177 # there are enough differences in the details that it's simpler to have them
178 # written as completely standalone functions rather than trying to share code
178 # written as completely standalone functions rather than trying to share code
179 # and make a single one with convoluted logic.
179 # and make a single one with convoluted logic.
180
180
181 def _method_magic_marker(magic_kind):
181 def _method_magic_marker(magic_kind):
182 """Decorator factory for methods in Magics subclasses.
182 """Decorator factory for methods in Magics subclasses.
183 """
183 """
184
184
185 validate_type(magic_kind)
185 validate_type(magic_kind)
186
186
187 # This is a closure to capture the magic_kind. We could also use a class,
187 # This is a closure to capture the magic_kind. We could also use a class,
188 # but it's overkill for just that one bit of state.
188 # but it's overkill for just that one bit of state.
189 def magic_deco(arg):
189 def magic_deco(arg):
190 call = lambda f, *a, **k: f(*a, **k)
190 call = lambda f, *a, **k: f(*a, **k)
191
191
192 if callable(arg):
192 if callable(arg):
193 # "Naked" decorator call (just @foo, no args)
193 # "Naked" decorator call (just @foo, no args)
194 func = arg
194 func = arg
195 name = func.func_name
195 name = func.func_name
196 retval = decorator(call, func)
196 retval = decorator(call, func)
197 record_magic(magics, magic_kind, name, name)
197 record_magic(magics, magic_kind, name, name)
198 elif isinstance(arg, basestring):
198 elif isinstance(arg, basestring):
199 # Decorator called with arguments (@foo('bar'))
199 # Decorator called with arguments (@foo('bar'))
200 name = arg
200 name = arg
201 def mark(func, *a, **kw):
201 def mark(func, *a, **kw):
202 record_magic(magics, magic_kind, name, func.func_name)
202 record_magic(magics, magic_kind, name, func.func_name)
203 return decorator(call, func)
203 return decorator(call, func)
204 retval = mark
204 retval = mark
205 else:
205 else:
206 raise TypeError("Decorator can only be called with "
206 raise TypeError("Decorator can only be called with "
207 "string or function")
207 "string or function")
208 return retval
208 return retval
209
209
210 # Ensure the resulting decorator has a usable docstring
210 # Ensure the resulting decorator has a usable docstring
211 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
211 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
212 return magic_deco
212 return magic_deco
213
213
214
214
215 def _function_magic_marker(magic_kind):
215 def _function_magic_marker(magic_kind):
216 """Decorator factory for standalone functions.
216 """Decorator factory for standalone functions.
217 """
217 """
218 validate_type(magic_kind)
218 validate_type(magic_kind)
219
219
220 # This is a closure to capture the magic_kind. We could also use a class,
220 # This is a closure to capture the magic_kind. We could also use a class,
221 # but it's overkill for just that one bit of state.
221 # but it's overkill for just that one bit of state.
222 def magic_deco(arg):
222 def magic_deco(arg):
223 call = lambda f, *a, **k: f(*a, **k)
223 call = lambda f, *a, **k: f(*a, **k)
224
224
225 # Find get_ipython() in the caller's namespace
225 # Find get_ipython() in the caller's namespace
226 caller = sys._getframe(1)
226 caller = sys._getframe(1)
227 for ns in ['f_locals', 'f_globals', 'f_builtins']:
227 for ns in ['f_locals', 'f_globals', 'f_builtins']:
228 get_ipython = getattr(caller, ns).get('get_ipython')
228 get_ipython = getattr(caller, ns).get('get_ipython')
229 if get_ipython is not None:
229 if get_ipython is not None:
230 break
230 break
231 else:
231 else:
232 raise NameError('Decorator can only run in context where '
232 raise NameError('Decorator can only run in context where '
233 '`get_ipython` exists')
233 '`get_ipython` exists')
234
234
235 ip = get_ipython()
235 ip = get_ipython()
236
236
237 if callable(arg):
237 if callable(arg):
238 # "Naked" decorator call (just @foo, no args)
238 # "Naked" decorator call (just @foo, no args)
239 func = arg
239 func = arg
240 name = func.func_name
240 name = func.func_name
241 ip.register_magic_function(func, magic_kind, name)
241 ip.register_magic_function(func, magic_kind, name)
242 retval = decorator(call, func)
242 retval = decorator(call, func)
243 elif isinstance(arg, basestring):
243 elif isinstance(arg, basestring):
244 # Decorator called with arguments (@foo('bar'))
244 # Decorator called with arguments (@foo('bar'))
245 name = arg
245 name = arg
246 def mark(func, *a, **kw):
246 def mark(func, *a, **kw):
247 ip.register_magic_function(func, magic_kind, name)
247 ip.register_magic_function(func, magic_kind, name)
248 return decorator(call, func)
248 return decorator(call, func)
249 retval = mark
249 retval = mark
250 else:
250 else:
251 raise TypeError("Decorator can only be called with "
251 raise TypeError("Decorator can only be called with "
252 "string or function")
252 "string or function")
253 return retval
253 return retval
254
254
255 # Ensure the resulting decorator has a usable docstring
255 # Ensure the resulting decorator has a usable docstring
256 ds = _docstring_template.format('function', magic_kind)
256 ds = _docstring_template.format('function', magic_kind)
257
257
258 ds += dedent("""
258 ds += dedent("""
259 Note: this decorator can only be used in a context where IPython is already
259 Note: this decorator can only be used in a context where IPython is already
260 active, so that the `get_ipython()` call succeeds. You can therefore use
260 active, so that the `get_ipython()` call succeeds. You can therefore use
261 it in your startup files loaded after IPython initializes, but *not* in the
261 it in your startup files loaded after IPython initializes, but *not* in the
262 IPython configuration file itself, which is executed before IPython is
262 IPython configuration file itself, which is executed before IPython is
263 fully up and running. Any file located in the `startup` subdirectory of
263 fully up and running. Any file located in the `startup` subdirectory of
264 your configuration profile will be OK in this sense.
264 your configuration profile will be OK in this sense.
265 """)
265 """)
266
266
267 magic_deco.__doc__ = ds
267 magic_deco.__doc__ = ds
268 return magic_deco
268 return magic_deco
269
269
270
270
271 # Create the actual decorators for public use
271 # Create the actual decorators for public use
272
272
273 # These three are used to decorate methods in class definitions
273 # These three are used to decorate methods in class definitions
274 line_magic = _method_magic_marker('line')
274 line_magic = _method_magic_marker('line')
275 cell_magic = _method_magic_marker('cell')
275 cell_magic = _method_magic_marker('cell')
276 line_cell_magic = _method_magic_marker('line_cell')
276 line_cell_magic = _method_magic_marker('line_cell')
277
277
278 # These three decorate standalone functions and perform the decoration
278 # These three decorate standalone functions and perform the decoration
279 # immediately. They can only run where get_ipython() works
279 # immediately. They can only run where get_ipython() works
280 register_line_magic = _function_magic_marker('line')
280 register_line_magic = _function_magic_marker('line')
281 register_cell_magic = _function_magic_marker('cell')
281 register_cell_magic = _function_magic_marker('cell')
282 register_line_cell_magic = _function_magic_marker('line_cell')
282 register_line_cell_magic = _function_magic_marker('line_cell')
283
283
284 #-----------------------------------------------------------------------------
284 #-----------------------------------------------------------------------------
285 # Core Magic classes
285 # Core Magic classes
286 #-----------------------------------------------------------------------------
286 #-----------------------------------------------------------------------------
287
287
288 class MagicsManager(Configurable):
288 class MagicsManager(Configurable):
289 """Object that handles all magic-related functionality for IPython.
289 """Object that handles all magic-related functionality for IPython.
290 """
290 """
291 # Non-configurable class attributes
291 # Non-configurable class attributes
292
292
293 # A two-level dict, first keyed by magic type, then by magic function, and
293 # A two-level dict, first keyed by magic type, then by magic function, and
294 # holding the actual callable object as value. This is the dict used for
294 # holding the actual callable object as value. This is the dict used for
295 # magic function dispatch
295 # magic function dispatch
296 magics = Dict
296 magics = Dict
297
297
298 # A registry of the original objects that we've been given holding magics.
298 # A registry of the original objects that we've been given holding magics.
299 registry = Dict
299 registry = Dict
300
300
301 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
301 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
302
302
303 auto_magic = Bool(True, config=True, help=
303 auto_magic = Bool(True, config=True, help=
304 "Automatically call line magics without requiring explicit % prefix")
304 "Automatically call line magics without requiring explicit % prefix")
305
305
306 _auto_status = [
306 _auto_status = [
307 'Automagic is OFF, % prefix IS needed for line magics.',
307 'Automagic is OFF, % prefix IS needed for line magics.',
308 'Automagic is ON, % prefix IS NOT needed for line magics.']
308 'Automagic is ON, % prefix IS NOT needed for line magics.']
309
309
310 user_magics = Instance('IPython.core.magics.UserMagics')
310 user_magics = Instance('IPython.core.magics.UserMagics')
311
311
312 def __init__(self, shell=None, config=None, user_magics=None, **traits):
312 def __init__(self, shell=None, config=None, user_magics=None, **traits):
313
313
314 super(MagicsManager, self).__init__(shell=shell, config=config,
314 super(MagicsManager, self).__init__(shell=shell, config=config,
315 user_magics=user_magics, **traits)
315 user_magics=user_magics, **traits)
316 self.magics = dict(line={}, cell={})
316 self.magics = dict(line={}, cell={})
317 # Let's add the user_magics to the registry for uniformity, so *all*
317 # Let's add the user_magics to the registry for uniformity, so *all*
318 # registered magic containers can be found there.
318 # registered magic containers can be found there.
319 self.registry[user_magics.__class__.__name__] = user_magics
319 self.registry[user_magics.__class__.__name__] = user_magics
320
320
321 def auto_status(self):
321 def auto_status(self):
322 """Return descriptive string with automagic status."""
322 """Return descriptive string with automagic status."""
323 return self._auto_status[self.auto_magic]
323 return self._auto_status[self.auto_magic]
324
324
325 def lsmagic_info(self):
325 def lsmagic_info(self):
326 magic_list = []
326 magic_list = []
327 for m_type in self.magics :
327 for m_type in self.magics :
328 for m_name,mgc in self.magics[m_type].items():
328 for m_name,mgc in self.magics[m_type].items():
329 try :
329 try :
330 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
330 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
331 except AttributeError :
331 except AttributeError :
332 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
332 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
333 return magic_list
333 return magic_list
334
334
335 def lsmagic(self):
335 def lsmagic(self):
336 """Return a dict of currently available magic functions.
336 """Return a dict of currently available magic functions.
337
337
338 The return dict has the keys 'line' and 'cell', corresponding to the
338 The return dict has the keys 'line' and 'cell', corresponding to the
339 two types of magics we support. Each value is a list of names.
339 two types of magics we support. Each value is a list of names.
340 """
340 """
341 return self.magics
341 return self.magics
342
342
343 def lsmagic_docs(self, brief=False, missing=''):
344 """Return dict of documentation of magic functions.
345
346 The return dict has the keys 'line' and 'cell', corresponding to the
347 two types of magics we support. Each value is a dict keyed by magic
348 name whose value is the function docstring. If a docstring is
349 unavailable, the value of `missing` is used instead.
350
351 If brief is True, only the first line of each docstring will be returned.
352 """
353 docs = {}
354 for m_type in self.magics:
355 m_docs = {}
356 for m_name, m_func in self.magics[m_type].iteritems():
357 if m_func.__doc__:
358 if brief:
359 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
360 else:
361 m_docs[m_name] = m_func.__doc__.rstrip()
362 else:
363 m_docs[m_name] = missing
364 docs[m_type] = m_docs
365 return docs
366
343 def register(self, *magic_objects):
367 def register(self, *magic_objects):
344 """Register one or more instances of Magics.
368 """Register one or more instances of Magics.
345
369
346 Take one or more classes or instances of classes that subclass the main
370 Take one or more classes or instances of classes that subclass the main
347 `core.Magic` class, and register them with IPython to use the magic
371 `core.Magic` class, and register them with IPython to use the magic
348 functions they provide. The registration process will then ensure that
372 functions they provide. The registration process will then ensure that
349 any methods that have decorated to provide line and/or cell magics will
373 any methods that have decorated to provide line and/or cell magics will
350 be recognized with the `%x`/`%%x` syntax as a line/cell magic
374 be recognized with the `%x`/`%%x` syntax as a line/cell magic
351 respectively.
375 respectively.
352
376
353 If classes are given, they will be instantiated with the default
377 If classes are given, they will be instantiated with the default
354 constructor. If your classes need a custom constructor, you should
378 constructor. If your classes need a custom constructor, you should
355 instanitate them first and pass the instance.
379 instanitate them first and pass the instance.
356
380
357 The provided arguments can be an arbitrary mix of classes and instances.
381 The provided arguments can be an arbitrary mix of classes and instances.
358
382
359 Parameters
383 Parameters
360 ----------
384 ----------
361 magic_objects : one or more classes or instances
385 magic_objects : one or more classes or instances
362 """
386 """
363 # Start by validating them to ensure they have all had their magic
387 # Start by validating them to ensure they have all had their magic
364 # methods registered at the instance level
388 # methods registered at the instance level
365 for m in magic_objects:
389 for m in magic_objects:
366 if not m.registered:
390 if not m.registered:
367 raise ValueError("Class of magics %r was constructed without "
391 raise ValueError("Class of magics %r was constructed without "
368 "the @register_magics class decorator")
392 "the @register_magics class decorator")
369 if type(m) in (type, MetaHasTraits):
393 if type(m) in (type, MetaHasTraits):
370 # If we're given an uninstantiated class
394 # If we're given an uninstantiated class
371 m = m(shell=self.shell)
395 m = m(shell=self.shell)
372
396
373 # Now that we have an instance, we can register it and update the
397 # Now that we have an instance, we can register it and update the
374 # table of callables
398 # table of callables
375 self.registry[m.__class__.__name__] = m
399 self.registry[m.__class__.__name__] = m
376 for mtype in magic_kinds:
400 for mtype in magic_kinds:
377 self.magics[mtype].update(m.magics[mtype])
401 self.magics[mtype].update(m.magics[mtype])
378
402
379 def register_function(self, func, magic_kind='line', magic_name=None):
403 def register_function(self, func, magic_kind='line', magic_name=None):
380 """Expose a standalone function as magic function for IPython.
404 """Expose a standalone function as magic function for IPython.
381
405
382 This will create an IPython magic (line, cell or both) from a
406 This will create an IPython magic (line, cell or both) from a
383 standalone function. The functions should have the following
407 standalone function. The functions should have the following
384 signatures:
408 signatures:
385
409
386 * For line magics: `def f(line)`
410 * For line magics: `def f(line)`
387 * For cell magics: `def f(line, cell)`
411 * For cell magics: `def f(line, cell)`
388 * For a function that does both: `def f(line, cell=None)`
412 * For a function that does both: `def f(line, cell=None)`
389
413
390 In the latter case, the function will be called with `cell==None` when
414 In the latter case, the function will be called with `cell==None` when
391 invoked as `%f`, and with cell as a string when invoked as `%%f`.
415 invoked as `%f`, and with cell as a string when invoked as `%%f`.
392
416
393 Parameters
417 Parameters
394 ----------
418 ----------
395 func : callable
419 func : callable
396 Function to be registered as a magic.
420 Function to be registered as a magic.
397
421
398 magic_kind : str
422 magic_kind : str
399 Kind of magic, one of 'line', 'cell' or 'line_cell'
423 Kind of magic, one of 'line', 'cell' or 'line_cell'
400
424
401 magic_name : optional str
425 magic_name : optional str
402 If given, the name the magic will have in the IPython namespace. By
426 If given, the name the magic will have in the IPython namespace. By
403 default, the name of the function itself is used.
427 default, the name of the function itself is used.
404 """
428 """
405
429
406 # Create the new method in the user_magics and register it in the
430 # Create the new method in the user_magics and register it in the
407 # global table
431 # global table
408 validate_type(magic_kind)
432 validate_type(magic_kind)
409 magic_name = func.func_name if magic_name is None else magic_name
433 magic_name = func.func_name if magic_name is None else magic_name
410 setattr(self.user_magics, magic_name, func)
434 setattr(self.user_magics, magic_name, func)
411 record_magic(self.magics, magic_kind, magic_name, func)
435 record_magic(self.magics, magic_kind, magic_name, func)
412
436
413 def define_magic(self, name, func):
437 def define_magic(self, name, func):
414 """[Deprecated] Expose own function as magic function for IPython.
438 """[Deprecated] Expose own function as magic function for IPython.
415
439
416 Example::
440 Example::
417
441
418 def foo_impl(self, parameter_s=''):
442 def foo_impl(self, parameter_s=''):
419 'My very own magic!. (Use docstrings, IPython reads them).'
443 'My very own magic!. (Use docstrings, IPython reads them).'
420 print 'Magic function. Passed parameter is between < >:'
444 print 'Magic function. Passed parameter is between < >:'
421 print '<%s>' % parameter_s
445 print '<%s>' % parameter_s
422 print 'The self object is:', self
446 print 'The self object is:', self
423
447
424 ip.define_magic('foo',foo_impl)
448 ip.define_magic('foo',foo_impl)
425 """
449 """
426 meth = types.MethodType(func, self.user_magics)
450 meth = types.MethodType(func, self.user_magics)
427 setattr(self.user_magics, name, meth)
451 setattr(self.user_magics, name, meth)
428 record_magic(self.magics, 'line', name, meth)
452 record_magic(self.magics, 'line', name, meth)
429
453
430 # Key base class that provides the central functionality for magics.
454 # Key base class that provides the central functionality for magics.
431
455
432 class Magics(object):
456 class Magics(object):
433 """Base class for implementing magic functions.
457 """Base class for implementing magic functions.
434
458
435 Shell functions which can be reached as %function_name. All magic
459 Shell functions which can be reached as %function_name. All magic
436 functions should accept a string, which they can parse for their own
460 functions should accept a string, which they can parse for their own
437 needs. This can make some functions easier to type, eg `%cd ../`
461 needs. This can make some functions easier to type, eg `%cd ../`
438 vs. `%cd("../")`
462 vs. `%cd("../")`
439
463
440 Classes providing magic functions need to subclass this class, and they
464 Classes providing magic functions need to subclass this class, and they
441 MUST:
465 MUST:
442
466
443 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
467 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
444 individual methods as magic functions, AND
468 individual methods as magic functions, AND
445
469
446 - Use the class decorator `@magics_class` to ensure that the magic
470 - Use the class decorator `@magics_class` to ensure that the magic
447 methods are properly registered at the instance level upon instance
471 methods are properly registered at the instance level upon instance
448 initialization.
472 initialization.
449
473
450 See :mod:`magic_functions` for examples of actual implementation classes.
474 See :mod:`magic_functions` for examples of actual implementation classes.
451 """
475 """
452 # Dict holding all command-line options for each magic.
476 # Dict holding all command-line options for each magic.
453 options_table = None
477 options_table = None
454 # Dict for the mapping of magic names to methods, set by class decorator
478 # Dict for the mapping of magic names to methods, set by class decorator
455 magics = None
479 magics = None
456 # Flag to check that the class decorator was properly applied
480 # Flag to check that the class decorator was properly applied
457 registered = False
481 registered = False
458 # Instance of IPython shell
482 # Instance of IPython shell
459 shell = None
483 shell = None
460
484
461 def __init__(self, shell):
485 def __init__(self, shell):
462 if not(self.__class__.registered):
486 if not(self.__class__.registered):
463 raise ValueError('Magics subclass without registration - '
487 raise ValueError('Magics subclass without registration - '
464 'did you forget to apply @magics_class?')
488 'did you forget to apply @magics_class?')
465 self.shell = shell
489 self.shell = shell
466 self.options_table = {}
490 self.options_table = {}
467 # The method decorators are run when the instance doesn't exist yet, so
491 # The method decorators are run when the instance doesn't exist yet, so
468 # they can only record the names of the methods they are supposed to
492 # they can only record the names of the methods they are supposed to
469 # grab. Only now, that the instance exists, can we create the proper
493 # grab. Only now, that the instance exists, can we create the proper
470 # mapping to bound methods. So we read the info off the original names
494 # mapping to bound methods. So we read the info off the original names
471 # table and replace each method name by the actual bound method.
495 # table and replace each method name by the actual bound method.
472 # But we mustn't clobber the *class* mapping, in case of multiple instances.
496 # But we mustn't clobber the *class* mapping, in case of multiple instances.
473 class_magics = self.magics
497 class_magics = self.magics
474 self.magics = {}
498 self.magics = {}
475 for mtype in magic_kinds:
499 for mtype in magic_kinds:
476 tab = self.magics[mtype] = {}
500 tab = self.magics[mtype] = {}
477 cls_tab = class_magics[mtype]
501 cls_tab = class_magics[mtype]
478 for magic_name, meth_name in cls_tab.iteritems():
502 for magic_name, meth_name in cls_tab.iteritems():
479 if isinstance(meth_name, basestring):
503 if isinstance(meth_name, basestring):
480 # it's a method name, grab it
504 # it's a method name, grab it
481 tab[magic_name] = getattr(self, meth_name)
505 tab[magic_name] = getattr(self, meth_name)
482 else:
506 else:
483 # it's the real thing
507 # it's the real thing
484 tab[magic_name] = meth_name
508 tab[magic_name] = meth_name
485
509
486 def arg_err(self,func):
510 def arg_err(self,func):
487 """Print docstring if incorrect arguments were passed"""
511 """Print docstring if incorrect arguments were passed"""
488 print 'Error in arguments:'
512 print 'Error in arguments:'
489 print oinspect.getdoc(func)
513 print oinspect.getdoc(func)
490
514
491 def format_latex(self, strng):
515 def format_latex(self, strng):
492 """Format a string for latex inclusion."""
516 """Format a string for latex inclusion."""
493
517
494 # Characters that need to be escaped for latex:
518 # Characters that need to be escaped for latex:
495 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
519 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
496 # Magic command names as headers:
520 # Magic command names as headers:
497 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
521 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
498 re.MULTILINE)
522 re.MULTILINE)
499 # Magic commands
523 # Magic commands
500 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
524 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
501 re.MULTILINE)
525 re.MULTILINE)
502 # Paragraph continue
526 # Paragraph continue
503 par_re = re.compile(r'\\$',re.MULTILINE)
527 par_re = re.compile(r'\\$',re.MULTILINE)
504
528
505 # The "\n" symbol
529 # The "\n" symbol
506 newline_re = re.compile(r'\\n')
530 newline_re = re.compile(r'\\n')
507
531
508 # Now build the string for output:
532 # Now build the string for output:
509 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
533 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
510 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
534 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
511 strng)
535 strng)
512 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
536 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
513 strng = par_re.sub(r'\\\\',strng)
537 strng = par_re.sub(r'\\\\',strng)
514 strng = escape_re.sub(r'\\\1',strng)
538 strng = escape_re.sub(r'\\\1',strng)
515 strng = newline_re.sub(r'\\textbackslash{}n',strng)
539 strng = newline_re.sub(r'\\textbackslash{}n',strng)
516 return strng
540 return strng
517
541
518 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
542 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
519 """Parse options passed to an argument string.
543 """Parse options passed to an argument string.
520
544
521 The interface is similar to that of getopt(), but it returns back a
545 The interface is similar to that of getopt(), but it returns back a
522 Struct with the options as keys and the stripped argument string still
546 Struct with the options as keys and the stripped argument string still
523 as a string.
547 as a string.
524
548
525 arg_str is quoted as a true sys.argv vector by using shlex.split.
549 arg_str is quoted as a true sys.argv vector by using shlex.split.
526 This allows us to easily expand variables, glob files, quote
550 This allows us to easily expand variables, glob files, quote
527 arguments, etc.
551 arguments, etc.
528
552
529 Options:
553 Options:
530 -mode: default 'string'. If given as 'list', the argument string is
554 -mode: default 'string'. If given as 'list', the argument string is
531 returned as a list (split on whitespace) instead of a string.
555 returned as a list (split on whitespace) instead of a string.
532
556
533 -list_all: put all option values in lists. Normally only options
557 -list_all: put all option values in lists. Normally only options
534 appearing more than once are put in a list.
558 appearing more than once are put in a list.
535
559
536 -posix (True): whether to split the input line in POSIX mode or not,
560 -posix (True): whether to split the input line in POSIX mode or not,
537 as per the conventions outlined in the shlex module from the
561 as per the conventions outlined in the shlex module from the
538 standard library."""
562 standard library."""
539
563
540 # inject default options at the beginning of the input line
564 # inject default options at the beginning of the input line
541 caller = sys._getframe(1).f_code.co_name
565 caller = sys._getframe(1).f_code.co_name
542 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
566 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
543
567
544 mode = kw.get('mode','string')
568 mode = kw.get('mode','string')
545 if mode not in ['string','list']:
569 if mode not in ['string','list']:
546 raise ValueError,'incorrect mode given: %s' % mode
570 raise ValueError,'incorrect mode given: %s' % mode
547 # Get options
571 # Get options
548 list_all = kw.get('list_all',0)
572 list_all = kw.get('list_all',0)
549 posix = kw.get('posix', os.name == 'posix')
573 posix = kw.get('posix', os.name == 'posix')
550 strict = kw.get('strict', True)
574 strict = kw.get('strict', True)
551
575
552 # Check if we have more than one argument to warrant extra processing:
576 # Check if we have more than one argument to warrant extra processing:
553 odict = {} # Dictionary with options
577 odict = {} # Dictionary with options
554 args = arg_str.split()
578 args = arg_str.split()
555 if len(args) >= 1:
579 if len(args) >= 1:
556 # If the list of inputs only has 0 or 1 thing in it, there's no
580 # If the list of inputs only has 0 or 1 thing in it, there's no
557 # need to look for options
581 # need to look for options
558 argv = arg_split(arg_str, posix, strict)
582 argv = arg_split(arg_str, posix, strict)
559 # Do regular option processing
583 # Do regular option processing
560 try:
584 try:
561 opts,args = getopt(argv, opt_str, long_opts)
585 opts,args = getopt(argv, opt_str, long_opts)
562 except GetoptError,e:
586 except GetoptError,e:
563 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
587 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
564 " ".join(long_opts)))
588 " ".join(long_opts)))
565 for o,a in opts:
589 for o,a in opts:
566 if o.startswith('--'):
590 if o.startswith('--'):
567 o = o[2:]
591 o = o[2:]
568 else:
592 else:
569 o = o[1:]
593 o = o[1:]
570 try:
594 try:
571 odict[o].append(a)
595 odict[o].append(a)
572 except AttributeError:
596 except AttributeError:
573 odict[o] = [odict[o],a]
597 odict[o] = [odict[o],a]
574 except KeyError:
598 except KeyError:
575 if list_all:
599 if list_all:
576 odict[o] = [a]
600 odict[o] = [a]
577 else:
601 else:
578 odict[o] = a
602 odict[o] = a
579
603
580 # Prepare opts,args for return
604 # Prepare opts,args for return
581 opts = Struct(odict)
605 opts = Struct(odict)
582 if mode == 'string':
606 if mode == 'string':
583 args = ' '.join(args)
607 args = ' '.join(args)
584
608
585 return opts,args
609 return opts,args
586
610
587 def default_option(self, fn, optstr):
611 def default_option(self, fn, optstr):
588 """Make an entry in the options_table for fn, with value optstr"""
612 """Make an entry in the options_table for fn, with value optstr"""
589
613
590 if fn not in self.lsmagic():
614 if fn not in self.lsmagic():
591 error("%s is not a magic function" % fn)
615 error("%s is not a magic function" % fn)
592 self.options_table[fn] = optstr
616 self.options_table[fn] = optstr
@@ -1,538 +1,526 b''
1 """Implementation of basic magic functions.
1 """Implementation of basic magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
14 from __future__ import print_function
15
15
16 # Stdlib
16 # Stdlib
17 import io
17 import io
18 import sys
18 import sys
19 from pprint import pformat
19 from pprint import pformat
20
20
21 # Our own packages
21 # Our own packages
22 from IPython.core.error import UsageError
22 from IPython.core.error import UsageError
23 from IPython.core.inputsplitter import ESC_MAGIC
23 from IPython.core.inputsplitter import ESC_MAGIC
24 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.core.magic import Magics, magics_class, line_magic
25 from IPython.utils.text import format_screen
25 from IPython.utils.text import format_screen
26 from IPython.core import magic_arguments, page
26 from IPython.core import magic_arguments, page
27 from IPython.testing.skipdoctest import skip_doctest
27 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils.ipstruct import Struct
28 from IPython.utils.ipstruct import Struct
29 from IPython.utils.path import unquote_filename
29 from IPython.utils.path import unquote_filename
30 from IPython.utils.warn import warn, error
30 from IPython.utils.warn import warn, error
31
31
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Magics class implementation
33 # Magics class implementation
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 @magics_class
36 @magics_class
37 class BasicMagics(Magics):
37 class BasicMagics(Magics):
38 """Magics that provide central IPython functionality.
38 """Magics that provide central IPython functionality.
39
39
40 These are various magics that don't fit into specific categories but that
40 These are various magics that don't fit into specific categories but that
41 are all part of the base 'IPython experience'."""
41 are all part of the base 'IPython experience'."""
42
42
43 def _lsmagic(self):
43 def _lsmagic(self):
44 mesc = ESC_MAGIC
44 mesc = ESC_MAGIC
45 cesc = mesc*2
45 cesc = mesc*2
46 mman = self.shell.magics_manager
46 mman = self.shell.magics_manager
47 magics = mman.lsmagic()
47 magics = mman.lsmagic()
48 out = ['Available line magics:',
48 out = ['Available line magics:',
49 mesc + (' '+mesc).join(sorted(magics['line'])),
49 mesc + (' '+mesc).join(sorted(magics['line'])),
50 '',
50 '',
51 'Available cell magics:',
51 'Available cell magics:',
52 cesc + (' '+cesc).join(sorted(magics['cell'])),
52 cesc + (' '+cesc).join(sorted(magics['cell'])),
53 '',
53 '',
54 mman.auto_status()]
54 mman.auto_status()]
55 return '\n'.join(out)
55 return '\n'.join(out)
56
56
57 @line_magic
57 @line_magic
58 def lsmagic(self, parameter_s=''):
58 def lsmagic(self, parameter_s=''):
59 """List currently available magic functions."""
59 """List currently available magic functions."""
60 print(self._lsmagic())
60 print(self._lsmagic())
61
61
62 def _magic_docs(self, brief=False, rest=False):
63 """Return docstrings from magic functions."""
64 mman = self.shell.magics_manager
65 docs = mman.lsmagic_docs(brief, missing='No documentation')
66
67 if rest:
68 format_string = '**%s%s**::\n\n\t%s\n\n'
69 else:
70 format_string = '%s%s:\n\t%s\n'
71
72 return ''.join(
73 [format_string % (ESC_MAGIC, fname, fndoc)
74 for fname, fndoc in sorted(docs['line'].items())]
75 +
76 [format_string % (ESC_MAGIC*2, fname, fndoc)
77 for fname, fndoc in sorted(docs['cell'].items())]
78 )
79
62 @line_magic
80 @line_magic
63 def magic(self, parameter_s=''):
81 def magic(self, parameter_s=''):
64 """Print information about the magic function system.
82 """Print information about the magic function system.
65
83
66 Supported formats: -latex, -brief, -rest
84 Supported formats: -latex, -brief, -rest
67 """
85 """
68
86
69 mode = ''
87 mode = ''
70 try:
88 try:
71 mode = parameter_s.split()[0][1:]
89 mode = parameter_s.split()[0][1:]
72 if mode == 'rest':
90 if mode == 'rest':
73 rest_docs = []
91 rest_docs = []
74 except IndexError:
92 except IndexError:
75 pass
93 pass
76
94
77 magic_docs = []
95 brief = (mode == 'brief')
78 escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2)
96 rest = (mode == 'rest')
79 magics = self.shell.magics_manager.magics
97 magic_docs = self._magic_docs(brief, rest)
80
81 for mtype in ('line', 'cell'):
82 escape = escapes[mtype]
83 for fname, fn in sorted(magics[mtype].items()):
84
85 if mode == 'brief':
86 # only first line
87 if fn.__doc__:
88 fndoc = fn.__doc__.split('\n',1)[0]
89 else:
90 fndoc = 'No documentation'
91 else:
92 if fn.__doc__:
93 fndoc = fn.__doc__.rstrip()
94 else:
95 fndoc = 'No documentation'
96
97 if mode == 'rest':
98 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %
99 (escape, fname, fndoc))
100 else:
101 magic_docs.append('%s%s:\n\t%s\n' %
102 (escape, fname, fndoc))
103
104 magic_docs = ''.join(magic_docs)
105
106 if mode == 'rest':
107 return "".join(rest_docs)
108
98
109 if mode == 'latex':
99 if mode == 'latex':
110 print(self.format_latex(magic_docs))
100 print(self.format_latex(magic_docs))
111 return
101 return
112 else:
102 else:
113 magic_docs = format_screen(magic_docs)
103 magic_docs = format_screen(magic_docs)
114 if mode == 'brief':
115 return magic_docs
116
104
117 out = ["""
105 out = ["""
118 IPython's 'magic' functions
106 IPython's 'magic' functions
119 ===========================
107 ===========================
120
108
121 The magic function system provides a series of functions which allow you to
109 The magic function system provides a series of functions which allow you to
122 control the behavior of IPython itself, plus a lot of system-type
110 control the behavior of IPython itself, plus a lot of system-type
123 features. There are two kinds of magics, line-oriented and cell-oriented.
111 features. There are two kinds of magics, line-oriented and cell-oriented.
124
112
125 Line magics are prefixed with the % character and work much like OS
113 Line magics are prefixed with the % character and work much like OS
126 command-line calls: they get as an argument the rest of the line, where
114 command-line calls: they get as an argument the rest of the line, where
127 arguments are passed without parentheses or quotes. For example, this will
115 arguments are passed without parentheses or quotes. For example, this will
128 time the given statement::
116 time the given statement::
129
117
130 %timeit range(1000)
118 %timeit range(1000)
131
119
132 Cell magics are prefixed with a double %%, and they are functions that get as
120 Cell magics are prefixed with a double %%, and they are functions that get as
133 an argument not only the rest of the line, but also the lines below it in a
121 an argument not only the rest of the line, but also the lines below it in a
134 separate argument. These magics are called with two arguments: the rest of the
122 separate argument. These magics are called with two arguments: the rest of the
135 call line and the body of the cell, consisting of the lines below the first.
123 call line and the body of the cell, consisting of the lines below the first.
136 For example::
124 For example::
137
125
138 %%timeit x = numpy.random.randn((100, 100))
126 %%timeit x = numpy.random.randn((100, 100))
139 numpy.linalg.svd(x)
127 numpy.linalg.svd(x)
140
128
141 will time the execution of the numpy svd routine, running the assignment of x
129 will time the execution of the numpy svd routine, running the assignment of x
142 as part of the setup phase, which is not timed.
130 as part of the setup phase, which is not timed.
143
131
144 In a line-oriented client (the terminal or Qt console IPython), starting a new
132 In a line-oriented client (the terminal or Qt console IPython), starting a new
145 input with %% will automatically enter cell mode, and IPython will continue
133 input with %% will automatically enter cell mode, and IPython will continue
146 reading input until a blank line is given. In the notebook, simply type the
134 reading input until a blank line is given. In the notebook, simply type the
147 whole cell as one entity, but keep in mind that the %% escape can only be at
135 whole cell as one entity, but keep in mind that the %% escape can only be at
148 the very start of the cell.
136 the very start of the cell.
149
137
150 NOTE: If you have 'automagic' enabled (via the command line option or with the
138 NOTE: If you have 'automagic' enabled (via the command line option or with the
151 %automagic function), you don't need to type in the % explicitly for line
139 %automagic function), you don't need to type in the % explicitly for line
152 magics; cell magics always require an explicit '%%' escape. By default,
140 magics; cell magics always require an explicit '%%' escape. By default,
153 IPython ships with automagic on, so you should only rarely need the % escape.
141 IPython ships with automagic on, so you should only rarely need the % escape.
154
142
155 Example: typing '%cd mydir' (without the quotes) changes you working directory
143 Example: typing '%cd mydir' (without the quotes) changes you working directory
156 to 'mydir', if it exists.
144 to 'mydir', if it exists.
157
145
158 For a list of the available magic functions, use %lsmagic. For a description
146 For a list of the available magic functions, use %lsmagic. For a description
159 of any of them, type %magic_name?, e.g. '%cd?'.
147 of any of them, type %magic_name?, e.g. '%cd?'.
160
148
161 Currently the magic system has the following functions:""",
149 Currently the magic system has the following functions:""",
162 magic_docs,
150 magic_docs,
163 "Summary of magic functions (from %slsmagic):",
151 "Summary of magic functions (from %slsmagic):",
164 self._lsmagic(),
152 self._lsmagic(),
165 ]
153 ]
166 page.page('\n'.join(out))
154 page.page('\n'.join(out))
167
155
168
156
169 @line_magic
157 @line_magic
170 def page(self, parameter_s=''):
158 def page(self, parameter_s=''):
171 """Pretty print the object and display it through a pager.
159 """Pretty print the object and display it through a pager.
172
160
173 %page [options] OBJECT
161 %page [options] OBJECT
174
162
175 If no object is given, use _ (last output).
163 If no object is given, use _ (last output).
176
164
177 Options:
165 Options:
178
166
179 -r: page str(object), don't pretty-print it."""
167 -r: page str(object), don't pretty-print it."""
180
168
181 # After a function contributed by Olivier Aubert, slightly modified.
169 # After a function contributed by Olivier Aubert, slightly modified.
182
170
183 # Process options/args
171 # Process options/args
184 opts, args = self.parse_options(parameter_s, 'r')
172 opts, args = self.parse_options(parameter_s, 'r')
185 raw = 'r' in opts
173 raw = 'r' in opts
186
174
187 oname = args and args or '_'
175 oname = args and args or '_'
188 info = self.shell._ofind(oname)
176 info = self.shell._ofind(oname)
189 if info['found']:
177 if info['found']:
190 txt = (raw and str or pformat)( info['obj'] )
178 txt = (raw and str or pformat)( info['obj'] )
191 page.page(txt)
179 page.page(txt)
192 else:
180 else:
193 print('Object `%s` not found' % oname)
181 print('Object `%s` not found' % oname)
194
182
195 @line_magic
183 @line_magic
196 def profile(self, parameter_s=''):
184 def profile(self, parameter_s=''):
197 """Print your currently active IPython profile."""
185 """Print your currently active IPython profile."""
198 from IPython.core.application import BaseIPythonApplication
186 from IPython.core.application import BaseIPythonApplication
199 if BaseIPythonApplication.initialized():
187 if BaseIPythonApplication.initialized():
200 print(BaseIPythonApplication.instance().profile)
188 print(BaseIPythonApplication.instance().profile)
201 else:
189 else:
202 error("profile is an application-level value, but you don't appear to be in an IPython application")
190 error("profile is an application-level value, but you don't appear to be in an IPython application")
203
191
204 @line_magic
192 @line_magic
205 def pprint(self, parameter_s=''):
193 def pprint(self, parameter_s=''):
206 """Toggle pretty printing on/off."""
194 """Toggle pretty printing on/off."""
207 ptformatter = self.shell.display_formatter.formatters['text/plain']
195 ptformatter = self.shell.display_formatter.formatters['text/plain']
208 ptformatter.pprint = bool(1 - ptformatter.pprint)
196 ptformatter.pprint = bool(1 - ptformatter.pprint)
209 print('Pretty printing has been turned',
197 print('Pretty printing has been turned',
210 ['OFF','ON'][ptformatter.pprint])
198 ['OFF','ON'][ptformatter.pprint])
211
199
212 @line_magic
200 @line_magic
213 def colors(self, parameter_s=''):
201 def colors(self, parameter_s=''):
214 """Switch color scheme for prompts, info system and exception handlers.
202 """Switch color scheme for prompts, info system and exception handlers.
215
203
216 Currently implemented schemes: NoColor, Linux, LightBG.
204 Currently implemented schemes: NoColor, Linux, LightBG.
217
205
218 Color scheme names are not case-sensitive.
206 Color scheme names are not case-sensitive.
219
207
220 Examples
208 Examples
221 --------
209 --------
222 To get a plain black and white terminal::
210 To get a plain black and white terminal::
223
211
224 %colors nocolor
212 %colors nocolor
225 """
213 """
226 def color_switch_err(name):
214 def color_switch_err(name):
227 warn('Error changing %s color schemes.\n%s' %
215 warn('Error changing %s color schemes.\n%s' %
228 (name, sys.exc_info()[1]))
216 (name, sys.exc_info()[1]))
229
217
230
218
231 new_scheme = parameter_s.strip()
219 new_scheme = parameter_s.strip()
232 if not new_scheme:
220 if not new_scheme:
233 raise UsageError(
221 raise UsageError(
234 "%colors: you must specify a color scheme. See '%colors?'")
222 "%colors: you must specify a color scheme. See '%colors?'")
235 return
223 return
236 # local shortcut
224 # local shortcut
237 shell = self.shell
225 shell = self.shell
238
226
239 import IPython.utils.rlineimpl as readline
227 import IPython.utils.rlineimpl as readline
240
228
241 if not shell.colors_force and \
229 if not shell.colors_force and \
242 not readline.have_readline and sys.platform == "win32":
230 not readline.have_readline and sys.platform == "win32":
243 msg = """\
231 msg = """\
244 Proper color support under MS Windows requires the pyreadline library.
232 Proper color support under MS Windows requires the pyreadline library.
245 You can find it at:
233 You can find it at:
246 http://ipython.org/pyreadline.html
234 http://ipython.org/pyreadline.html
247 Gary's readline needs the ctypes module, from:
235 Gary's readline needs the ctypes module, from:
248 http://starship.python.net/crew/theller/ctypes
236 http://starship.python.net/crew/theller/ctypes
249 (Note that ctypes is already part of Python versions 2.5 and newer).
237 (Note that ctypes is already part of Python versions 2.5 and newer).
250
238
251 Defaulting color scheme to 'NoColor'"""
239 Defaulting color scheme to 'NoColor'"""
252 new_scheme = 'NoColor'
240 new_scheme = 'NoColor'
253 warn(msg)
241 warn(msg)
254
242
255 # readline option is 0
243 # readline option is 0
256 if not shell.colors_force and not shell.has_readline:
244 if not shell.colors_force and not shell.has_readline:
257 new_scheme = 'NoColor'
245 new_scheme = 'NoColor'
258
246
259 # Set prompt colors
247 # Set prompt colors
260 try:
248 try:
261 shell.prompt_manager.color_scheme = new_scheme
249 shell.prompt_manager.color_scheme = new_scheme
262 except:
250 except:
263 color_switch_err('prompt')
251 color_switch_err('prompt')
264 else:
252 else:
265 shell.colors = \
253 shell.colors = \
266 shell.prompt_manager.color_scheme_table.active_scheme_name
254 shell.prompt_manager.color_scheme_table.active_scheme_name
267 # Set exception colors
255 # Set exception colors
268 try:
256 try:
269 shell.InteractiveTB.set_colors(scheme = new_scheme)
257 shell.InteractiveTB.set_colors(scheme = new_scheme)
270 shell.SyntaxTB.set_colors(scheme = new_scheme)
258 shell.SyntaxTB.set_colors(scheme = new_scheme)
271 except:
259 except:
272 color_switch_err('exception')
260 color_switch_err('exception')
273
261
274 # Set info (for 'object?') colors
262 # Set info (for 'object?') colors
275 if shell.color_info:
263 if shell.color_info:
276 try:
264 try:
277 shell.inspector.set_active_scheme(new_scheme)
265 shell.inspector.set_active_scheme(new_scheme)
278 except:
266 except:
279 color_switch_err('object inspector')
267 color_switch_err('object inspector')
280 else:
268 else:
281 shell.inspector.set_active_scheme('NoColor')
269 shell.inspector.set_active_scheme('NoColor')
282
270
283 @line_magic
271 @line_magic
284 def xmode(self, parameter_s=''):
272 def xmode(self, parameter_s=''):
285 """Switch modes for the exception handlers.
273 """Switch modes for the exception handlers.
286
274
287 Valid modes: Plain, Context and Verbose.
275 Valid modes: Plain, Context and Verbose.
288
276
289 If called without arguments, acts as a toggle."""
277 If called without arguments, acts as a toggle."""
290
278
291 def xmode_switch_err(name):
279 def xmode_switch_err(name):
292 warn('Error changing %s exception modes.\n%s' %
280 warn('Error changing %s exception modes.\n%s' %
293 (name,sys.exc_info()[1]))
281 (name,sys.exc_info()[1]))
294
282
295 shell = self.shell
283 shell = self.shell
296 new_mode = parameter_s.strip().capitalize()
284 new_mode = parameter_s.strip().capitalize()
297 try:
285 try:
298 shell.InteractiveTB.set_mode(mode=new_mode)
286 shell.InteractiveTB.set_mode(mode=new_mode)
299 print('Exception reporting mode:',shell.InteractiveTB.mode)
287 print('Exception reporting mode:',shell.InteractiveTB.mode)
300 except:
288 except:
301 xmode_switch_err('user')
289 xmode_switch_err('user')
302
290
303 @line_magic
291 @line_magic
304 def quickref(self,arg):
292 def quickref(self,arg):
305 """ Show a quick reference sheet """
293 """ Show a quick reference sheet """
306 from IPython.core.usage import quick_reference
294 from IPython.core.usage import quick_reference
307 qr = quick_reference + self.magic('-brief')
295 qr = quick_reference + self._magic_docs(brief=True)
308 page.page(qr)
296 page.page(qr)
309
297
310 @line_magic
298 @line_magic
311 def doctest_mode(self, parameter_s=''):
299 def doctest_mode(self, parameter_s=''):
312 """Toggle doctest mode on and off.
300 """Toggle doctest mode on and off.
313
301
314 This mode is intended to make IPython behave as much as possible like a
302 This mode is intended to make IPython behave as much as possible like a
315 plain Python shell, from the perspective of how its prompts, exceptions
303 plain Python shell, from the perspective of how its prompts, exceptions
316 and output look. This makes it easy to copy and paste parts of a
304 and output look. This makes it easy to copy and paste parts of a
317 session into doctests. It does so by:
305 session into doctests. It does so by:
318
306
319 - Changing the prompts to the classic ``>>>`` ones.
307 - Changing the prompts to the classic ``>>>`` ones.
320 - Changing the exception reporting mode to 'Plain'.
308 - Changing the exception reporting mode to 'Plain'.
321 - Disabling pretty-printing of output.
309 - Disabling pretty-printing of output.
322
310
323 Note that IPython also supports the pasting of code snippets that have
311 Note that IPython also supports the pasting of code snippets that have
324 leading '>>>' and '...' prompts in them. This means that you can paste
312 leading '>>>' and '...' prompts in them. This means that you can paste
325 doctests from files or docstrings (even if they have leading
313 doctests from files or docstrings (even if they have leading
326 whitespace), and the code will execute correctly. You can then use
314 whitespace), and the code will execute correctly. You can then use
327 '%history -t' to see the translated history; this will give you the
315 '%history -t' to see the translated history; this will give you the
328 input after removal of all the leading prompts and whitespace, which
316 input after removal of all the leading prompts and whitespace, which
329 can be pasted back into an editor.
317 can be pasted back into an editor.
330
318
331 With these features, you can switch into this mode easily whenever you
319 With these features, you can switch into this mode easily whenever you
332 need to do testing and changes to doctests, without having to leave
320 need to do testing and changes to doctests, without having to leave
333 your existing IPython session.
321 your existing IPython session.
334 """
322 """
335
323
336 # Shorthands
324 # Shorthands
337 shell = self.shell
325 shell = self.shell
338 pm = shell.prompt_manager
326 pm = shell.prompt_manager
339 meta = shell.meta
327 meta = shell.meta
340 disp_formatter = self.shell.display_formatter
328 disp_formatter = self.shell.display_formatter
341 ptformatter = disp_formatter.formatters['text/plain']
329 ptformatter = disp_formatter.formatters['text/plain']
342 # dstore is a data store kept in the instance metadata bag to track any
330 # dstore is a data store kept in the instance metadata bag to track any
343 # changes we make, so we can undo them later.
331 # changes we make, so we can undo them later.
344 dstore = meta.setdefault('doctest_mode',Struct())
332 dstore = meta.setdefault('doctest_mode',Struct())
345 save_dstore = dstore.setdefault
333 save_dstore = dstore.setdefault
346
334
347 # save a few values we'll need to recover later
335 # save a few values we'll need to recover later
348 mode = save_dstore('mode',False)
336 mode = save_dstore('mode',False)
349 save_dstore('rc_pprint',ptformatter.pprint)
337 save_dstore('rc_pprint',ptformatter.pprint)
350 save_dstore('xmode',shell.InteractiveTB.mode)
338 save_dstore('xmode',shell.InteractiveTB.mode)
351 save_dstore('rc_separate_out',shell.separate_out)
339 save_dstore('rc_separate_out',shell.separate_out)
352 save_dstore('rc_separate_out2',shell.separate_out2)
340 save_dstore('rc_separate_out2',shell.separate_out2)
353 save_dstore('rc_prompts_pad_left',pm.justify)
341 save_dstore('rc_prompts_pad_left',pm.justify)
354 save_dstore('rc_separate_in',shell.separate_in)
342 save_dstore('rc_separate_in',shell.separate_in)
355 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
343 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
356 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
344 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
357
345
358 if mode == False:
346 if mode == False:
359 # turn on
347 # turn on
360 pm.in_template = '>>> '
348 pm.in_template = '>>> '
361 pm.in2_template = '... '
349 pm.in2_template = '... '
362 pm.out_template = ''
350 pm.out_template = ''
363
351
364 # Prompt separators like plain python
352 # Prompt separators like plain python
365 shell.separate_in = ''
353 shell.separate_in = ''
366 shell.separate_out = ''
354 shell.separate_out = ''
367 shell.separate_out2 = ''
355 shell.separate_out2 = ''
368
356
369 pm.justify = False
357 pm.justify = False
370
358
371 ptformatter.pprint = False
359 ptformatter.pprint = False
372 disp_formatter.plain_text_only = True
360 disp_formatter.plain_text_only = True
373
361
374 shell.magic('xmode Plain')
362 shell.magic('xmode Plain')
375 else:
363 else:
376 # turn off
364 # turn off
377 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
365 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
378
366
379 shell.separate_in = dstore.rc_separate_in
367 shell.separate_in = dstore.rc_separate_in
380
368
381 shell.separate_out = dstore.rc_separate_out
369 shell.separate_out = dstore.rc_separate_out
382 shell.separate_out2 = dstore.rc_separate_out2
370 shell.separate_out2 = dstore.rc_separate_out2
383
371
384 pm.justify = dstore.rc_prompts_pad_left
372 pm.justify = dstore.rc_prompts_pad_left
385
373
386 ptformatter.pprint = dstore.rc_pprint
374 ptformatter.pprint = dstore.rc_pprint
387 disp_formatter.plain_text_only = dstore.rc_plain_text_only
375 disp_formatter.plain_text_only = dstore.rc_plain_text_only
388
376
389 shell.magic('xmode ' + dstore.xmode)
377 shell.magic('xmode ' + dstore.xmode)
390
378
391 # Store new mode and inform
379 # Store new mode and inform
392 dstore.mode = bool(1-int(mode))
380 dstore.mode = bool(1-int(mode))
393 mode_label = ['OFF','ON'][dstore.mode]
381 mode_label = ['OFF','ON'][dstore.mode]
394 print('Doctest mode is:', mode_label)
382 print('Doctest mode is:', mode_label)
395
383
396 @line_magic
384 @line_magic
397 def gui(self, parameter_s=''):
385 def gui(self, parameter_s=''):
398 """Enable or disable IPython GUI event loop integration.
386 """Enable or disable IPython GUI event loop integration.
399
387
400 %gui [GUINAME]
388 %gui [GUINAME]
401
389
402 This magic replaces IPython's threaded shells that were activated
390 This magic replaces IPython's threaded shells that were activated
403 using the (pylab/wthread/etc.) command line flags. GUI toolkits
391 using the (pylab/wthread/etc.) command line flags. GUI toolkits
404 can now be enabled at runtime and keyboard
392 can now be enabled at runtime and keyboard
405 interrupts should work without any problems. The following toolkits
393 interrupts should work without any problems. The following toolkits
406 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
394 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
407
395
408 %gui wx # enable wxPython event loop integration
396 %gui wx # enable wxPython event loop integration
409 %gui qt4|qt # enable PyQt4 event loop integration
397 %gui qt4|qt # enable PyQt4 event loop integration
410 %gui gtk # enable PyGTK event loop integration
398 %gui gtk # enable PyGTK event loop integration
411 %gui gtk3 # enable Gtk3 event loop integration
399 %gui gtk3 # enable Gtk3 event loop integration
412 %gui tk # enable Tk event loop integration
400 %gui tk # enable Tk event loop integration
413 %gui osx # enable Cocoa event loop integration
401 %gui osx # enable Cocoa event loop integration
414 # (requires %matplotlib 1.1)
402 # (requires %matplotlib 1.1)
415 %gui # disable all event loop integration
403 %gui # disable all event loop integration
416
404
417 WARNING: after any of these has been called you can simply create
405 WARNING: after any of these has been called you can simply create
418 an application object, but DO NOT start the event loop yourself, as
406 an application object, but DO NOT start the event loop yourself, as
419 we have already handled that.
407 we have already handled that.
420 """
408 """
421 opts, arg = self.parse_options(parameter_s, '')
409 opts, arg = self.parse_options(parameter_s, '')
422 if arg=='': arg = None
410 if arg=='': arg = None
423 try:
411 try:
424 return self.shell.enable_gui(arg)
412 return self.shell.enable_gui(arg)
425 except Exception as e:
413 except Exception as e:
426 # print simple error message, rather than traceback if we can't
414 # print simple error message, rather than traceback if we can't
427 # hook up the GUI
415 # hook up the GUI
428 error(str(e))
416 error(str(e))
429
417
430 @skip_doctest
418 @skip_doctest
431 @line_magic
419 @line_magic
432 def precision(self, s=''):
420 def precision(self, s=''):
433 """Set floating point precision for pretty printing.
421 """Set floating point precision for pretty printing.
434
422
435 Can set either integer precision or a format string.
423 Can set either integer precision or a format string.
436
424
437 If numpy has been imported and precision is an int,
425 If numpy has been imported and precision is an int,
438 numpy display precision will also be set, via ``numpy.set_printoptions``.
426 numpy display precision will also be set, via ``numpy.set_printoptions``.
439
427
440 If no argument is given, defaults will be restored.
428 If no argument is given, defaults will be restored.
441
429
442 Examples
430 Examples
443 --------
431 --------
444 ::
432 ::
445
433
446 In [1]: from math import pi
434 In [1]: from math import pi
447
435
448 In [2]: %precision 3
436 In [2]: %precision 3
449 Out[2]: u'%.3f'
437 Out[2]: u'%.3f'
450
438
451 In [3]: pi
439 In [3]: pi
452 Out[3]: 3.142
440 Out[3]: 3.142
453
441
454 In [4]: %precision %i
442 In [4]: %precision %i
455 Out[4]: u'%i'
443 Out[4]: u'%i'
456
444
457 In [5]: pi
445 In [5]: pi
458 Out[5]: 3
446 Out[5]: 3
459
447
460 In [6]: %precision %e
448 In [6]: %precision %e
461 Out[6]: u'%e'
449 Out[6]: u'%e'
462
450
463 In [7]: pi**10
451 In [7]: pi**10
464 Out[7]: 9.364805e+04
452 Out[7]: 9.364805e+04
465
453
466 In [8]: %precision
454 In [8]: %precision
467 Out[8]: u'%r'
455 Out[8]: u'%r'
468
456
469 In [9]: pi**10
457 In [9]: pi**10
470 Out[9]: 93648.047476082982
458 Out[9]: 93648.047476082982
471 """
459 """
472 ptformatter = self.shell.display_formatter.formatters['text/plain']
460 ptformatter = self.shell.display_formatter.formatters['text/plain']
473 ptformatter.float_precision = s
461 ptformatter.float_precision = s
474 return ptformatter.float_format
462 return ptformatter.float_format
475
463
476 @magic_arguments.magic_arguments()
464 @magic_arguments.magic_arguments()
477 @magic_arguments.argument(
465 @magic_arguments.argument(
478 '-e', '--export', action='store_true', default=False,
466 '-e', '--export', action='store_true', default=False,
479 help='Export IPython history as a notebook. The filename argument '
467 help='Export IPython history as a notebook. The filename argument '
480 'is used to specify the notebook name and format. For example '
468 'is used to specify the notebook name and format. For example '
481 'a filename of notebook.ipynb will result in a notebook name '
469 'a filename of notebook.ipynb will result in a notebook name '
482 'of "notebook" and a format of "xml". Likewise using a ".json" '
470 'of "notebook" and a format of "xml". Likewise using a ".json" '
483 'or ".py" file extension will write the notebook in the json '
471 'or ".py" file extension will write the notebook in the json '
484 'or py formats.'
472 'or py formats.'
485 )
473 )
486 @magic_arguments.argument(
474 @magic_arguments.argument(
487 '-f', '--format',
475 '-f', '--format',
488 help='Convert an existing IPython notebook to a new format. This option '
476 help='Convert an existing IPython notebook to a new format. This option '
489 'specifies the new format and can have the values: xml, json, py. '
477 'specifies the new format and can have the values: xml, json, py. '
490 'The target filename is chosen automatically based on the new '
478 'The target filename is chosen automatically based on the new '
491 'format. The filename argument gives the name of the source file.'
479 'format. The filename argument gives the name of the source file.'
492 )
480 )
493 @magic_arguments.argument(
481 @magic_arguments.argument(
494 'filename', type=unicode,
482 'filename', type=unicode,
495 help='Notebook name or filename'
483 help='Notebook name or filename'
496 )
484 )
497 @line_magic
485 @line_magic
498 def notebook(self, s):
486 def notebook(self, s):
499 """Export and convert IPython notebooks.
487 """Export and convert IPython notebooks.
500
488
501 This function can export the current IPython history to a notebook file
489 This function can export the current IPython history to a notebook file
502 or can convert an existing notebook file into a different format. For
490 or can convert an existing notebook file into a different format. For
503 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
491 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
504 To export the history to "foo.py" do "%notebook -e foo.py". To convert
492 To export the history to "foo.py" do "%notebook -e foo.py". To convert
505 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
493 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
506 formats include (json/ipynb, py).
494 formats include (json/ipynb, py).
507 """
495 """
508 args = magic_arguments.parse_argstring(self.notebook, s)
496 args = magic_arguments.parse_argstring(self.notebook, s)
509
497
510 from IPython.nbformat import current
498 from IPython.nbformat import current
511 args.filename = unquote_filename(args.filename)
499 args.filename = unquote_filename(args.filename)
512 if args.export:
500 if args.export:
513 fname, name, format = current.parse_filename(args.filename)
501 fname, name, format = current.parse_filename(args.filename)
514 cells = []
502 cells = []
515 hist = list(self.shell.history_manager.get_range())
503 hist = list(self.shell.history_manager.get_range())
516 for session, prompt_number, input in hist[:-1]:
504 for session, prompt_number, input in hist[:-1]:
517 cells.append(current.new_code_cell(prompt_number=prompt_number,
505 cells.append(current.new_code_cell(prompt_number=prompt_number,
518 input=input))
506 input=input))
519 worksheet = current.new_worksheet(cells=cells)
507 worksheet = current.new_worksheet(cells=cells)
520 nb = current.new_notebook(name=name,worksheets=[worksheet])
508 nb = current.new_notebook(name=name,worksheets=[worksheet])
521 with io.open(fname, 'w', encoding='utf-8') as f:
509 with io.open(fname, 'w', encoding='utf-8') as f:
522 current.write(nb, f, format);
510 current.write(nb, f, format);
523 elif args.format is not None:
511 elif args.format is not None:
524 old_fname, old_name, old_format = current.parse_filename(args.filename)
512 old_fname, old_name, old_format = current.parse_filename(args.filename)
525 new_format = args.format
513 new_format = args.format
526 if new_format == u'xml':
514 if new_format == u'xml':
527 raise ValueError('Notebooks cannot be written as xml.')
515 raise ValueError('Notebooks cannot be written as xml.')
528 elif new_format == u'ipynb' or new_format == u'json':
516 elif new_format == u'ipynb' or new_format == u'json':
529 new_fname = old_name + u'.ipynb'
517 new_fname = old_name + u'.ipynb'
530 new_format = u'json'
518 new_format = u'json'
531 elif new_format == u'py':
519 elif new_format == u'py':
532 new_fname = old_name + u'.py'
520 new_fname = old_name + u'.py'
533 else:
521 else:
534 raise ValueError('Invalid notebook format: %s' % new_format)
522 raise ValueError('Invalid notebook format: %s' % new_format)
535 with io.open(old_fname, 'r', encoding='utf-8') as f:
523 with io.open(old_fname, 'r', encoding='utf-8') as f:
536 nb = current.read(f, old_format)
524 nb = current.read(f, old_format)
537 with io.open(new_fname, 'w', encoding='utf-8') as f:
525 with io.open(new_fname, 'w', encoding='utf-8') as f:
538 current.write(nb, f, new_format)
526 current.write(nb, f, new_format)
General Comments 0
You need to be logged in to leave comments. Login now