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