##// END OF EJS Templates
Refactor %magic into a lsmagic_docs API function.
Bradley M. Froehle -
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,528 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':
104 if mode == 'brief':
115 return magic_docs
105 return magic_docs
116
106
117 out = ["""
107 out = ["""
118 IPython's 'magic' functions
108 IPython's 'magic' functions
119 ===========================
109 ===========================
120
110
121 The magic function system provides a series of functions which allow you to
111 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
112 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.
113 features. There are two kinds of magics, line-oriented and cell-oriented.
124
114
125 Line magics are prefixed with the % character and work much like OS
115 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
116 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
117 arguments are passed without parentheses or quotes. For example, this will
128 time the given statement::
118 time the given statement::
129
119
130 %timeit range(1000)
120 %timeit range(1000)
131
121
132 Cell magics are prefixed with a double %%, and they are functions that get as
122 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
123 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
124 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.
125 call line and the body of the cell, consisting of the lines below the first.
136 For example::
126 For example::
137
127
138 %%timeit x = numpy.random.randn((100, 100))
128 %%timeit x = numpy.random.randn((100, 100))
139 numpy.linalg.svd(x)
129 numpy.linalg.svd(x)
140
130
141 will time the execution of the numpy svd routine, running the assignment of x
131 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.
132 as part of the setup phase, which is not timed.
143
133
144 In a line-oriented client (the terminal or Qt console IPython), starting a new
134 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
135 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
136 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
137 whole cell as one entity, but keep in mind that the %% escape can only be at
148 the very start of the cell.
138 the very start of the cell.
149
139
150 NOTE: If you have 'automagic' enabled (via the command line option or with the
140 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
141 %automagic function), you don't need to type in the % explicitly for line
152 magics; cell magics always require an explicit '%%' escape. By default,
142 magics; cell magics always require an explicit '%%' escape. By default,
153 IPython ships with automagic on, so you should only rarely need the % escape.
143 IPython ships with automagic on, so you should only rarely need the % escape.
154
144
155 Example: typing '%cd mydir' (without the quotes) changes you working directory
145 Example: typing '%cd mydir' (without the quotes) changes you working directory
156 to 'mydir', if it exists.
146 to 'mydir', if it exists.
157
147
158 For a list of the available magic functions, use %lsmagic. For a description
148 For a list of the available magic functions, use %lsmagic. For a description
159 of any of them, type %magic_name?, e.g. '%cd?'.
149 of any of them, type %magic_name?, e.g. '%cd?'.
160
150
161 Currently the magic system has the following functions:""",
151 Currently the magic system has the following functions:""",
162 magic_docs,
152 magic_docs,
163 "Summary of magic functions (from %slsmagic):",
153 "Summary of magic functions (from %slsmagic):",
164 self._lsmagic(),
154 self._lsmagic(),
165 ]
155 ]
166 page.page('\n'.join(out))
156 page.page('\n'.join(out))
167
157
168
158
169 @line_magic
159 @line_magic
170 def page(self, parameter_s=''):
160 def page(self, parameter_s=''):
171 """Pretty print the object and display it through a pager.
161 """Pretty print the object and display it through a pager.
172
162
173 %page [options] OBJECT
163 %page [options] OBJECT
174
164
175 If no object is given, use _ (last output).
165 If no object is given, use _ (last output).
176
166
177 Options:
167 Options:
178
168
179 -r: page str(object), don't pretty-print it."""
169 -r: page str(object), don't pretty-print it."""
180
170
181 # After a function contributed by Olivier Aubert, slightly modified.
171 # After a function contributed by Olivier Aubert, slightly modified.
182
172
183 # Process options/args
173 # Process options/args
184 opts, args = self.parse_options(parameter_s, 'r')
174 opts, args = self.parse_options(parameter_s, 'r')
185 raw = 'r' in opts
175 raw = 'r' in opts
186
176
187 oname = args and args or '_'
177 oname = args and args or '_'
188 info = self.shell._ofind(oname)
178 info = self.shell._ofind(oname)
189 if info['found']:
179 if info['found']:
190 txt = (raw and str or pformat)( info['obj'] )
180 txt = (raw and str or pformat)( info['obj'] )
191 page.page(txt)
181 page.page(txt)
192 else:
182 else:
193 print('Object `%s` not found' % oname)
183 print('Object `%s` not found' % oname)
194
184
195 @line_magic
185 @line_magic
196 def profile(self, parameter_s=''):
186 def profile(self, parameter_s=''):
197 """Print your currently active IPython profile."""
187 """Print your currently active IPython profile."""
198 from IPython.core.application import BaseIPythonApplication
188 from IPython.core.application import BaseIPythonApplication
199 if BaseIPythonApplication.initialized():
189 if BaseIPythonApplication.initialized():
200 print(BaseIPythonApplication.instance().profile)
190 print(BaseIPythonApplication.instance().profile)
201 else:
191 else:
202 error("profile is an application-level value, but you don't appear to be in an IPython application")
192 error("profile is an application-level value, but you don't appear to be in an IPython application")
203
193
204 @line_magic
194 @line_magic
205 def pprint(self, parameter_s=''):
195 def pprint(self, parameter_s=''):
206 """Toggle pretty printing on/off."""
196 """Toggle pretty printing on/off."""
207 ptformatter = self.shell.display_formatter.formatters['text/plain']
197 ptformatter = self.shell.display_formatter.formatters['text/plain']
208 ptformatter.pprint = bool(1 - ptformatter.pprint)
198 ptformatter.pprint = bool(1 - ptformatter.pprint)
209 print('Pretty printing has been turned',
199 print('Pretty printing has been turned',
210 ['OFF','ON'][ptformatter.pprint])
200 ['OFF','ON'][ptformatter.pprint])
211
201
212 @line_magic
202 @line_magic
213 def colors(self, parameter_s=''):
203 def colors(self, parameter_s=''):
214 """Switch color scheme for prompts, info system and exception handlers.
204 """Switch color scheme for prompts, info system and exception handlers.
215
205
216 Currently implemented schemes: NoColor, Linux, LightBG.
206 Currently implemented schemes: NoColor, Linux, LightBG.
217
207
218 Color scheme names are not case-sensitive.
208 Color scheme names are not case-sensitive.
219
209
220 Examples
210 Examples
221 --------
211 --------
222 To get a plain black and white terminal::
212 To get a plain black and white terminal::
223
213
224 %colors nocolor
214 %colors nocolor
225 """
215 """
226 def color_switch_err(name):
216 def color_switch_err(name):
227 warn('Error changing %s color schemes.\n%s' %
217 warn('Error changing %s color schemes.\n%s' %
228 (name, sys.exc_info()[1]))
218 (name, sys.exc_info()[1]))
229
219
230
220
231 new_scheme = parameter_s.strip()
221 new_scheme = parameter_s.strip()
232 if not new_scheme:
222 if not new_scheme:
233 raise UsageError(
223 raise UsageError(
234 "%colors: you must specify a color scheme. See '%colors?'")
224 "%colors: you must specify a color scheme. See '%colors?'")
235 return
225 return
236 # local shortcut
226 # local shortcut
237 shell = self.shell
227 shell = self.shell
238
228
239 import IPython.utils.rlineimpl as readline
229 import IPython.utils.rlineimpl as readline
240
230
241 if not shell.colors_force and \
231 if not shell.colors_force and \
242 not readline.have_readline and sys.platform == "win32":
232 not readline.have_readline and sys.platform == "win32":
243 msg = """\
233 msg = """\
244 Proper color support under MS Windows requires the pyreadline library.
234 Proper color support under MS Windows requires the pyreadline library.
245 You can find it at:
235 You can find it at:
246 http://ipython.org/pyreadline.html
236 http://ipython.org/pyreadline.html
247 Gary's readline needs the ctypes module, from:
237 Gary's readline needs the ctypes module, from:
248 http://starship.python.net/crew/theller/ctypes
238 http://starship.python.net/crew/theller/ctypes
249 (Note that ctypes is already part of Python versions 2.5 and newer).
239 (Note that ctypes is already part of Python versions 2.5 and newer).
250
240
251 Defaulting color scheme to 'NoColor'"""
241 Defaulting color scheme to 'NoColor'"""
252 new_scheme = 'NoColor'
242 new_scheme = 'NoColor'
253 warn(msg)
243 warn(msg)
254
244
255 # readline option is 0
245 # readline option is 0
256 if not shell.colors_force and not shell.has_readline:
246 if not shell.colors_force and not shell.has_readline:
257 new_scheme = 'NoColor'
247 new_scheme = 'NoColor'
258
248
259 # Set prompt colors
249 # Set prompt colors
260 try:
250 try:
261 shell.prompt_manager.color_scheme = new_scheme
251 shell.prompt_manager.color_scheme = new_scheme
262 except:
252 except:
263 color_switch_err('prompt')
253 color_switch_err('prompt')
264 else:
254 else:
265 shell.colors = \
255 shell.colors = \
266 shell.prompt_manager.color_scheme_table.active_scheme_name
256 shell.prompt_manager.color_scheme_table.active_scheme_name
267 # Set exception colors
257 # Set exception colors
268 try:
258 try:
269 shell.InteractiveTB.set_colors(scheme = new_scheme)
259 shell.InteractiveTB.set_colors(scheme = new_scheme)
270 shell.SyntaxTB.set_colors(scheme = new_scheme)
260 shell.SyntaxTB.set_colors(scheme = new_scheme)
271 except:
261 except:
272 color_switch_err('exception')
262 color_switch_err('exception')
273
263
274 # Set info (for 'object?') colors
264 # Set info (for 'object?') colors
275 if shell.color_info:
265 if shell.color_info:
276 try:
266 try:
277 shell.inspector.set_active_scheme(new_scheme)
267 shell.inspector.set_active_scheme(new_scheme)
278 except:
268 except:
279 color_switch_err('object inspector')
269 color_switch_err('object inspector')
280 else:
270 else:
281 shell.inspector.set_active_scheme('NoColor')
271 shell.inspector.set_active_scheme('NoColor')
282
272
283 @line_magic
273 @line_magic
284 def xmode(self, parameter_s=''):
274 def xmode(self, parameter_s=''):
285 """Switch modes for the exception handlers.
275 """Switch modes for the exception handlers.
286
276
287 Valid modes: Plain, Context and Verbose.
277 Valid modes: Plain, Context and Verbose.
288
278
289 If called without arguments, acts as a toggle."""
279 If called without arguments, acts as a toggle."""
290
280
291 def xmode_switch_err(name):
281 def xmode_switch_err(name):
292 warn('Error changing %s exception modes.\n%s' %
282 warn('Error changing %s exception modes.\n%s' %
293 (name,sys.exc_info()[1]))
283 (name,sys.exc_info()[1]))
294
284
295 shell = self.shell
285 shell = self.shell
296 new_mode = parameter_s.strip().capitalize()
286 new_mode = parameter_s.strip().capitalize()
297 try:
287 try:
298 shell.InteractiveTB.set_mode(mode=new_mode)
288 shell.InteractiveTB.set_mode(mode=new_mode)
299 print('Exception reporting mode:',shell.InteractiveTB.mode)
289 print('Exception reporting mode:',shell.InteractiveTB.mode)
300 except:
290 except:
301 xmode_switch_err('user')
291 xmode_switch_err('user')
302
292
303 @line_magic
293 @line_magic
304 def quickref(self,arg):
294 def quickref(self,arg):
305 """ Show a quick reference sheet """
295 """ Show a quick reference sheet """
306 from IPython.core.usage import quick_reference
296 from IPython.core.usage import quick_reference
307 qr = quick_reference + self.magic('-brief')
297 qr = quick_reference + self.magic('-brief')
308 page.page(qr)
298 page.page(qr)
309
299
310 @line_magic
300 @line_magic
311 def doctest_mode(self, parameter_s=''):
301 def doctest_mode(self, parameter_s=''):
312 """Toggle doctest mode on and off.
302 """Toggle doctest mode on and off.
313
303
314 This mode is intended to make IPython behave as much as possible like a
304 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
305 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
306 and output look. This makes it easy to copy and paste parts of a
317 session into doctests. It does so by:
307 session into doctests. It does so by:
318
308
319 - Changing the prompts to the classic ``>>>`` ones.
309 - Changing the prompts to the classic ``>>>`` ones.
320 - Changing the exception reporting mode to 'Plain'.
310 - Changing the exception reporting mode to 'Plain'.
321 - Disabling pretty-printing of output.
311 - Disabling pretty-printing of output.
322
312
323 Note that IPython also supports the pasting of code snippets that have
313 Note that IPython also supports the pasting of code snippets that have
324 leading '>>>' and '...' prompts in them. This means that you can paste
314 leading '>>>' and '...' prompts in them. This means that you can paste
325 doctests from files or docstrings (even if they have leading
315 doctests from files or docstrings (even if they have leading
326 whitespace), and the code will execute correctly. You can then use
316 whitespace), and the code will execute correctly. You can then use
327 '%history -t' to see the translated history; this will give you the
317 '%history -t' to see the translated history; this will give you the
328 input after removal of all the leading prompts and whitespace, which
318 input after removal of all the leading prompts and whitespace, which
329 can be pasted back into an editor.
319 can be pasted back into an editor.
330
320
331 With these features, you can switch into this mode easily whenever you
321 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
322 need to do testing and changes to doctests, without having to leave
333 your existing IPython session.
323 your existing IPython session.
334 """
324 """
335
325
336 # Shorthands
326 # Shorthands
337 shell = self.shell
327 shell = self.shell
338 pm = shell.prompt_manager
328 pm = shell.prompt_manager
339 meta = shell.meta
329 meta = shell.meta
340 disp_formatter = self.shell.display_formatter
330 disp_formatter = self.shell.display_formatter
341 ptformatter = disp_formatter.formatters['text/plain']
331 ptformatter = disp_formatter.formatters['text/plain']
342 # dstore is a data store kept in the instance metadata bag to track any
332 # dstore is a data store kept in the instance metadata bag to track any
343 # changes we make, so we can undo them later.
333 # changes we make, so we can undo them later.
344 dstore = meta.setdefault('doctest_mode',Struct())
334 dstore = meta.setdefault('doctest_mode',Struct())
345 save_dstore = dstore.setdefault
335 save_dstore = dstore.setdefault
346
336
347 # save a few values we'll need to recover later
337 # save a few values we'll need to recover later
348 mode = save_dstore('mode',False)
338 mode = save_dstore('mode',False)
349 save_dstore('rc_pprint',ptformatter.pprint)
339 save_dstore('rc_pprint',ptformatter.pprint)
350 save_dstore('xmode',shell.InteractiveTB.mode)
340 save_dstore('xmode',shell.InteractiveTB.mode)
351 save_dstore('rc_separate_out',shell.separate_out)
341 save_dstore('rc_separate_out',shell.separate_out)
352 save_dstore('rc_separate_out2',shell.separate_out2)
342 save_dstore('rc_separate_out2',shell.separate_out2)
353 save_dstore('rc_prompts_pad_left',pm.justify)
343 save_dstore('rc_prompts_pad_left',pm.justify)
354 save_dstore('rc_separate_in',shell.separate_in)
344 save_dstore('rc_separate_in',shell.separate_in)
355 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
345 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))
346 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
357
347
358 if mode == False:
348 if mode == False:
359 # turn on
349 # turn on
360 pm.in_template = '>>> '
350 pm.in_template = '>>> '
361 pm.in2_template = '... '
351 pm.in2_template = '... '
362 pm.out_template = ''
352 pm.out_template = ''
363
353
364 # Prompt separators like plain python
354 # Prompt separators like plain python
365 shell.separate_in = ''
355 shell.separate_in = ''
366 shell.separate_out = ''
356 shell.separate_out = ''
367 shell.separate_out2 = ''
357 shell.separate_out2 = ''
368
358
369 pm.justify = False
359 pm.justify = False
370
360
371 ptformatter.pprint = False
361 ptformatter.pprint = False
372 disp_formatter.plain_text_only = True
362 disp_formatter.plain_text_only = True
373
363
374 shell.magic('xmode Plain')
364 shell.magic('xmode Plain')
375 else:
365 else:
376 # turn off
366 # turn off
377 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
367 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
378
368
379 shell.separate_in = dstore.rc_separate_in
369 shell.separate_in = dstore.rc_separate_in
380
370
381 shell.separate_out = dstore.rc_separate_out
371 shell.separate_out = dstore.rc_separate_out
382 shell.separate_out2 = dstore.rc_separate_out2
372 shell.separate_out2 = dstore.rc_separate_out2
383
373
384 pm.justify = dstore.rc_prompts_pad_left
374 pm.justify = dstore.rc_prompts_pad_left
385
375
386 ptformatter.pprint = dstore.rc_pprint
376 ptformatter.pprint = dstore.rc_pprint
387 disp_formatter.plain_text_only = dstore.rc_plain_text_only
377 disp_formatter.plain_text_only = dstore.rc_plain_text_only
388
378
389 shell.magic('xmode ' + dstore.xmode)
379 shell.magic('xmode ' + dstore.xmode)
390
380
391 # Store new mode and inform
381 # Store new mode and inform
392 dstore.mode = bool(1-int(mode))
382 dstore.mode = bool(1-int(mode))
393 mode_label = ['OFF','ON'][dstore.mode]
383 mode_label = ['OFF','ON'][dstore.mode]
394 print('Doctest mode is:', mode_label)
384 print('Doctest mode is:', mode_label)
395
385
396 @line_magic
386 @line_magic
397 def gui(self, parameter_s=''):
387 def gui(self, parameter_s=''):
398 """Enable or disable IPython GUI event loop integration.
388 """Enable or disable IPython GUI event loop integration.
399
389
400 %gui [GUINAME]
390 %gui [GUINAME]
401
391
402 This magic replaces IPython's threaded shells that were activated
392 This magic replaces IPython's threaded shells that were activated
403 using the (pylab/wthread/etc.) command line flags. GUI toolkits
393 using the (pylab/wthread/etc.) command line flags. GUI toolkits
404 can now be enabled at runtime and keyboard
394 can now be enabled at runtime and keyboard
405 interrupts should work without any problems. The following toolkits
395 interrupts should work without any problems. The following toolkits
406 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
396 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
407
397
408 %gui wx # enable wxPython event loop integration
398 %gui wx # enable wxPython event loop integration
409 %gui qt4|qt # enable PyQt4 event loop integration
399 %gui qt4|qt # enable PyQt4 event loop integration
410 %gui gtk # enable PyGTK event loop integration
400 %gui gtk # enable PyGTK event loop integration
411 %gui gtk3 # enable Gtk3 event loop integration
401 %gui gtk3 # enable Gtk3 event loop integration
412 %gui tk # enable Tk event loop integration
402 %gui tk # enable Tk event loop integration
413 %gui osx # enable Cocoa event loop integration
403 %gui osx # enable Cocoa event loop integration
414 # (requires %matplotlib 1.1)
404 # (requires %matplotlib 1.1)
415 %gui # disable all event loop integration
405 %gui # disable all event loop integration
416
406
417 WARNING: after any of these has been called you can simply create
407 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
408 an application object, but DO NOT start the event loop yourself, as
419 we have already handled that.
409 we have already handled that.
420 """
410 """
421 opts, arg = self.parse_options(parameter_s, '')
411 opts, arg = self.parse_options(parameter_s, '')
422 if arg=='': arg = None
412 if arg=='': arg = None
423 try:
413 try:
424 return self.shell.enable_gui(arg)
414 return self.shell.enable_gui(arg)
425 except Exception as e:
415 except Exception as e:
426 # print simple error message, rather than traceback if we can't
416 # print simple error message, rather than traceback if we can't
427 # hook up the GUI
417 # hook up the GUI
428 error(str(e))
418 error(str(e))
429
419
430 @skip_doctest
420 @skip_doctest
431 @line_magic
421 @line_magic
432 def precision(self, s=''):
422 def precision(self, s=''):
433 """Set floating point precision for pretty printing.
423 """Set floating point precision for pretty printing.
434
424
435 Can set either integer precision or a format string.
425 Can set either integer precision or a format string.
436
426
437 If numpy has been imported and precision is an int,
427 If numpy has been imported and precision is an int,
438 numpy display precision will also be set, via ``numpy.set_printoptions``.
428 numpy display precision will also be set, via ``numpy.set_printoptions``.
439
429
440 If no argument is given, defaults will be restored.
430 If no argument is given, defaults will be restored.
441
431
442 Examples
432 Examples
443 --------
433 --------
444 ::
434 ::
445
435
446 In [1]: from math import pi
436 In [1]: from math import pi
447
437
448 In [2]: %precision 3
438 In [2]: %precision 3
449 Out[2]: u'%.3f'
439 Out[2]: u'%.3f'
450
440
451 In [3]: pi
441 In [3]: pi
452 Out[3]: 3.142
442 Out[3]: 3.142
453
443
454 In [4]: %precision %i
444 In [4]: %precision %i
455 Out[4]: u'%i'
445 Out[4]: u'%i'
456
446
457 In [5]: pi
447 In [5]: pi
458 Out[5]: 3
448 Out[5]: 3
459
449
460 In [6]: %precision %e
450 In [6]: %precision %e
461 Out[6]: u'%e'
451 Out[6]: u'%e'
462
452
463 In [7]: pi**10
453 In [7]: pi**10
464 Out[7]: 9.364805e+04
454 Out[7]: 9.364805e+04
465
455
466 In [8]: %precision
456 In [8]: %precision
467 Out[8]: u'%r'
457 Out[8]: u'%r'
468
458
469 In [9]: pi**10
459 In [9]: pi**10
470 Out[9]: 93648.047476082982
460 Out[9]: 93648.047476082982
471 """
461 """
472 ptformatter = self.shell.display_formatter.formatters['text/plain']
462 ptformatter = self.shell.display_formatter.formatters['text/plain']
473 ptformatter.float_precision = s
463 ptformatter.float_precision = s
474 return ptformatter.float_format
464 return ptformatter.float_format
475
465
476 @magic_arguments.magic_arguments()
466 @magic_arguments.magic_arguments()
477 @magic_arguments.argument(
467 @magic_arguments.argument(
478 '-e', '--export', action='store_true', default=False,
468 '-e', '--export', action='store_true', default=False,
479 help='Export IPython history as a notebook. The filename argument '
469 help='Export IPython history as a notebook. The filename argument '
480 'is used to specify the notebook name and format. For example '
470 'is used to specify the notebook name and format. For example '
481 'a filename of notebook.ipynb will result in a notebook name '
471 'a filename of notebook.ipynb will result in a notebook name '
482 'of "notebook" and a format of "xml". Likewise using a ".json" '
472 'of "notebook" and a format of "xml". Likewise using a ".json" '
483 'or ".py" file extension will write the notebook in the json '
473 'or ".py" file extension will write the notebook in the json '
484 'or py formats.'
474 'or py formats.'
485 )
475 )
486 @magic_arguments.argument(
476 @magic_arguments.argument(
487 '-f', '--format',
477 '-f', '--format',
488 help='Convert an existing IPython notebook to a new format. This option '
478 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. '
479 'specifies the new format and can have the values: xml, json, py. '
490 'The target filename is chosen automatically based on the new '
480 'The target filename is chosen automatically based on the new '
491 'format. The filename argument gives the name of the source file.'
481 'format. The filename argument gives the name of the source file.'
492 )
482 )
493 @magic_arguments.argument(
483 @magic_arguments.argument(
494 'filename', type=unicode,
484 'filename', type=unicode,
495 help='Notebook name or filename'
485 help='Notebook name or filename'
496 )
486 )
497 @line_magic
487 @line_magic
498 def notebook(self, s):
488 def notebook(self, s):
499 """Export and convert IPython notebooks.
489 """Export and convert IPython notebooks.
500
490
501 This function can export the current IPython history to a notebook file
491 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
492 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".
493 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
494 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
495 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
506 formats include (json/ipynb, py).
496 formats include (json/ipynb, py).
507 """
497 """
508 args = magic_arguments.parse_argstring(self.notebook, s)
498 args = magic_arguments.parse_argstring(self.notebook, s)
509
499
510 from IPython.nbformat import current
500 from IPython.nbformat import current
511 args.filename = unquote_filename(args.filename)
501 args.filename = unquote_filename(args.filename)
512 if args.export:
502 if args.export:
513 fname, name, format = current.parse_filename(args.filename)
503 fname, name, format = current.parse_filename(args.filename)
514 cells = []
504 cells = []
515 hist = list(self.shell.history_manager.get_range())
505 hist = list(self.shell.history_manager.get_range())
516 for session, prompt_number, input in hist[:-1]:
506 for session, prompt_number, input in hist[:-1]:
517 cells.append(current.new_code_cell(prompt_number=prompt_number,
507 cells.append(current.new_code_cell(prompt_number=prompt_number,
518 input=input))
508 input=input))
519 worksheet = current.new_worksheet(cells=cells)
509 worksheet = current.new_worksheet(cells=cells)
520 nb = current.new_notebook(name=name,worksheets=[worksheet])
510 nb = current.new_notebook(name=name,worksheets=[worksheet])
521 with io.open(fname, 'w', encoding='utf-8') as f:
511 with io.open(fname, 'w', encoding='utf-8') as f:
522 current.write(nb, f, format);
512 current.write(nb, f, format);
523 elif args.format is not None:
513 elif args.format is not None:
524 old_fname, old_name, old_format = current.parse_filename(args.filename)
514 old_fname, old_name, old_format = current.parse_filename(args.filename)
525 new_format = args.format
515 new_format = args.format
526 if new_format == u'xml':
516 if new_format == u'xml':
527 raise ValueError('Notebooks cannot be written as xml.')
517 raise ValueError('Notebooks cannot be written as xml.')
528 elif new_format == u'ipynb' or new_format == u'json':
518 elif new_format == u'ipynb' or new_format == u'json':
529 new_fname = old_name + u'.ipynb'
519 new_fname = old_name + u'.ipynb'
530 new_format = u'json'
520 new_format = u'json'
531 elif new_format == u'py':
521 elif new_format == u'py':
532 new_fname = old_name + u'.py'
522 new_fname = old_name + u'.py'
533 else:
523 else:
534 raise ValueError('Invalid notebook format: %s' % new_format)
524 raise ValueError('Invalid notebook format: %s' % new_format)
535 with io.open(old_fname, 'r', encoding='utf-8') as f:
525 with io.open(old_fname, 'r', encoding='utf-8') as f:
536 nb = current.read(f, old_format)
526 nb = current.read(f, old_format)
537 with io.open(new_fname, 'w', encoding='utf-8') as f:
527 with io.open(new_fname, 'w', encoding='utf-8') as f:
538 current.write(nb, f, new_format)
528 current.write(nb, f, new_format)
General Comments 0
You need to be logged in to leave comments. Login now