##// END OF EJS Templates
Remove extra space
Matthias Bussonnier -
Show More
@@ -1,694 +1,694 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, ESC_MAGIC2
28 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
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
34 from IPython.utils.warn import error
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 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
50 magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2)
51
51
52 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
53 # Utility classes and functions
53 # Utility classes and functions
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55
55
56 class Bunch: pass
56 class Bunch: pass
57
57
58
58
59 def on_off(tag):
59 def on_off(tag):
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
60 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
61 return ['OFF','ON'][tag]
61 return ['OFF','ON'][tag]
62
62
63
63
64 def compress_dhist(dh):
64 def compress_dhist(dh):
65 """Compress a directory history into a new one with at most 20 entries.
65 """Compress a directory history into a new one with at most 20 entries.
66
66
67 Return a new list made from the first and last 10 elements of dhist after
67 Return a new list made from the first and last 10 elements of dhist after
68 removal of duplicates.
68 removal of duplicates.
69 """
69 """
70 head, tail = dh[:-10], dh[-10:]
70 head, tail = dh[:-10], dh[-10:]
71
71
72 newhead = []
72 newhead = []
73 done = set()
73 done = set()
74 for h in head:
74 for h in head:
75 if h in done:
75 if h in done:
76 continue
76 continue
77 newhead.append(h)
77 newhead.append(h)
78 done.add(h)
78 done.add(h)
79
79
80 return newhead + tail
80 return newhead + tail
81
81
82
82
83 def needs_local_scope(func):
83 def needs_local_scope(func):
84 """Decorator to mark magic functions which need to local scope to run."""
84 """Decorator to mark magic functions which need to local scope to run."""
85 func.needs_local_scope = True
85 func.needs_local_scope = True
86 return func
86 return func
87
87
88 #-----------------------------------------------------------------------------
88 #-----------------------------------------------------------------------------
89 # Class and method decorators for registering magics
89 # Class and method decorators for registering magics
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91
91
92 def magics_class(cls):
92 def magics_class(cls):
93 """Class decorator for all subclasses of the main Magics class.
93 """Class decorator for all subclasses of the main Magics class.
94
94
95 Any class that subclasses Magics *must* also apply this decorator, to
95 Any class that subclasses Magics *must* also apply this decorator, to
96 ensure that all the methods that have been decorated as line/cell magics
96 ensure that all the methods that have been decorated as line/cell magics
97 get correctly registered in the class instance. This is necessary because
97 get correctly registered in the class instance. This is necessary because
98 when method decorators run, the class does not exist yet, so they
98 when method decorators run, the class does not exist yet, so they
99 temporarily store their information into a module global. Application of
99 temporarily store their information into a module global. Application of
100 this class decorator copies that global data to the class instance and
100 this class decorator copies that global data to the class instance and
101 clears the global.
101 clears the global.
102
102
103 Obviously, this mechanism is not thread-safe, which means that the
103 Obviously, this mechanism is not thread-safe, which means that the
104 *creation* of subclasses of Magic should only be done in a single-thread
104 *creation* of subclasses of Magic should only be done in a single-thread
105 context. Instantiation of the classes has no restrictions. Given that
105 context. Instantiation of the classes has no restrictions. Given that
106 these classes are typically created at IPython startup time and before user
106 these classes are typically created at IPython startup time and before user
107 application code becomes active, in practice this should not pose any
107 application code becomes active, in practice this should not pose any
108 problems.
108 problems.
109 """
109 """
110 cls.registered = True
110 cls.registered = True
111 cls.magics = dict(line = magics['line'],
111 cls.magics = dict(line = magics['line'],
112 cell = magics['cell'])
112 cell = magics['cell'])
113 magics['line'] = {}
113 magics['line'] = {}
114 magics['cell'] = {}
114 magics['cell'] = {}
115 return cls
115 return cls
116
116
117
117
118 def record_magic(dct, magic_kind, magic_name, func):
118 def record_magic(dct, magic_kind, magic_name, func):
119 """Utility function to store a function as a magic of a specific kind.
119 """Utility function to store a function as a magic of a specific kind.
120
120
121 Parameters
121 Parameters
122 ----------
122 ----------
123 dct : dict
123 dct : dict
124 A dictionary with 'line' and 'cell' subdicts.
124 A dictionary with 'line' and 'cell' subdicts.
125
125
126 magic_kind : str
126 magic_kind : str
127 Kind of magic to be stored.
127 Kind of magic to be stored.
128
128
129 magic_name : str
129 magic_name : str
130 Key to store the magic as.
130 Key to store the magic as.
131
131
132 func : function
132 func : function
133 Callable object to store.
133 Callable object to store.
134 """
134 """
135 if magic_kind == 'line_cell':
135 if magic_kind == 'line_cell':
136 dct['line'][magic_name] = dct['cell'][magic_name] = func
136 dct['line'][magic_name] = dct['cell'][magic_name] = func
137 else:
137 else:
138 dct[magic_kind][magic_name] = func
138 dct[magic_kind][magic_name] = func
139
139
140
140
141 def validate_type(magic_kind):
141 def validate_type(magic_kind):
142 """Ensure that the given magic_kind is valid.
142 """Ensure that the given magic_kind is valid.
143
143
144 Check that the given magic_kind is one of the accepted spec types (stored
144 Check that the given magic_kind is one of the accepted spec types (stored
145 in the global `magic_spec`), raise ValueError otherwise.
145 in the global `magic_spec`), raise ValueError otherwise.
146 """
146 """
147 if magic_kind not in magic_spec:
147 if magic_kind not in magic_spec:
148 raise ValueError('magic_kind must be one of %s, %s given' %
148 raise ValueError('magic_kind must be one of %s, %s given' %
149 magic_kinds, magic_kind)
149 magic_kinds, magic_kind)
150
150
151
151
152 # The docstrings for the decorator below will be fairly similar for the two
152 # The docstrings for the decorator below will be fairly similar for the two
153 # types (method and function), so we generate them here once and reuse the
153 # types (method and function), so we generate them here once and reuse the
154 # templates below.
154 # templates below.
155 _docstring_template = \
155 _docstring_template = \
156 """Decorate the given {0} as {1} magic.
156 """Decorate the given {0} as {1} magic.
157
157
158 The decorator can be used with or without arguments, as follows.
158 The decorator can be used with or without arguments, as follows.
159
159
160 i) without arguments: it will create a {1} magic named as the {0} being
160 i) without arguments: it will create a {1} magic named as the {0} being
161 decorated::
161 decorated::
162
162
163 @deco
163 @deco
164 def foo(...)
164 def foo(...)
165
165
166 will create a {1} magic named `foo`.
166 will create a {1} magic named `foo`.
167
167
168 ii) with one string argument: which will be used as the actual name of the
168 ii) with one string argument: which will be used as the actual name of the
169 resulting magic::
169 resulting magic::
170
170
171 @deco('bar')
171 @deco('bar')
172 def foo(...)
172 def foo(...)
173
173
174 will create a {1} magic named `bar`.
174 will create a {1} magic named `bar`.
175 """
175 """
176
176
177 # These two are decorator factories. While they are conceptually very similar,
177 # These two are decorator factories. While they are conceptually very similar,
178 # there are enough differences in the details that it's simpler to have them
178 # there are enough differences in the details that it's simpler to have them
179 # written as completely standalone functions rather than trying to share code
179 # written as completely standalone functions rather than trying to share code
180 # and make a single one with convoluted logic.
180 # and make a single one with convoluted logic.
181
181
182 def _method_magic_marker(magic_kind):
182 def _method_magic_marker(magic_kind):
183 """Decorator factory for methods in Magics subclasses.
183 """Decorator factory for methods in Magics subclasses.
184 """
184 """
185
185
186 validate_type(magic_kind)
186 validate_type(magic_kind)
187
187
188 # This is a closure to capture the magic_kind. We could also use a class,
188 # This is a closure to capture the magic_kind. We could also use a class,
189 # but it's overkill for just that one bit of state.
189 # but it's overkill for just that one bit of state.
190 def magic_deco(arg):
190 def magic_deco(arg):
191 call = lambda f, *a, **k: f(*a, **k)
191 call = lambda f, *a, **k: f(*a, **k)
192
192
193 if callable(arg):
193 if callable(arg):
194 # "Naked" decorator call (just @foo, no args)
194 # "Naked" decorator call (just @foo, no args)
195 func = arg
195 func = arg
196 name = func.func_name
196 name = func.func_name
197 retval = decorator(call, func)
197 retval = decorator(call, func)
198 record_magic(magics, magic_kind, name, name)
198 record_magic(magics, magic_kind, name, name)
199 elif isinstance(arg, basestring):
199 elif isinstance(arg, basestring):
200 # Decorator called with arguments (@foo('bar'))
200 # Decorator called with arguments (@foo('bar'))
201 name = arg
201 name = arg
202 def mark(func, *a, **kw):
202 def mark(func, *a, **kw):
203 record_magic(magics, magic_kind, name, func.func_name)
203 record_magic(magics, magic_kind, name, func.func_name)
204 return decorator(call, func)
204 return decorator(call, func)
205 retval = mark
205 retval = mark
206 else:
206 else:
207 raise TypeError("Decorator can only be called with "
207 raise TypeError("Decorator can only be called with "
208 "string or function")
208 "string or function")
209 return retval
209 return retval
210
210
211 # Ensure the resulting decorator has a usable docstring
211 # Ensure the resulting decorator has a usable docstring
212 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
212 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
213 return magic_deco
213 return magic_deco
214
214
215
215
216 def _function_magic_marker(magic_kind):
216 def _function_magic_marker(magic_kind):
217 """Decorator factory for standalone functions.
217 """Decorator factory for standalone functions.
218 """
218 """
219 validate_type(magic_kind)
219 validate_type(magic_kind)
220
220
221 # This is a closure to capture the magic_kind. We could also use a class,
221 # This is a closure to capture the magic_kind. We could also use a class,
222 # but it's overkill for just that one bit of state.
222 # but it's overkill for just that one bit of state.
223 def magic_deco(arg):
223 def magic_deco(arg):
224 call = lambda f, *a, **k: f(*a, **k)
224 call = lambda f, *a, **k: f(*a, **k)
225
225
226 # Find get_ipython() in the caller's namespace
226 # Find get_ipython() in the caller's namespace
227 caller = sys._getframe(1)
227 caller = sys._getframe(1)
228 for ns in ['f_locals', 'f_globals', 'f_builtins']:
228 for ns in ['f_locals', 'f_globals', 'f_builtins']:
229 get_ipython = getattr(caller, ns).get('get_ipython')
229 get_ipython = getattr(caller, ns).get('get_ipython')
230 if get_ipython is not None:
230 if get_ipython is not None:
231 break
231 break
232 else:
232 else:
233 raise NameError('Decorator can only run in context where '
233 raise NameError('Decorator can only run in context where '
234 '`get_ipython` exists')
234 '`get_ipython` exists')
235
235
236 ip = get_ipython()
236 ip = get_ipython()
237
237
238 if callable(arg):
238 if callable(arg):
239 # "Naked" decorator call (just @foo, no args)
239 # "Naked" decorator call (just @foo, no args)
240 func = arg
240 func = arg
241 name = func.func_name
241 name = func.func_name
242 ip.register_magic_function(func, magic_kind, name)
242 ip.register_magic_function(func, magic_kind, name)
243 retval = decorator(call, func)
243 retval = decorator(call, func)
244 elif isinstance(arg, basestring):
244 elif isinstance(arg, basestring):
245 # Decorator called with arguments (@foo('bar'))
245 # Decorator called with arguments (@foo('bar'))
246 name = arg
246 name = arg
247 def mark(func, *a, **kw):
247 def mark(func, *a, **kw):
248 ip.register_magic_function(func, magic_kind, name)
248 ip.register_magic_function(func, magic_kind, name)
249 return decorator(call, func)
249 return decorator(call, func)
250 retval = mark
250 retval = mark
251 else:
251 else:
252 raise TypeError("Decorator can only be called with "
252 raise TypeError("Decorator can only be called with "
253 "string or function")
253 "string or function")
254 return retval
254 return retval
255
255
256 # Ensure the resulting decorator has a usable docstring
256 # Ensure the resulting decorator has a usable docstring
257 ds = _docstring_template.format('function', magic_kind)
257 ds = _docstring_template.format('function', magic_kind)
258
258
259 ds += dedent("""
259 ds += dedent("""
260 Note: this decorator can only be used in a context where IPython is already
260 Note: this decorator can only be used in a context where IPython is already
261 active, so that the `get_ipython()` call succeeds. You can therefore use
261 active, so that the `get_ipython()` call succeeds. You can therefore use
262 it in your startup files loaded after IPython initializes, but *not* in the
262 it in your startup files loaded after IPython initializes, but *not* in the
263 IPython configuration file itself, which is executed before IPython is
263 IPython configuration file itself, which is executed before IPython is
264 fully up and running. Any file located in the `startup` subdirectory of
264 fully up and running. Any file located in the `startup` subdirectory of
265 your configuration profile will be OK in this sense.
265 your configuration profile will be OK in this sense.
266 """)
266 """)
267
267
268 magic_deco.__doc__ = ds
268 magic_deco.__doc__ = ds
269 return magic_deco
269 return magic_deco
270
270
271
271
272 # Create the actual decorators for public use
272 # Create the actual decorators for public use
273
273
274 # These three are used to decorate methods in class definitions
274 # These three are used to decorate methods in class definitions
275 line_magic = _method_magic_marker('line')
275 line_magic = _method_magic_marker('line')
276 cell_magic = _method_magic_marker('cell')
276 cell_magic = _method_magic_marker('cell')
277 line_cell_magic = _method_magic_marker('line_cell')
277 line_cell_magic = _method_magic_marker('line_cell')
278
278
279 # These three decorate standalone functions and perform the decoration
279 # These three decorate standalone functions and perform the decoration
280 # immediately. They can only run where get_ipython() works
280 # immediately. They can only run where get_ipython() works
281 register_line_magic = _function_magic_marker('line')
281 register_line_magic = _function_magic_marker('line')
282 register_cell_magic = _function_magic_marker('cell')
282 register_cell_magic = _function_magic_marker('cell')
283 register_line_cell_magic = _function_magic_marker('line_cell')
283 register_line_cell_magic = _function_magic_marker('line_cell')
284
284
285 #-----------------------------------------------------------------------------
285 #-----------------------------------------------------------------------------
286 # Core Magic classes
286 # Core Magic classes
287 #-----------------------------------------------------------------------------
287 #-----------------------------------------------------------------------------
288
288
289 class MagicsManager(Configurable):
289 class MagicsManager(Configurable):
290 """Object that handles all magic-related functionality for IPython.
290 """Object that handles all magic-related functionality for IPython.
291 """
291 """
292 # Non-configurable class attributes
292 # Non-configurable class attributes
293
293
294 # A two-level dict, first keyed by magic type, then by magic function, and
294 # A two-level dict, first keyed by magic type, then by magic function, and
295 # holding the actual callable object as value. This is the dict used for
295 # holding the actual callable object as value. This is the dict used for
296 # magic function dispatch
296 # magic function dispatch
297 magics = Dict
297 magics = Dict
298
298
299 # A registry of the original objects that we've been given holding magics.
299 # A registry of the original objects that we've been given holding magics.
300 registry = Dict
300 registry = Dict
301
301
302 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
302 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
303
303
304 auto_magic = Bool(True, config=True, help=
304 auto_magic = Bool(True, config=True, help=
305 "Automatically call line magics without requiring explicit % prefix")
305 "Automatically call line magics without requiring explicit % prefix")
306
306
307 def _auto_magic_changed(self, name, value):
307 def _auto_magic_changed(self, name, value):
308 self.shell.automagic = value
308 self.shell.automagic = value
309
309
310 _auto_status = [
310 _auto_status = [
311 'Automagic is OFF, % prefix IS needed for line magics.',
311 'Automagic is OFF, % prefix IS needed for line magics.',
312 'Automagic is ON, % prefix IS NOT needed for line magics.']
312 'Automagic is ON, % prefix IS NOT needed for line magics.']
313
313
314 user_magics = Instance('IPython.core.magics.UserMagics')
314 user_magics = Instance('IPython.core.magics.UserMagics')
315
315
316 def __init__(self, shell=None, config=None, user_magics=None, **traits):
316 def __init__(self, shell=None, config=None, user_magics=None, **traits):
317
317
318 super(MagicsManager, self).__init__(shell=shell, config=config,
318 super(MagicsManager, self).__init__(shell=shell, config=config,
319 user_magics=user_magics, **traits)
319 user_magics=user_magics, **traits)
320 self.magics = dict(line={}, cell={})
320 self.magics = dict(line={}, cell={})
321 # Let's add the user_magics to the registry for uniformity, so *all*
321 # Let's add the user_magics to the registry for uniformity, so *all*
322 # registered magic containers can be found there.
322 # registered magic containers can be found there.
323 self.registry[user_magics.__class__.__name__] = user_magics
323 self.registry[user_magics.__class__.__name__] = user_magics
324
324
325 def auto_status(self):
325 def auto_status(self):
326 """Return descriptive string with automagic status."""
326 """Return descriptive string with automagic status."""
327 return self._auto_status[self.auto_magic]
327 return self._auto_status[self.auto_magic]
328
328
329 def lsmagic(self):
329 def lsmagic(self):
330 """Return a dict of currently available magic functions.
330 """Return a dict of currently available magic functions.
331
331
332 The return dict has the keys 'line' and 'cell', corresponding to the
332 The return dict has the keys 'line' and 'cell', corresponding to the
333 two types of magics we support. Each value is a list of names.
333 two types of magics we support. Each value is a list of names.
334 """
334 """
335 return self.magics
335 return self.magics
336
336
337 def lsmagic_docs(self, brief=False, missing=''):
337 def lsmagic_docs(self, brief=False, missing=''):
338 """Return dict of documentation of magic functions.
338 """Return dict of documentation of magic functions.
339
339
340 The return dict has the keys 'line' and 'cell', corresponding to the
340 The return dict has the keys 'line' and 'cell', corresponding to the
341 two types of magics we support. Each value is a dict keyed by magic
341 two types of magics we support. Each value is a dict keyed by magic
342 name whose value is the function docstring. If a docstring is
342 name whose value is the function docstring. If a docstring is
343 unavailable, the value of `missing` is used instead.
343 unavailable, the value of `missing` is used instead.
344
344
345 If brief is True, only the first line of each docstring will be returned.
345 If brief is True, only the first line of each docstring will be returned.
346 """
346 """
347 docs = {}
347 docs = {}
348 for m_type in self.magics:
348 for m_type in self.magics:
349 m_docs = {}
349 m_docs = {}
350 for m_name, m_func in self.magics[m_type].iteritems():
350 for m_name, m_func in self.magics[m_type].iteritems():
351 if m_func.__doc__:
351 if m_func.__doc__:
352 if brief:
352 if brief:
353 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
353 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
354 else:
354 else:
355 m_docs[m_name] = m_func.__doc__.rstrip()
355 m_docs[m_name] = m_func.__doc__.rstrip()
356 else:
356 else:
357 m_docs[m_name] = missing
357 m_docs[m_name] = missing
358 docs[m_type] = m_docs
358 docs[m_type] = m_docs
359 return docs
359 return docs
360
360
361 def register(self, *magic_objects):
361 def register(self, *magic_objects):
362 """Register one or more instances of Magics.
362 """Register one or more instances of Magics.
363
363
364 Take one or more classes or instances of classes that subclass the main
364 Take one or more classes or instances of classes that subclass the main
365 `core.Magic` class, and register them with IPython to use the magic
365 `core.Magic` class, and register them with IPython to use the magic
366 functions they provide. The registration process will then ensure that
366 functions they provide. The registration process will then ensure that
367 any methods that have decorated to provide line and/or cell magics will
367 any methods that have decorated to provide line and/or cell magics will
368 be recognized with the `%x`/`%%x` syntax as a line/cell magic
368 be recognized with the `%x`/`%%x` syntax as a line/cell magic
369 respectively.
369 respectively.
370
370
371 If classes are given, they will be instantiated with the default
371 If classes are given, they will be instantiated with the default
372 constructor. If your classes need a custom constructor, you should
372 constructor. If your classes need a custom constructor, you should
373 instanitate them first and pass the instance.
373 instanitate them first and pass the instance.
374
374
375 The provided arguments can be an arbitrary mix of classes and instances.
375 The provided arguments can be an arbitrary mix of classes and instances.
376
376
377 Parameters
377 Parameters
378 ----------
378 ----------
379 magic_objects : one or more classes or instances
379 magic_objects : one or more classes or instances
380 """
380 """
381 # Start by validating them to ensure they have all had their magic
381 # Start by validating them to ensure they have all had their magic
382 # methods registered at the instance level
382 # methods registered at the instance level
383 for m in magic_objects:
383 for m in magic_objects:
384 if not m.registered:
384 if not m.registered:
385 raise ValueError("Class of magics %r was constructed without "
385 raise ValueError("Class of magics %r was constructed without "
386 "the @register_magics class decorator")
386 "the @register_magics class decorator")
387 if type(m) in (type, MetaHasTraits):
387 if type(m) in (type, MetaHasTraits):
388 # If we're given an uninstantiated class
388 # If we're given an uninstantiated class
389 m = m(shell=self.shell)
389 m = m(shell=self.shell)
390
390
391 # Now that we have an instance, we can register it and update the
391 # Now that we have an instance, we can register it and update the
392 # table of callables
392 # table of callables
393 self.registry[m.__class__.__name__] = m
393 self.registry[m.__class__.__name__] = m
394 for mtype in magic_kinds:
394 for mtype in magic_kinds:
395 self.magics[mtype].update(m.magics[mtype])
395 self.magics[mtype].update(m.magics[mtype])
396
396
397 def register_function(self, func, magic_kind='line', magic_name=None):
397 def register_function(self, func, magic_kind='line', magic_name=None):
398 """Expose a standalone function as magic function for IPython.
398 """Expose a standalone function as magic function for IPython.
399
399
400 This will create an IPython magic (line, cell or both) from a
400 This will create an IPython magic (line, cell or both) from a
401 standalone function. The functions should have the following
401 standalone function. The functions should have the following
402 signatures:
402 signatures:
403
403
404 * For line magics: `def f(line)`
404 * For line magics: `def f(line)`
405 * For cell magics: `def f(line, cell)`
405 * For cell magics: `def f(line, cell)`
406 * For a function that does both: `def f(line, cell=None)`
406 * For a function that does both: `def f(line, cell=None)`
407
407
408 In the latter case, the function will be called with `cell==None` when
408 In the latter case, the function will be called with `cell==None` when
409 invoked as `%f`, and with cell as a string when invoked as `%%f`.
409 invoked as `%f`, and with cell as a string when invoked as `%%f`.
410
410
411 Parameters
411 Parameters
412 ----------
412 ----------
413 func : callable
413 func : callable
414 Function to be registered as a magic.
414 Function to be registered as a magic.
415
415
416 magic_kind : str
416 magic_kind : str
417 Kind of magic, one of 'line', 'cell' or 'line_cell'
417 Kind of magic, one of 'line', 'cell' or 'line_cell'
418
418
419 magic_name : optional str
419 magic_name : optional str
420 If given, the name the magic will have in the IPython namespace. By
420 If given, the name the magic will have in the IPython namespace. By
421 default, the name of the function itself is used.
421 default, the name of the function itself is used.
422 """
422 """
423
423
424 # Create the new method in the user_magics and register it in the
424 # Create the new method in the user_magics and register it in the
425 # global table
425 # global table
426 validate_type(magic_kind)
426 validate_type(magic_kind)
427 magic_name = func.func_name if magic_name is None else magic_name
427 magic_name = func.func_name if magic_name is None else magic_name
428 setattr(self.user_magics, magic_name, func)
428 setattr(self.user_magics, magic_name, func)
429 record_magic(self.magics, magic_kind, magic_name, func)
429 record_magic(self.magics, magic_kind, magic_name, func)
430
430
431 def define_magic(self, name, func):
431 def define_magic(self, name, func):
432 """[Deprecated] Expose own function as magic function for IPython.
432 """[Deprecated] Expose own function as magic function for IPython.
433
433
434 Example::
434 Example::
435
435
436 def foo_impl(self, parameter_s=''):
436 def foo_impl(self, parameter_s=''):
437 'My very own magic!. (Use docstrings, IPython reads them).'
437 'My very own magic!. (Use docstrings, IPython reads them).'
438 print 'Magic function. Passed parameter is between < >:'
438 print 'Magic function. Passed parameter is between < >:'
439 print '<%s>' % parameter_s
439 print '<%s>' % parameter_s
440 print 'The self object is:', self
440 print 'The self object is:', self
441
441
442 ip.define_magic('foo',foo_impl)
442 ip.define_magic('foo',foo_impl)
443 """
443 """
444 meth = types.MethodType(func, self.user_magics)
444 meth = types.MethodType(func, self.user_magics)
445 setattr(self.user_magics, name, meth)
445 setattr(self.user_magics, name, meth)
446 record_magic(self.magics, 'line', name, meth)
446 record_magic(self.magics, 'line', name, meth)
447
447
448 def register_alias(self, alias_name, magic_name, magic_kind='line'):
448 def register_alias(self, alias_name, magic_name, magic_kind='line'):
449 """Register an alias to a magic function.
449 """Register an alias to a magic function.
450
450
451 The alias is an instance of :class:`MagicAlias`, which holds the
451 The alias is an instance of :class:`MagicAlias`, which holds the
452 name and kind of the magic it should call. Binding is done at
452 name and kind of the magic it should call. Binding is done at
453 call time, so if the underlying magic function is changed the alias
453 call time, so if the underlying magic function is changed the alias
454 will call the new function.
454 will call the new function.
455
455
456 Parameters
456 Parameters
457 ----------
457 ----------
458 alias_name : str
458 alias_name : str
459 The name of the magic to be registered.
459 The name of the magic to be registered.
460
460
461 magic_name : str
461 magic_name : str
462 The name of an existing magic.
462 The name of an existing magic.
463
463
464 magic_kind : str
464 magic_kind : str
465 Kind of magic, one of 'line' or 'cell'
465 Kind of magic, one of 'line' or 'cell'
466 """
466 """
467
467
468 # `validate_type` is too permissive, as it allows 'line_cell'
468 # `validate_type` is too permissive, as it allows 'line_cell'
469 # which we do not handle.
469 # which we do not handle.
470 if magic_kind not in magic_kinds:
470 if magic_kind not in magic_kinds:
471 raise ValueError('magic_kind must be one of %s, %s given' %
471 raise ValueError('magic_kind must be one of %s, %s given' %
472 magic_kinds, magic_kind)
472 magic_kinds, magic_kind)
473
473
474 alias = MagicAlias(self.shell, magic_name, magic_kind)
474 alias = MagicAlias(self.shell, magic_name, magic_kind)
475 setattr(self.user_magics, alias_name, alias)
475 setattr(self.user_magics, alias_name, alias)
476 record_magic(self.magics, magic_kind, alias_name, alias)
476 record_magic(self.magics, magic_kind, alias_name, alias)
477
477
478 # Key base class that provides the central functionality for magics.
478 # Key base class that provides the central functionality for magics.
479
479
480
480
481 class Magics(Configurable):
481 class Magics(Configurable):
482 """Base class for implementing magic functions.
482 """Base class for implementing magic functions.
483
483
484 Shell functions which can be reached as %function_name. All magic
484 Shell functions which can be reached as %function_name. All magic
485 functions should accept a string, which they can parse for their own
485 functions should accept a string, which they can parse for their own
486 needs. This can make some functions easier to type, eg `%cd ../`
486 needs. This can make some functions easier to type, eg `%cd ../`
487 vs. `%cd("../")`
487 vs. `%cd("../")`
488
488
489 Classes providing magic functions need to subclass this class, and they
489 Classes providing magic functions need to subclass this class, and they
490 MUST:
490 MUST:
491
491
492 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
492 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
493 individual methods as magic functions, AND
493 individual methods as magic functions, AND
494
494
495 - Use the class decorator `@magics_class` to ensure that the magic
495 - Use the class decorator `@magics_class` to ensure that the magic
496 methods are properly registered at the instance level upon instance
496 methods are properly registered at the instance level upon instance
497 initialization.
497 initialization.
498
498
499 See :mod:`magic_functions` for examples of actual implementation classes.
499 See :mod:`magic_functions` for examples of actual implementation classes.
500 """
500 """
501 # Dict holding all command-line options for each magic.
501 # Dict holding all command-line options for each magic.
502 options_table = None
502 options_table = None
503 # Dict for the mapping of magic names to methods, set by class decorator
503 # Dict for the mapping of magic names to methods, set by class decorator
504 magics = None
504 magics = None
505 # Flag to check that the class decorator was properly applied
505 # Flag to check that the class decorator was properly applied
506 registered = False
506 registered = False
507 # Instance of IPython shell
507 # Instance of IPython shell
508 shell = None
508 shell = None
509
509
510 def __init__(self, shell=None, **kwargs):
510 def __init__(self, shell=None, **kwargs):
511 if shell is not None:
511 if shell is not None:
512 kwargs['shell'] = shell
512 kwargs['shell'] = shell
513 kwargs.setdefault('parent', shell)
513 kwargs.setdefault('parent', shell)
514 super(Magics, self).__init__(**kwargs)
514 super(Magics, self).__init__(**kwargs)
515
515
516 def __init__(self, shell=None, **kwargs):
516 def __init__(self, shell=None, **kwargs):
517 if not(self.__class__.registered):
517 if not(self.__class__.registered):
518 raise ValueError('Magics subclass without registration - '
518 raise ValueError('Magics subclass without registration - '
519 'did you forget to apply @magics_class?')
519 'did you forget to apply @magics_class?')
520 if shell is not None:
520 if shell is not None:
521 if hasattr( shell, 'configurables'):
521 if hasattr(shell, 'configurables'):
522 shell.configurables.append(self)
522 shell.configurables.append(self)
523 if hasattr( shell, 'config'):
523 if hasattr(shell, 'config'):
524 kwargs.setdefault('parent', shell)
524 kwargs.setdefault('parent', shell)
525 kwargs['shell'] = shell
525 kwargs['shell'] = shell
526
526
527 self.shell = shell
527 self.shell = shell
528 self.options_table = {}
528 self.options_table = {}
529 # The method decorators are run when the instance doesn't exist yet, so
529 # The method decorators are run when the instance doesn't exist yet, so
530 # they can only record the names of the methods they are supposed to
530 # they can only record the names of the methods they are supposed to
531 # grab. Only now, that the instance exists, can we create the proper
531 # grab. Only now, that the instance exists, can we create the proper
532 # mapping to bound methods. So we read the info off the original names
532 # mapping to bound methods. So we read the info off the original names
533 # table and replace each method name by the actual bound method.
533 # table and replace each method name by the actual bound method.
534 # But we mustn't clobber the *class* mapping, in case of multiple instances.
534 # But we mustn't clobber the *class* mapping, in case of multiple instances.
535 class_magics = self.magics
535 class_magics = self.magics
536 self.magics = {}
536 self.magics = {}
537 for mtype in magic_kinds:
537 for mtype in magic_kinds:
538 tab = self.magics[mtype] = {}
538 tab = self.magics[mtype] = {}
539 cls_tab = class_magics[mtype]
539 cls_tab = class_magics[mtype]
540 for magic_name, meth_name in cls_tab.iteritems():
540 for magic_name, meth_name in cls_tab.iteritems():
541 if isinstance(meth_name, basestring):
541 if isinstance(meth_name, basestring):
542 # it's a method name, grab it
542 # it's a method name, grab it
543 tab[magic_name] = getattr(self, meth_name)
543 tab[magic_name] = getattr(self, meth_name)
544 else:
544 else:
545 # it's the real thing
545 # it's the real thing
546 tab[magic_name] = meth_name
546 tab[magic_name] = meth_name
547 # Configurable **need** to be initiated at the end or the config
547 # Configurable **need** to be initiated at the end or the config
548 # magics get screwed up.
548 # magics get screwed up.
549 super(Magics, self).__init__(**kwargs)
549 super(Magics, self).__init__(**kwargs)
550
550
551 def arg_err(self,func):
551 def arg_err(self,func):
552 """Print docstring if incorrect arguments were passed"""
552 """Print docstring if incorrect arguments were passed"""
553 print 'Error in arguments:'
553 print 'Error in arguments:'
554 print oinspect.getdoc(func)
554 print oinspect.getdoc(func)
555
555
556 def format_latex(self, strng):
556 def format_latex(self, strng):
557 """Format a string for latex inclusion."""
557 """Format a string for latex inclusion."""
558
558
559 # Characters that need to be escaped for latex:
559 # Characters that need to be escaped for latex:
560 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
560 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
561 # Magic command names as headers:
561 # Magic command names as headers:
562 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
562 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
563 re.MULTILINE)
563 re.MULTILINE)
564 # Magic commands
564 # Magic commands
565 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
565 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
566 re.MULTILINE)
566 re.MULTILINE)
567 # Paragraph continue
567 # Paragraph continue
568 par_re = re.compile(r'\\$',re.MULTILINE)
568 par_re = re.compile(r'\\$',re.MULTILINE)
569
569
570 # The "\n" symbol
570 # The "\n" symbol
571 newline_re = re.compile(r'\\n')
571 newline_re = re.compile(r'\\n')
572
572
573 # Now build the string for output:
573 # Now build the string for output:
574 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
574 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
575 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
575 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
576 strng)
576 strng)
577 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
577 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
578 strng = par_re.sub(r'\\\\',strng)
578 strng = par_re.sub(r'\\\\',strng)
579 strng = escape_re.sub(r'\\\1',strng)
579 strng = escape_re.sub(r'\\\1',strng)
580 strng = newline_re.sub(r'\\textbackslash{}n',strng)
580 strng = newline_re.sub(r'\\textbackslash{}n',strng)
581 return strng
581 return strng
582
582
583 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
583 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
584 """Parse options passed to an argument string.
584 """Parse options passed to an argument string.
585
585
586 The interface is similar to that of getopt(), but it returns back a
586 The interface is similar to that of getopt(), but it returns back a
587 Struct with the options as keys and the stripped argument string still
587 Struct with the options as keys and the stripped argument string still
588 as a string.
588 as a string.
589
589
590 arg_str is quoted as a true sys.argv vector by using shlex.split.
590 arg_str is quoted as a true sys.argv vector by using shlex.split.
591 This allows us to easily expand variables, glob files, quote
591 This allows us to easily expand variables, glob files, quote
592 arguments, etc.
592 arguments, etc.
593
593
594 Options:
594 Options:
595 -mode: default 'string'. If given as 'list', the argument string is
595 -mode: default 'string'. If given as 'list', the argument string is
596 returned as a list (split on whitespace) instead of a string.
596 returned as a list (split on whitespace) instead of a string.
597
597
598 -list_all: put all option values in lists. Normally only options
598 -list_all: put all option values in lists. Normally only options
599 appearing more than once are put in a list.
599 appearing more than once are put in a list.
600
600
601 -posix (True): whether to split the input line in POSIX mode or not,
601 -posix (True): whether to split the input line in POSIX mode or not,
602 as per the conventions outlined in the shlex module from the
602 as per the conventions outlined in the shlex module from the
603 standard library."""
603 standard library."""
604
604
605 # inject default options at the beginning of the input line
605 # inject default options at the beginning of the input line
606 caller = sys._getframe(1).f_code.co_name
606 caller = sys._getframe(1).f_code.co_name
607 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
607 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
608
608
609 mode = kw.get('mode','string')
609 mode = kw.get('mode','string')
610 if mode not in ['string','list']:
610 if mode not in ['string','list']:
611 raise ValueError('incorrect mode given: %s' % mode)
611 raise ValueError('incorrect mode given: %s' % mode)
612 # Get options
612 # Get options
613 list_all = kw.get('list_all',0)
613 list_all = kw.get('list_all',0)
614 posix = kw.get('posix', os.name == 'posix')
614 posix = kw.get('posix', os.name == 'posix')
615 strict = kw.get('strict', True)
615 strict = kw.get('strict', True)
616
616
617 # Check if we have more than one argument to warrant extra processing:
617 # Check if we have more than one argument to warrant extra processing:
618 odict = {} # Dictionary with options
618 odict = {} # Dictionary with options
619 args = arg_str.split()
619 args = arg_str.split()
620 if len(args) >= 1:
620 if len(args) >= 1:
621 # If the list of inputs only has 0 or 1 thing in it, there's no
621 # If the list of inputs only has 0 or 1 thing in it, there's no
622 # need to look for options
622 # need to look for options
623 argv = arg_split(arg_str, posix, strict)
623 argv = arg_split(arg_str, posix, strict)
624 # Do regular option processing
624 # Do regular option processing
625 try:
625 try:
626 opts,args = getopt(argv, opt_str, long_opts)
626 opts,args = getopt(argv, opt_str, long_opts)
627 except GetoptError as e:
627 except GetoptError as e:
628 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
628 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
629 " ".join(long_opts)))
629 " ".join(long_opts)))
630 for o,a in opts:
630 for o,a in opts:
631 if o.startswith('--'):
631 if o.startswith('--'):
632 o = o[2:]
632 o = o[2:]
633 else:
633 else:
634 o = o[1:]
634 o = o[1:]
635 try:
635 try:
636 odict[o].append(a)
636 odict[o].append(a)
637 except AttributeError:
637 except AttributeError:
638 odict[o] = [odict[o],a]
638 odict[o] = [odict[o],a]
639 except KeyError:
639 except KeyError:
640 if list_all:
640 if list_all:
641 odict[o] = [a]
641 odict[o] = [a]
642 else:
642 else:
643 odict[o] = a
643 odict[o] = a
644
644
645 # Prepare opts,args for return
645 # Prepare opts,args for return
646 opts = Struct(odict)
646 opts = Struct(odict)
647 if mode == 'string':
647 if mode == 'string':
648 args = ' '.join(args)
648 args = ' '.join(args)
649
649
650 return opts,args
650 return opts,args
651
651
652 def default_option(self, fn, optstr):
652 def default_option(self, fn, optstr):
653 """Make an entry in the options_table for fn, with value optstr"""
653 """Make an entry in the options_table for fn, with value optstr"""
654
654
655 if fn not in self.lsmagic():
655 if fn not in self.lsmagic():
656 error("%s is not a magic function" % fn)
656 error("%s is not a magic function" % fn)
657 self.options_table[fn] = optstr
657 self.options_table[fn] = optstr
658
658
659
659
660 class MagicAlias(object):
660 class MagicAlias(object):
661 """An alias to another magic function.
661 """An alias to another magic function.
662
662
663 An alias is determined by its magic name and magic kind. Lookup
663 An alias is determined by its magic name and magic kind. Lookup
664 is done at call time, so if the underlying magic changes the alias
664 is done at call time, so if the underlying magic changes the alias
665 will call the new function.
665 will call the new function.
666
666
667 Use the :meth:`MagicsManager.register_alias` method or the
667 Use the :meth:`MagicsManager.register_alias` method or the
668 `%alias_magic` magic function to create and register a new alias.
668 `%alias_magic` magic function to create and register a new alias.
669 """
669 """
670 def __init__(self, shell, magic_name, magic_kind):
670 def __init__(self, shell, magic_name, magic_kind):
671 self.shell = shell
671 self.shell = shell
672 self.magic_name = magic_name
672 self.magic_name = magic_name
673 self.magic_kind = magic_kind
673 self.magic_kind = magic_kind
674
674
675 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
675 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
676 self.__doc__ = "Alias for `%s`." % self.pretty_target
676 self.__doc__ = "Alias for `%s`." % self.pretty_target
677
677
678 self._in_call = False
678 self._in_call = False
679
679
680 def __call__(self, *args, **kwargs):
680 def __call__(self, *args, **kwargs):
681 """Call the magic alias."""
681 """Call the magic alias."""
682 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
682 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
683 if fn is None:
683 if fn is None:
684 raise UsageError("Magic `%s` not found." % self.pretty_target)
684 raise UsageError("Magic `%s` not found." % self.pretty_target)
685
685
686 # Protect against infinite recursion.
686 # Protect against infinite recursion.
687 if self._in_call:
687 if self._in_call:
688 raise UsageError("Infinite recursion detected; "
688 raise UsageError("Infinite recursion detected; "
689 "magic aliases cannot call themselves.")
689 "magic aliases cannot call themselves.")
690 self._in_call = True
690 self._in_call = True
691 try:
691 try:
692 return fn(*args, **kwargs)
692 return fn(*args, **kwargs)
693 finally:
693 finally:
694 self._in_call = False
694 self._in_call = False
General Comments 0
You need to be logged in to leave comments. Login now