##// END OF EJS Templates
MagicAlias: Make __doc__ an instance variable rather than a property....
Bradley M. Froehle -
Show More
@@ -1,689 +1,683 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, 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 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 _auto_status = [
307 _auto_status = [
308 'Automagic is OFF, % prefix IS needed for line magics.',
308 'Automagic is OFF, % prefix IS needed for line magics.',
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
309 'Automagic is ON, % prefix IS NOT needed for line magics.']
310
310
311 user_magics = Instance('IPython.core.magics.UserMagics')
311 user_magics = Instance('IPython.core.magics.UserMagics')
312
312
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
313 def __init__(self, shell=None, config=None, user_magics=None, **traits):
314
314
315 super(MagicsManager, self).__init__(shell=shell, config=config,
315 super(MagicsManager, self).__init__(shell=shell, config=config,
316 user_magics=user_magics, **traits)
316 user_magics=user_magics, **traits)
317 self.magics = dict(line={}, cell={})
317 self.magics = dict(line={}, cell={})
318 # Let's add the user_magics to the registry for uniformity, so *all*
318 # Let's add the user_magics to the registry for uniformity, so *all*
319 # registered magic containers can be found there.
319 # registered magic containers can be found there.
320 self.registry[user_magics.__class__.__name__] = user_magics
320 self.registry[user_magics.__class__.__name__] = user_magics
321
321
322 def auto_status(self):
322 def auto_status(self):
323 """Return descriptive string with automagic status."""
323 """Return descriptive string with automagic status."""
324 return self._auto_status[self.auto_magic]
324 return self._auto_status[self.auto_magic]
325
325
326 def lsmagic_info(self):
326 def lsmagic_info(self):
327 magic_list = []
327 magic_list = []
328 for m_type in self.magics :
328 for m_type in self.magics :
329 for m_name,mgc in self.magics[m_type].items():
329 for m_name,mgc in self.magics[m_type].items():
330 try :
330 try :
331 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
331 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
332 except AttributeError :
332 except AttributeError :
333 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
333 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
334 return magic_list
334 return magic_list
335
335
336 def lsmagic(self):
336 def lsmagic(self):
337 """Return a dict of currently available magic functions.
337 """Return a dict of currently available magic functions.
338
338
339 The return dict has the keys 'line' and 'cell', corresponding to the
339 The return dict has the keys 'line' and 'cell', corresponding to the
340 two types of magics we support. Each value is a list of names.
340 two types of magics we support. Each value is a list of names.
341 """
341 """
342 return self.magics
342 return self.magics
343
343
344 def lsmagic_docs(self, brief=False, missing=''):
344 def lsmagic_docs(self, brief=False, missing=''):
345 """Return dict of documentation of magic functions.
345 """Return dict of documentation of magic functions.
346
346
347 The return dict has the keys 'line' and 'cell', corresponding to the
347 The return dict has the keys 'line' and 'cell', corresponding to the
348 two types of magics we support. Each value is a dict keyed by magic
348 two types of magics we support. Each value is a dict keyed by magic
349 name whose value is the function docstring. If a docstring is
349 name whose value is the function docstring. If a docstring is
350 unavailable, the value of `missing` is used instead.
350 unavailable, the value of `missing` is used instead.
351
351
352 If brief is True, only the first line of each docstring will be returned.
352 If brief is True, only the first line of each docstring will be returned.
353 """
353 """
354 docs = {}
354 docs = {}
355 for m_type in self.magics:
355 for m_type in self.magics:
356 m_docs = {}
356 m_docs = {}
357 for m_name, m_func in self.magics[m_type].iteritems():
357 for m_name, m_func in self.magics[m_type].iteritems():
358 if m_func.__doc__:
358 if m_func.__doc__:
359 if brief:
359 if brief:
360 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
360 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
361 else:
361 else:
362 m_docs[m_name] = m_func.__doc__.rstrip()
362 m_docs[m_name] = m_func.__doc__.rstrip()
363 else:
363 else:
364 m_docs[m_name] = missing
364 m_docs[m_name] = missing
365 docs[m_type] = m_docs
365 docs[m_type] = m_docs
366 return docs
366 return docs
367
367
368 def register(self, *magic_objects):
368 def register(self, *magic_objects):
369 """Register one or more instances of Magics.
369 """Register one or more instances of Magics.
370
370
371 Take one or more classes or instances of classes that subclass the main
371 Take one or more classes or instances of classes that subclass the main
372 `core.Magic` class, and register them with IPython to use the magic
372 `core.Magic` class, and register them with IPython to use the magic
373 functions they provide. The registration process will then ensure that
373 functions they provide. The registration process will then ensure that
374 any methods that have decorated to provide line and/or cell magics will
374 any methods that have decorated to provide line and/or cell magics will
375 be recognized with the `%x`/`%%x` syntax as a line/cell magic
375 be recognized with the `%x`/`%%x` syntax as a line/cell magic
376 respectively.
376 respectively.
377
377
378 If classes are given, they will be instantiated with the default
378 If classes are given, they will be instantiated with the default
379 constructor. If your classes need a custom constructor, you should
379 constructor. If your classes need a custom constructor, you should
380 instanitate them first and pass the instance.
380 instanitate them first and pass the instance.
381
381
382 The provided arguments can be an arbitrary mix of classes and instances.
382 The provided arguments can be an arbitrary mix of classes and instances.
383
383
384 Parameters
384 Parameters
385 ----------
385 ----------
386 magic_objects : one or more classes or instances
386 magic_objects : one or more classes or instances
387 """
387 """
388 # Start by validating them to ensure they have all had their magic
388 # Start by validating them to ensure they have all had their magic
389 # methods registered at the instance level
389 # methods registered at the instance level
390 for m in magic_objects:
390 for m in magic_objects:
391 if not m.registered:
391 if not m.registered:
392 raise ValueError("Class of magics %r was constructed without "
392 raise ValueError("Class of magics %r was constructed without "
393 "the @register_magics class decorator")
393 "the @register_magics class decorator")
394 if type(m) in (type, MetaHasTraits):
394 if type(m) in (type, MetaHasTraits):
395 # If we're given an uninstantiated class
395 # If we're given an uninstantiated class
396 m = m(shell=self.shell)
396 m = m(shell=self.shell)
397
397
398 # Now that we have an instance, we can register it and update the
398 # Now that we have an instance, we can register it and update the
399 # table of callables
399 # table of callables
400 self.registry[m.__class__.__name__] = m
400 self.registry[m.__class__.__name__] = m
401 for mtype in magic_kinds:
401 for mtype in magic_kinds:
402 self.magics[mtype].update(m.magics[mtype])
402 self.magics[mtype].update(m.magics[mtype])
403
403
404 def register_function(self, func, magic_kind='line', magic_name=None):
404 def register_function(self, func, magic_kind='line', magic_name=None):
405 """Expose a standalone function as magic function for IPython.
405 """Expose a standalone function as magic function for IPython.
406
406
407 This will create an IPython magic (line, cell or both) from a
407 This will create an IPython magic (line, cell or both) from a
408 standalone function. The functions should have the following
408 standalone function. The functions should have the following
409 signatures:
409 signatures:
410
410
411 * For line magics: `def f(line)`
411 * For line magics: `def f(line)`
412 * For cell magics: `def f(line, cell)`
412 * For cell magics: `def f(line, cell)`
413 * For a function that does both: `def f(line, cell=None)`
413 * For a function that does both: `def f(line, cell=None)`
414
414
415 In the latter case, the function will be called with `cell==None` when
415 In the latter case, the function will be called with `cell==None` when
416 invoked as `%f`, and with cell as a string when invoked as `%%f`.
416 invoked as `%f`, and with cell as a string when invoked as `%%f`.
417
417
418 Parameters
418 Parameters
419 ----------
419 ----------
420 func : callable
420 func : callable
421 Function to be registered as a magic.
421 Function to be registered as a magic.
422
422
423 magic_kind : str
423 magic_kind : str
424 Kind of magic, one of 'line', 'cell' or 'line_cell'
424 Kind of magic, one of 'line', 'cell' or 'line_cell'
425
425
426 magic_name : optional str
426 magic_name : optional str
427 If given, the name the magic will have in the IPython namespace. By
427 If given, the name the magic will have in the IPython namespace. By
428 default, the name of the function itself is used.
428 default, the name of the function itself is used.
429 """
429 """
430
430
431 # Create the new method in the user_magics and register it in the
431 # Create the new method in the user_magics and register it in the
432 # global table
432 # global table
433 validate_type(magic_kind)
433 validate_type(magic_kind)
434 magic_name = func.func_name if magic_name is None else magic_name
434 magic_name = func.func_name if magic_name is None else magic_name
435 setattr(self.user_magics, magic_name, func)
435 setattr(self.user_magics, magic_name, func)
436 record_magic(self.magics, magic_kind, magic_name, func)
436 record_magic(self.magics, magic_kind, magic_name, func)
437
437
438 def define_magic(self, name, func):
438 def define_magic(self, name, func):
439 """[Deprecated] Expose own function as magic function for IPython.
439 """[Deprecated] Expose own function as magic function for IPython.
440
440
441 Example::
441 Example::
442
442
443 def foo_impl(self, parameter_s=''):
443 def foo_impl(self, parameter_s=''):
444 'My very own magic!. (Use docstrings, IPython reads them).'
444 'My very own magic!. (Use docstrings, IPython reads them).'
445 print 'Magic function. Passed parameter is between < >:'
445 print 'Magic function. Passed parameter is between < >:'
446 print '<%s>' % parameter_s
446 print '<%s>' % parameter_s
447 print 'The self object is:', self
447 print 'The self object is:', self
448
448
449 ip.define_magic('foo',foo_impl)
449 ip.define_magic('foo',foo_impl)
450 """
450 """
451 meth = types.MethodType(func, self.user_magics)
451 meth = types.MethodType(func, self.user_magics)
452 setattr(self.user_magics, name, meth)
452 setattr(self.user_magics, name, meth)
453 record_magic(self.magics, 'line', name, meth)
453 record_magic(self.magics, 'line', name, meth)
454
454
455 def register_alias(self, alias_name, magic_name, magic_kind='line'):
455 def register_alias(self, alias_name, magic_name, magic_kind='line'):
456 """Register an alias to a magic function.
456 """Register an alias to a magic function.
457
457
458 The alias is an instance of :class:`MagicAlias`, which holds the
458 The alias is an instance of :class:`MagicAlias`, which holds the
459 name and kind of the magic it should call. Binding is done at
459 name and kind of the magic it should call. Binding is done at
460 call time, so if the underlying magic function is changed the alias
460 call time, so if the underlying magic function is changed the alias
461 will call the new function.
461 will call the new function.
462
462
463 Parameters
463 Parameters
464 ----------
464 ----------
465 alias_name : str
465 alias_name : str
466 The name of the magic to be registered.
466 The name of the magic to be registered.
467
467
468 magic_name : str
468 magic_name : str
469 The name of an existing magic.
469 The name of an existing magic.
470
470
471 magic_kind : str
471 magic_kind : str
472 Kind of magic, one of 'line' or 'cell'
472 Kind of magic, one of 'line' or 'cell'
473 """
473 """
474
474
475 # `validate_type` is too permissive, as it allows 'line_cell'
475 # `validate_type` is too permissive, as it allows 'line_cell'
476 # which we do not handle.
476 # which we do not handle.
477 if magic_kind not in magic_kinds:
477 if magic_kind not in magic_kinds:
478 raise ValueError('magic_kind must be one of %s, %s given' %
478 raise ValueError('magic_kind must be one of %s, %s given' %
479 magic_kinds, magic_kind)
479 magic_kinds, magic_kind)
480
480
481 alias = MagicAlias(self.shell, magic_name, magic_kind)
481 alias = MagicAlias(self.shell, magic_name, magic_kind)
482 setattr(self.user_magics, alias_name, alias)
482 setattr(self.user_magics, alias_name, alias)
483 record_magic(self.magics, magic_kind, alias_name, alias)
483 record_magic(self.magics, magic_kind, alias_name, alias)
484
484
485 # Key base class that provides the central functionality for magics.
485 # Key base class that provides the central functionality for magics.
486
486
487 class Magics(object):
487 class Magics(object):
488 """Base class for implementing magic functions.
488 """Base class for implementing magic functions.
489
489
490 Shell functions which can be reached as %function_name. All magic
490 Shell functions which can be reached as %function_name. All magic
491 functions should accept a string, which they can parse for their own
491 functions should accept a string, which they can parse for their own
492 needs. This can make some functions easier to type, eg `%cd ../`
492 needs. This can make some functions easier to type, eg `%cd ../`
493 vs. `%cd("../")`
493 vs. `%cd("../")`
494
494
495 Classes providing magic functions need to subclass this class, and they
495 Classes providing magic functions need to subclass this class, and they
496 MUST:
496 MUST:
497
497
498 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
498 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
499 individual methods as magic functions, AND
499 individual methods as magic functions, AND
500
500
501 - Use the class decorator `@magics_class` to ensure that the magic
501 - Use the class decorator `@magics_class` to ensure that the magic
502 methods are properly registered at the instance level upon instance
502 methods are properly registered at the instance level upon instance
503 initialization.
503 initialization.
504
504
505 See :mod:`magic_functions` for examples of actual implementation classes.
505 See :mod:`magic_functions` for examples of actual implementation classes.
506 """
506 """
507 # Dict holding all command-line options for each magic.
507 # Dict holding all command-line options for each magic.
508 options_table = None
508 options_table = None
509 # Dict for the mapping of magic names to methods, set by class decorator
509 # Dict for the mapping of magic names to methods, set by class decorator
510 magics = None
510 magics = None
511 # Flag to check that the class decorator was properly applied
511 # Flag to check that the class decorator was properly applied
512 registered = False
512 registered = False
513 # Instance of IPython shell
513 # Instance of IPython shell
514 shell = None
514 shell = None
515
515
516 def __init__(self, shell):
516 def __init__(self, shell):
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 self.shell = shell
520 self.shell = shell
521 self.options_table = {}
521 self.options_table = {}
522 # The method decorators are run when the instance doesn't exist yet, so
522 # The method decorators are run when the instance doesn't exist yet, so
523 # they can only record the names of the methods they are supposed to
523 # they can only record the names of the methods they are supposed to
524 # grab. Only now, that the instance exists, can we create the proper
524 # grab. Only now, that the instance exists, can we create the proper
525 # mapping to bound methods. So we read the info off the original names
525 # mapping to bound methods. So we read the info off the original names
526 # table and replace each method name by the actual bound method.
526 # table and replace each method name by the actual bound method.
527 # But we mustn't clobber the *class* mapping, in case of multiple instances.
527 # But we mustn't clobber the *class* mapping, in case of multiple instances.
528 class_magics = self.magics
528 class_magics = self.magics
529 self.magics = {}
529 self.magics = {}
530 for mtype in magic_kinds:
530 for mtype in magic_kinds:
531 tab = self.magics[mtype] = {}
531 tab = self.magics[mtype] = {}
532 cls_tab = class_magics[mtype]
532 cls_tab = class_magics[mtype]
533 for magic_name, meth_name in cls_tab.iteritems():
533 for magic_name, meth_name in cls_tab.iteritems():
534 if isinstance(meth_name, basestring):
534 if isinstance(meth_name, basestring):
535 # it's a method name, grab it
535 # it's a method name, grab it
536 tab[magic_name] = getattr(self, meth_name)
536 tab[magic_name] = getattr(self, meth_name)
537 else:
537 else:
538 # it's the real thing
538 # it's the real thing
539 tab[magic_name] = meth_name
539 tab[magic_name] = meth_name
540
540
541 def arg_err(self,func):
541 def arg_err(self,func):
542 """Print docstring if incorrect arguments were passed"""
542 """Print docstring if incorrect arguments were passed"""
543 print 'Error in arguments:'
543 print 'Error in arguments:'
544 print oinspect.getdoc(func)
544 print oinspect.getdoc(func)
545
545
546 def format_latex(self, strng):
546 def format_latex(self, strng):
547 """Format a string for latex inclusion."""
547 """Format a string for latex inclusion."""
548
548
549 # Characters that need to be escaped for latex:
549 # Characters that need to be escaped for latex:
550 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
550 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
551 # Magic command names as headers:
551 # Magic command names as headers:
552 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
552 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
553 re.MULTILINE)
553 re.MULTILINE)
554 # Magic commands
554 # Magic commands
555 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
555 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
556 re.MULTILINE)
556 re.MULTILINE)
557 # Paragraph continue
557 # Paragraph continue
558 par_re = re.compile(r'\\$',re.MULTILINE)
558 par_re = re.compile(r'\\$',re.MULTILINE)
559
559
560 # The "\n" symbol
560 # The "\n" symbol
561 newline_re = re.compile(r'\\n')
561 newline_re = re.compile(r'\\n')
562
562
563 # Now build the string for output:
563 # Now build the string for output:
564 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
564 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
565 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
565 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
566 strng)
566 strng)
567 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
567 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
568 strng = par_re.sub(r'\\\\',strng)
568 strng = par_re.sub(r'\\\\',strng)
569 strng = escape_re.sub(r'\\\1',strng)
569 strng = escape_re.sub(r'\\\1',strng)
570 strng = newline_re.sub(r'\\textbackslash{}n',strng)
570 strng = newline_re.sub(r'\\textbackslash{}n',strng)
571 return strng
571 return strng
572
572
573 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
573 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
574 """Parse options passed to an argument string.
574 """Parse options passed to an argument string.
575
575
576 The interface is similar to that of getopt(), but it returns back a
576 The interface is similar to that of getopt(), but it returns back a
577 Struct with the options as keys and the stripped argument string still
577 Struct with the options as keys and the stripped argument string still
578 as a string.
578 as a string.
579
579
580 arg_str is quoted as a true sys.argv vector by using shlex.split.
580 arg_str is quoted as a true sys.argv vector by using shlex.split.
581 This allows us to easily expand variables, glob files, quote
581 This allows us to easily expand variables, glob files, quote
582 arguments, etc.
582 arguments, etc.
583
583
584 Options:
584 Options:
585 -mode: default 'string'. If given as 'list', the argument string is
585 -mode: default 'string'. If given as 'list', the argument string is
586 returned as a list (split on whitespace) instead of a string.
586 returned as a list (split on whitespace) instead of a string.
587
587
588 -list_all: put all option values in lists. Normally only options
588 -list_all: put all option values in lists. Normally only options
589 appearing more than once are put in a list.
589 appearing more than once are put in a list.
590
590
591 -posix (True): whether to split the input line in POSIX mode or not,
591 -posix (True): whether to split the input line in POSIX mode or not,
592 as per the conventions outlined in the shlex module from the
592 as per the conventions outlined in the shlex module from the
593 standard library."""
593 standard library."""
594
594
595 # inject default options at the beginning of the input line
595 # inject default options at the beginning of the input line
596 caller = sys._getframe(1).f_code.co_name
596 caller = sys._getframe(1).f_code.co_name
597 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
597 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
598
598
599 mode = kw.get('mode','string')
599 mode = kw.get('mode','string')
600 if mode not in ['string','list']:
600 if mode not in ['string','list']:
601 raise ValueError('incorrect mode given: %s' % mode)
601 raise ValueError('incorrect mode given: %s' % mode)
602 # Get options
602 # Get options
603 list_all = kw.get('list_all',0)
603 list_all = kw.get('list_all',0)
604 posix = kw.get('posix', os.name == 'posix')
604 posix = kw.get('posix', os.name == 'posix')
605 strict = kw.get('strict', True)
605 strict = kw.get('strict', True)
606
606
607 # Check if we have more than one argument to warrant extra processing:
607 # Check if we have more than one argument to warrant extra processing:
608 odict = {} # Dictionary with options
608 odict = {} # Dictionary with options
609 args = arg_str.split()
609 args = arg_str.split()
610 if len(args) >= 1:
610 if len(args) >= 1:
611 # If the list of inputs only has 0 or 1 thing in it, there's no
611 # If the list of inputs only has 0 or 1 thing in it, there's no
612 # need to look for options
612 # need to look for options
613 argv = arg_split(arg_str, posix, strict)
613 argv = arg_split(arg_str, posix, strict)
614 # Do regular option processing
614 # Do regular option processing
615 try:
615 try:
616 opts,args = getopt(argv, opt_str, long_opts)
616 opts,args = getopt(argv, opt_str, long_opts)
617 except GetoptError as e:
617 except GetoptError as e:
618 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
618 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
619 " ".join(long_opts)))
619 " ".join(long_opts)))
620 for o,a in opts:
620 for o,a in opts:
621 if o.startswith('--'):
621 if o.startswith('--'):
622 o = o[2:]
622 o = o[2:]
623 else:
623 else:
624 o = o[1:]
624 o = o[1:]
625 try:
625 try:
626 odict[o].append(a)
626 odict[o].append(a)
627 except AttributeError:
627 except AttributeError:
628 odict[o] = [odict[o],a]
628 odict[o] = [odict[o],a]
629 except KeyError:
629 except KeyError:
630 if list_all:
630 if list_all:
631 odict[o] = [a]
631 odict[o] = [a]
632 else:
632 else:
633 odict[o] = a
633 odict[o] = a
634
634
635 # Prepare opts,args for return
635 # Prepare opts,args for return
636 opts = Struct(odict)
636 opts = Struct(odict)
637 if mode == 'string':
637 if mode == 'string':
638 args = ' '.join(args)
638 args = ' '.join(args)
639
639
640 return opts,args
640 return opts,args
641
641
642 def default_option(self, fn, optstr):
642 def default_option(self, fn, optstr):
643 """Make an entry in the options_table for fn, with value optstr"""
643 """Make an entry in the options_table for fn, with value optstr"""
644
644
645 if fn not in self.lsmagic():
645 if fn not in self.lsmagic():
646 error("%s is not a magic function" % fn)
646 error("%s is not a magic function" % fn)
647 self.options_table[fn] = optstr
647 self.options_table[fn] = optstr
648
648
649 class MagicAlias(object):
649 class MagicAlias(object):
650 """Store a magic alias.
650 """An alias to another magic function.
651
651
652 An alias is determined by its magic name and magic kind. Lookup
652 An alias is determined by its magic name and magic kind. Lookup
653 is done at call time, so if the underlying magic changes the alias
653 is done at call time, so if the underlying magic changes the alias
654 will call the new function.
654 will call the new function.
655
655
656 Use the :meth:`MagicsManager.register_alias` method or the
656 Use the :meth:`MagicsManager.register_alias` method or the
657 `%alias_magic` magic function to create and register a new alias.
657 `%alias_magic` magic function to create and register a new alias.
658 """
658 """
659 def __init__(self, shell, magic_name, magic_kind):
659 def __init__(self, shell, magic_name, magic_kind):
660 self.shell = shell
660 self.shell = shell
661 self.magic_name = magic_name
661 self.magic_name = magic_name
662 self.magic_kind = magic_kind
662 self.magic_kind = magic_kind
663
663
664 self._in_call = False
664 self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
665
665 self.__doc__ = "Alias for `%s`." % self.pretty_target
666 @property
667 def pretty_target(self):
668 """A formatted version of the target of the alias."""
669 return '%s%s' % (magic_escapes[self.magic_kind], self.magic_name)
670
666
671 @property
667 self._in_call = False
672 def __doc__(self):
673 return "Alias for `%s`." % self.pretty_target
674
668
675 def __call__(self, *args, **kwargs):
669 def __call__(self, *args, **kwargs):
676 """Call the magic alias."""
670 """Call the magic alias."""
677 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
671 fn = self.shell.find_magic(self.magic_name, self.magic_kind)
678 if fn is None:
672 if fn is None:
679 raise UsageError("Magic `%s` not found." % self.pretty_target)
673 raise UsageError("Magic `%s` not found." % self.pretty_target)
680
674
681 # Protect against infinite recursion.
675 # Protect against infinite recursion.
682 if self._in_call:
676 if self._in_call:
683 raise UsageError("Infinite recursion detected; "
677 raise UsageError("Infinite recursion detected; "
684 "magic aliases cannot call themselves.")
678 "magic aliases cannot call themselves.")
685 self._in_call = True
679 self._in_call = True
686 try:
680 try:
687 return fn(*args, **kwargs)
681 return fn(*args, **kwargs)
688 finally:
682 finally:
689 self._in_call = False
683 self._in_call = False
General Comments 0
You need to be logged in to leave comments. Login now