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