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