Show More
@@ -1,485 +1,485 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Stdlib |
|
17 | # Stdlib | |
18 | import os |
|
18 | import os | |
19 | import re |
|
19 | import re | |
20 | import sys |
|
20 | import sys | |
21 | import types |
|
21 | import types | |
22 | from getopt import getopt, GetoptError |
|
22 | from getopt import getopt, GetoptError | |
23 |
|
23 | |||
24 | # Our own |
|
24 | # Our own | |
25 | from IPython.config.configurable import Configurable |
|
25 | from IPython.config.configurable import Configurable | |
26 | from IPython.core import oinspect |
|
26 | from IPython.core import oinspect | |
27 | from IPython.core.error import UsageError |
|
27 | from IPython.core.error import UsageError | |
28 | from IPython.core.prefilter import ESC_MAGIC |
|
28 | from IPython.core.prefilter import ESC_MAGIC | |
29 | from IPython.external.decorator import decorator |
|
29 | from IPython.external.decorator import decorator | |
30 | from IPython.utils.ipstruct import Struct |
|
30 | from IPython.utils.ipstruct import Struct | |
31 | from IPython.utils.process import arg_split |
|
31 | from IPython.utils.process import arg_split | |
32 | from IPython.utils.text import dedent |
|
32 | from IPython.utils.text import dedent | |
33 | from IPython.utils.traitlets import Bool, Dict, Instance |
|
33 | from IPython.utils.traitlets import Bool, Dict, Instance | |
34 | from IPython.utils.warn import error, warn |
|
34 | from IPython.utils.warn import error, warn | |
35 |
|
35 | |||
36 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
37 | # Globals |
|
37 | # Globals | |
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 |
|
39 | |||
40 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
40 | # A dict we'll use for each class that has magics, used as temporary storage to | |
41 | # pass information between the @line/cell_magic method decorators and the |
|
41 | # pass information between the @line/cell_magic method decorators and the | |
42 | # @magics_class class decorator, because the method decorators have no |
|
42 | # @magics_class class decorator, because the method decorators have no | |
43 | # access to the class when they run. See for more details: |
|
43 | # access to the class when they run. See for more details: | |
44 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
44 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class | |
45 |
|
45 | |||
46 | magics = dict(line={}, cell={}) |
|
46 | magics = dict(line={}, cell={}) | |
47 |
|
47 | |||
48 | magic_kinds = ('line', 'cell') |
|
48 | magic_kinds = ('line', 'cell') | |
49 | magic_spec = ('line', 'cell', 'line_cell') |
|
49 | magic_spec = ('line', 'cell', 'line_cell') | |
50 |
|
50 | |||
51 | #----------------------------------------------------------------------------- |
|
51 | #----------------------------------------------------------------------------- | |
52 | # Utility classes and functions |
|
52 | # Utility classes and functions | |
53 | #----------------------------------------------------------------------------- |
|
53 | #----------------------------------------------------------------------------- | |
54 |
|
54 | |||
55 | class Bunch: pass |
|
55 | class Bunch: pass | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | def on_off(tag): |
|
58 | def on_off(tag): | |
59 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
59 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
60 | return ['OFF','ON'][tag] |
|
60 | return ['OFF','ON'][tag] | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | def compress_dhist(dh): |
|
63 | def compress_dhist(dh): | |
64 | head, tail = dh[:-10], dh[-10:] |
|
64 | head, tail = dh[:-10], dh[-10:] | |
65 |
|
65 | |||
66 | newhead = [] |
|
66 | newhead = [] | |
67 | done = set() |
|
67 | done = set() | |
68 | for h in head: |
|
68 | for h in head: | |
69 | if h in done: |
|
69 | if h in done: | |
70 | continue |
|
70 | continue | |
71 | newhead.append(h) |
|
71 | newhead.append(h) | |
72 | done.add(h) |
|
72 | done.add(h) | |
73 |
|
73 | |||
74 | return newhead + tail |
|
74 | return newhead + tail | |
75 |
|
75 | |||
76 |
|
76 | |||
77 | def needs_local_scope(func): |
|
77 | def needs_local_scope(func): | |
78 | """Decorator to mark magic functions which need to local scope to run.""" |
|
78 | """Decorator to mark magic functions which need to local scope to run.""" | |
79 | func.needs_local_scope = True |
|
79 | func.needs_local_scope = True | |
80 | return func |
|
80 | return func | |
81 |
|
81 | |||
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 | # Class and method decorators for registering magics |
|
83 | # Class and method decorators for registering magics | |
84 | #----------------------------------------------------------------------------- |
|
84 | #----------------------------------------------------------------------------- | |
85 |
|
85 | |||
86 | def magics_class(cls): |
|
86 | def magics_class(cls): | |
87 | cls.registered = True |
|
87 | cls.registered = True | |
88 | cls.magics = dict(line = magics['line'], |
|
88 | cls.magics = dict(line = magics['line'], | |
89 | cell = magics['cell']) |
|
89 | cell = magics['cell']) | |
90 | magics['line'] = {} |
|
90 | magics['line'] = {} | |
91 | magics['cell'] = {} |
|
91 | magics['cell'] = {} | |
92 | return cls |
|
92 | return cls | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | def record_magic(dct, mtype, mname, func): |
|
95 | def record_magic(dct, mtype, mname, func): | |
96 | if mtype == 'line_cell': |
|
96 | if mtype == 'line_cell': | |
97 | dct['line'][mname] = dct['cell'][mname] = func |
|
97 | dct['line'][mname] = dct['cell'][mname] = func | |
98 | else: |
|
98 | else: | |
99 | dct[mtype][mname] = func |
|
99 | dct[mtype][mname] = func | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | def validate_type(magic_kind): |
|
102 | def validate_type(magic_kind): | |
103 | if magic_kind not in magic_spec: |
|
103 | if magic_kind not in magic_spec: | |
104 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
104 | raise ValueError('magic_kind must be one of %s, %s given' % | |
105 | magic_kinds, magic_kind) |
|
105 | magic_kinds, magic_kind) | |
106 |
|
106 | |||
107 |
|
107 | |||
108 | # The docstrings for the decorator below will be fairly similar for the two |
|
108 | # The docstrings for the decorator below will be fairly similar for the two | |
109 | # types (method and function), so we generate them here once and reuse the |
|
109 | # types (method and function), so we generate them here once and reuse the | |
110 | # templates below. |
|
110 | # templates below. | |
111 | _docstring_template = \ |
|
111 | _docstring_template = \ | |
112 | """Decorate the given {0} as {1} magic. |
|
112 | """Decorate the given {0} as {1} magic. | |
113 |
|
113 | |||
114 | The decorator can be used with or without arguments, as follows. |
|
114 | The decorator can be used with or without arguments, as follows. | |
115 |
|
115 | |||
116 | i) without arguments: it will create a {1} magic named as the {0} being |
|
116 | i) without arguments: it will create a {1} magic named as the {0} being | |
117 | decorated:: |
|
117 | decorated:: | |
118 |
|
118 | |||
119 | @deco |
|
119 | @deco | |
120 | def foo(...) |
|
120 | def foo(...) | |
121 |
|
121 | |||
122 | will create a {1} magic named `foo`. |
|
122 | will create a {1} magic named `foo`. | |
123 |
|
123 | |||
124 | ii) with one string argument: which will be used as the actual name of the |
|
124 | ii) with one string argument: which will be used as the actual name of the | |
125 | resulting magic:: |
|
125 | resulting magic:: | |
126 |
|
126 | |||
127 | @deco('bar') |
|
127 | @deco('bar') | |
128 | def foo(...) |
|
128 | def foo(...) | |
129 |
|
129 | |||
130 | will create a {1} magic named `bar`. |
|
130 | will create a {1} magic named `bar`. | |
131 | """ |
|
131 | """ | |
132 |
|
132 | |||
133 | # These two are decorator factories. While they are conceptually very similar, |
|
133 | # These two are decorator factories. While they are conceptually very similar, | |
134 | # there are enough differences in the details that it's simpler to have them |
|
134 | # there are enough differences in the details that it's simpler to have them | |
135 | # written as completely standalone functions rather than trying to share code |
|
135 | # written as completely standalone functions rather than trying to share code | |
136 | # and make a single one with convoluted logic. |
|
136 | # and make a single one with convoluted logic. | |
137 |
|
137 | |||
138 | def _method_magic_marker(magic_kind): |
|
138 | def _method_magic_marker(magic_kind): | |
139 | """Decorator factory for methods in Magics subclasses. |
|
139 | """Decorator factory for methods in Magics subclasses. | |
140 | """ |
|
140 | """ | |
141 |
|
141 | |||
142 | validate_type(magic_kind) |
|
142 | validate_type(magic_kind) | |
143 |
|
143 | |||
144 | # This is a closure to capture the magic_kind. We could also use a class, |
|
144 | # This is a closure to capture the magic_kind. We could also use a class, | |
145 | # but it's overkill for just that one bit of state. |
|
145 | # but it's overkill for just that one bit of state. | |
146 | def magic_deco(arg): |
|
146 | def magic_deco(arg): | |
147 | call = lambda f, *a, **k: f(*a, **k) |
|
147 | call = lambda f, *a, **k: f(*a, **k) | |
148 |
|
148 | |||
149 | if callable(arg): |
|
149 | if callable(arg): | |
150 | # "Naked" decorator call (just @foo, no args) |
|
150 | # "Naked" decorator call (just @foo, no args) | |
151 | func = arg |
|
151 | func = arg | |
152 | name = func.func_name |
|
152 | name = func.func_name | |
153 | retval = decorator(call, func) |
|
153 | retval = decorator(call, func) | |
154 | record_magic(magics, magic_kind, name, name) |
|
154 | record_magic(magics, magic_kind, name, name) | |
155 | elif isinstance(arg, basestring): |
|
155 | elif isinstance(arg, basestring): | |
156 | # Decorator called with arguments (@foo('bar')) |
|
156 | # Decorator called with arguments (@foo('bar')) | |
157 | name = arg |
|
157 | name = arg | |
158 | def mark(func, *a, **kw): |
|
158 | def mark(func, *a, **kw): | |
159 | record_magic(magics, magic_kind, name, func.func_name) |
|
159 | record_magic(magics, magic_kind, name, func.func_name) | |
160 | return decorator(call, func) |
|
160 | return decorator(call, func) | |
161 | retval = mark |
|
161 | retval = mark | |
162 | else: |
|
162 | else: | |
163 | raise ValueError("Decorator can only be called with " |
|
163 | raise ValueError("Decorator can only be called with " | |
164 | "string or function") |
|
164 | "string or function") | |
165 | return retval |
|
165 | return retval | |
166 |
|
166 | |||
167 | # Ensure the resulting decorator has a usable docstring |
|
167 | # Ensure the resulting decorator has a usable docstring | |
168 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) |
|
168 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) | |
169 | return magic_deco |
|
169 | return magic_deco | |
170 |
|
170 | |||
171 |
|
171 | |||
172 | def _function_magic_marker(magic_kind): |
|
172 | def _function_magic_marker(magic_kind): | |
173 | """Decorator factory for standalone functions. |
|
173 | """Decorator factory for standalone functions. | |
174 | """ |
|
174 | """ | |
175 |
|
175 | |||
176 | validate_type(magic_kind) |
|
176 | validate_type(magic_kind) | |
177 |
|
177 | |||
178 | # This is a closure to capture the magic_kind. We could also use a class, |
|
178 | # This is a closure to capture the magic_kind. We could also use a class, | |
179 | # but it's overkill for just that one bit of state. |
|
179 | # but it's overkill for just that one bit of state. | |
180 | def magic_deco(arg): |
|
180 | def magic_deco(arg): | |
181 | call = lambda f, *a, **k: f(*a, **k) |
|
181 | call = lambda f, *a, **k: f(*a, **k) | |
182 |
|
182 | |||
183 | # Find get_ipython() in the caller's namespace |
|
183 | # Find get_ipython() in the caller's namespace | |
184 | caller = sys._getframe(1) |
|
184 | caller = sys._getframe(1) | |
185 | for ns in ['f_locals', 'f_globals', 'f_builtins']: |
|
185 | for ns in ['f_locals', 'f_globals', 'f_builtins']: | |
186 | get_ipython = getattr(caller, ns).get('get_ipython') |
|
186 | get_ipython = getattr(caller, ns).get('get_ipython') | |
187 | if get_ipython is not None: |
|
187 | if get_ipython is not None: | |
188 | break |
|
188 | break | |
189 | else: |
|
189 | else: | |
190 | raise('Decorator can only run in context where `get_ipython` exists') |
|
190 | raise('Decorator can only run in context where `get_ipython` exists') | |
191 |
|
191 | |||
192 | ip = get_ipython() |
|
192 | ip = get_ipython() | |
193 |
|
193 | |||
194 | if callable(arg): |
|
194 | if callable(arg): | |
195 | # "Naked" decorator call (just @foo, no args) |
|
195 | # "Naked" decorator call (just @foo, no args) | |
196 | func = arg |
|
196 | func = arg | |
197 | name = func.func_name |
|
197 | name = func.func_name | |
198 | ip.register_magic_function(func, magic_kind, name) |
|
198 | ip.register_magic_function(func, magic_kind, name) | |
199 | retval = decorator(call, func) |
|
199 | retval = decorator(call, func) | |
200 | elif isinstance(arg, basestring): |
|
200 | elif isinstance(arg, basestring): | |
201 | # Decorator called with arguments (@foo('bar')) |
|
201 | # Decorator called with arguments (@foo('bar')) | |
202 | name = arg |
|
202 | name = arg | |
203 | def mark(func, *a, **kw): |
|
203 | def mark(func, *a, **kw): | |
204 | ip.register_magic_function(func, magic_kind, name) |
|
204 | ip.register_magic_function(func, magic_kind, name) | |
205 | return decorator(call, func) |
|
205 | return decorator(call, func) | |
206 | retval = mark |
|
206 | retval = mark | |
207 | else: |
|
207 | else: | |
208 | raise ValueError("Decorator can only be called with " |
|
208 | raise ValueError("Decorator can only be called with " | |
209 | "string or function") |
|
209 | "string or function") | |
210 | return retval |
|
210 | return retval | |
211 |
|
211 | |||
212 | # Ensure the resulting decorator has a usable docstring |
|
212 | # Ensure the resulting decorator has a usable docstring | |
213 | ds = _docstring_template.format('function', magic_kind) |
|
213 | ds = _docstring_template.format('function', magic_kind) | |
214 |
|
214 | |||
215 | ds += dedent(""" |
|
215 | ds += dedent(""" | |
216 | Note: this decorator can only be used in a context where IPython is already |
|
216 | Note: this decorator can only be used in a context where IPython is already | |
217 | active, so that the `get_ipython()` call succeeds. You can therefore use |
|
217 | active, so that the `get_ipython()` call succeeds. You can therefore use | |
218 | it in your startup files loaded after IPython initializes, but *not* in the |
|
218 | it in your startup files loaded after IPython initializes, but *not* in the | |
219 | IPython configuration file itself, which is executed before IPython is |
|
219 | IPython configuration file itself, which is executed before IPython is | |
220 | fully up and running. Any file located in the `startup` subdirectory of |
|
220 | fully up and running. Any file located in the `startup` subdirectory of | |
221 | your configuration profile will be OK in this sense. |
|
221 | your configuration profile will be OK in this sense. | |
222 | """) |
|
222 | """) | |
223 |
|
223 | |||
224 | magic_deco.__doc__ = ds |
|
224 | magic_deco.__doc__ = ds | |
225 | return magic_deco |
|
225 | return magic_deco | |
226 |
|
226 | |||
227 |
|
227 | |||
228 | # Create the actual decorators for public use |
|
228 | # Create the actual decorators for public use | |
229 |
|
229 | |||
230 | # These three are used to decorate methods in class definitions |
|
230 | # These three are used to decorate methods in class definitions | |
231 | line_magic = _method_magic_marker('line') |
|
231 | line_magic = _method_magic_marker('line') | |
232 | cell_magic = _method_magic_marker('cell') |
|
232 | cell_magic = _method_magic_marker('cell') | |
233 | line_cell_magic = _method_magic_marker('line_cell') |
|
233 | line_cell_magic = _method_magic_marker('line_cell') | |
234 |
|
234 | |||
235 | # These three decorate standalone functions and perform the decoration |
|
235 | # These three decorate standalone functions and perform the decoration | |
236 | # immediately. They can only run where get_ipython() works |
|
236 | # immediately. They can only run where get_ipython() works | |
237 | register_line_magic = _function_magic_marker('line') |
|
237 | register_line_magic = _function_magic_marker('line') | |
238 | register_cell_magic = _function_magic_marker('cell') |
|
238 | register_cell_magic = _function_magic_marker('cell') | |
239 | register_line_cell_magic = _function_magic_marker('line_cell') |
|
239 | register_line_cell_magic = _function_magic_marker('line_cell') | |
240 |
|
240 | |||
241 | #----------------------------------------------------------------------------- |
|
241 | #----------------------------------------------------------------------------- | |
242 | # Core Magic classes |
|
242 | # Core Magic classes | |
243 | #----------------------------------------------------------------------------- |
|
243 | #----------------------------------------------------------------------------- | |
244 |
|
244 | |||
245 | class MagicsManager(Configurable): |
|
245 | class MagicsManager(Configurable): | |
246 | """Object that handles all magic-related functionality for IPython. |
|
246 | """Object that handles all magic-related functionality for IPython. | |
247 | """ |
|
247 | """ | |
248 | # Non-configurable class attributes |
|
248 | # Non-configurable class attributes | |
249 |
|
249 | |||
250 | # A two-level dict, first keyed by magic type, then by magic function, and |
|
250 | # A two-level dict, first keyed by magic type, then by magic function, and | |
251 | # holding the actual callable object as value. This is the dict used for |
|
251 | # holding the actual callable object as value. This is the dict used for | |
252 | # magic function dispatch |
|
252 | # magic function dispatch | |
253 | magics = Dict |
|
253 | magics = Dict | |
254 |
|
254 | |||
255 | # A registry of the original objects that we've been given holding magics. |
|
255 | # A registry of the original objects that we've been given holding magics. | |
256 | registry = Dict |
|
256 | registry = Dict | |
257 |
|
257 | |||
258 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
258 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
259 |
|
259 | |||
260 | auto_magic = Bool |
|
260 | auto_magic = Bool | |
261 |
|
261 | |||
262 | _auto_status = [ |
|
262 | _auto_status = [ | |
263 |
'Automagic is OFF, % prefix IS needed for magic |
|
263 | 'Automagic is OFF, % prefix IS needed for line magics.', | |
264 |
'Automagic is ON, % prefix IS NOT needed for magic |
|
264 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] | |
265 |
|
265 | |||
266 | user_magics = Instance('IPython.core.magics.UserMagics') |
|
266 | user_magics = Instance('IPython.core.magics.UserMagics') | |
267 |
|
267 | |||
268 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
268 | def __init__(self, shell=None, config=None, user_magics=None, **traits): | |
269 |
|
269 | |||
270 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
270 | super(MagicsManager, self).__init__(shell=shell, config=config, | |
271 | user_magics=user_magics, **traits) |
|
271 | user_magics=user_magics, **traits) | |
272 | self.magics = dict(line={}, cell={}) |
|
272 | self.magics = dict(line={}, cell={}) | |
273 | # Let's add the user_magics to the registry for uniformity, so *all* |
|
273 | # Let's add the user_magics to the registry for uniformity, so *all* | |
274 | # registered magic containers can be found there. |
|
274 | # registered magic containers can be found there. | |
275 | self.registry[user_magics.__class__.__name__] = user_magics |
|
275 | self.registry[user_magics.__class__.__name__] = user_magics | |
276 |
|
276 | |||
277 | def auto_status(self): |
|
277 | def auto_status(self): | |
278 | """Return descriptive string with automagic status.""" |
|
278 | """Return descriptive string with automagic status.""" | |
279 | return self._auto_status[self.auto_magic] |
|
279 | return self._auto_status[self.auto_magic] | |
280 |
|
280 | |||
281 | def lsmagic(self): |
|
281 | def lsmagic(self): | |
282 | """Return a dict of currently available magic functions. |
|
282 | """Return a dict of currently available magic functions. | |
283 |
|
283 | |||
284 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
284 | The return dict has the keys 'line' and 'cell', corresponding to the | |
285 | two types of magics we support. Each value is a list of names. |
|
285 | two types of magics we support. Each value is a list of names. | |
286 | """ |
|
286 | """ | |
287 | return self.magics |
|
287 | return self.magics | |
288 |
|
288 | |||
289 | def register(self, *magic_objects): |
|
289 | def register(self, *magic_objects): | |
290 | """Register one or more instances of Magics. |
|
290 | """Register one or more instances of Magics. | |
291 | """ |
|
291 | """ | |
292 | # Start by validating them to ensure they have all had their magic |
|
292 | # Start by validating them to ensure they have all had their magic | |
293 | # methods registered at the instance level |
|
293 | # methods registered at the instance level | |
294 | for m in magic_objects: |
|
294 | for m in magic_objects: | |
295 | if not m.registered: |
|
295 | if not m.registered: | |
296 | raise ValueError("Class of magics %r was constructed without " |
|
296 | raise ValueError("Class of magics %r was constructed without " | |
297 | "the @register_macics class decorator") |
|
297 | "the @register_macics class decorator") | |
298 | if type(m) is type: |
|
298 | if type(m) is type: | |
299 | # If we're given an uninstantiated class |
|
299 | # If we're given an uninstantiated class | |
300 | m = m(self.shell) |
|
300 | m = m(self.shell) | |
301 |
|
301 | |||
302 | # Now that we have an instance, we can register it and update the |
|
302 | # Now that we have an instance, we can register it and update the | |
303 | # table of callables |
|
303 | # table of callables | |
304 | self.registry[m.__class__.__name__] = m |
|
304 | self.registry[m.__class__.__name__] = m | |
305 | for mtype in magic_kinds: |
|
305 | for mtype in magic_kinds: | |
306 | self.magics[mtype].update(m.magics[mtype]) |
|
306 | self.magics[mtype].update(m.magics[mtype]) | |
307 |
|
307 | |||
308 | def register_function(self, func, magic_kind='line', magic_name=None): |
|
308 | def register_function(self, func, magic_kind='line', magic_name=None): | |
309 | """Expose a standalone function as magic function for ipython. |
|
309 | """Expose a standalone function as magic function for ipython. | |
310 | """ |
|
310 | """ | |
311 |
|
311 | |||
312 | # Create the new method in the user_magics and register it in the |
|
312 | # Create the new method in the user_magics and register it in the | |
313 | # global table |
|
313 | # global table | |
314 | validate_type(magic_kind) |
|
314 | validate_type(magic_kind) | |
315 | magic_name = func.func_name if magic_name is None else magic_name |
|
315 | magic_name = func.func_name if magic_name is None else magic_name | |
316 | setattr(self.user_magics, magic_name, func) |
|
316 | setattr(self.user_magics, magic_name, func) | |
317 | record_magic(self.magics, magic_kind, magic_name, func) |
|
317 | record_magic(self.magics, magic_kind, magic_name, func) | |
318 |
|
318 | |||
319 | def define_magic(self, name, func): |
|
319 | def define_magic(self, name, func): | |
320 | """Support for deprecated API. |
|
320 | """Support for deprecated API. | |
321 |
|
321 | |||
322 | This method exists only to support the old-style definition of magics. |
|
322 | This method exists only to support the old-style definition of magics. | |
323 | It will eventually be removed. Deliberately not documented further. |
|
323 | It will eventually be removed. Deliberately not documented further. | |
324 | """ |
|
324 | """ | |
325 | meth = types.MethodType(func, self.user_magics) |
|
325 | meth = types.MethodType(func, self.user_magics) | |
326 | setattr(self.user_magics, name, meth) |
|
326 | setattr(self.user_magics, name, meth) | |
327 | record_magic(self.magics, 'line', name, meth) |
|
327 | record_magic(self.magics, 'line', name, meth) | |
328 |
|
328 | |||
329 | # Key base class that provides the central functionality for magics. |
|
329 | # Key base class that provides the central functionality for magics. | |
330 |
|
330 | |||
331 | class Magics(object): |
|
331 | class Magics(object): | |
332 | """Base class for implementing magic functions. |
|
332 | """Base class for implementing magic functions. | |
333 |
|
333 | |||
334 | Shell functions which can be reached as %function_name. All magic |
|
334 | Shell functions which can be reached as %function_name. All magic | |
335 | functions should accept a string, which they can parse for their own |
|
335 | functions should accept a string, which they can parse for their own | |
336 | needs. This can make some functions easier to type, eg `%cd ../` |
|
336 | needs. This can make some functions easier to type, eg `%cd ../` | |
337 | vs. `%cd("../")` |
|
337 | vs. `%cd("../")` | |
338 |
|
338 | |||
339 | Classes providing magic functions need to subclass this class, and they |
|
339 | Classes providing magic functions need to subclass this class, and they | |
340 | MUST: |
|
340 | MUST: | |
341 |
|
341 | |||
342 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
342 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate | |
343 | individual methods as magic functions, AND |
|
343 | individual methods as magic functions, AND | |
344 |
|
344 | |||
345 | - Use the class decorator `@magics_class` to ensure that the magic |
|
345 | - Use the class decorator `@magics_class` to ensure that the magic | |
346 | methods are properly registered at the instance level upon instance |
|
346 | methods are properly registered at the instance level upon instance | |
347 | initialization. |
|
347 | initialization. | |
348 |
|
348 | |||
349 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
349 | See :mod:`magic_functions` for examples of actual implementation classes. | |
350 | """ |
|
350 | """ | |
351 | # Dict holding all command-line options for each magic. |
|
351 | # Dict holding all command-line options for each magic. | |
352 | options_table = None |
|
352 | options_table = None | |
353 | # Dict for the mapping of magic names to methods, set by class decorator |
|
353 | # Dict for the mapping of magic names to methods, set by class decorator | |
354 | magics = None |
|
354 | magics = None | |
355 | # Flag to check that the class decorator was properly applied |
|
355 | # Flag to check that the class decorator was properly applied | |
356 | registered = False |
|
356 | registered = False | |
357 | # Instance of IPython shell |
|
357 | # Instance of IPython shell | |
358 | shell = None |
|
358 | shell = None | |
359 |
|
359 | |||
360 | def __init__(self, shell): |
|
360 | def __init__(self, shell): | |
361 | if not(self.__class__.registered): |
|
361 | if not(self.__class__.registered): | |
362 | raise ValueError('Magics subclass without registration - ' |
|
362 | raise ValueError('Magics subclass without registration - ' | |
363 | 'did you forget to apply @magics_class?') |
|
363 | 'did you forget to apply @magics_class?') | |
364 | self.shell = shell |
|
364 | self.shell = shell | |
365 | self.options_table = {} |
|
365 | self.options_table = {} | |
366 | # The method decorators are run when the instance doesn't exist yet, so |
|
366 | # The method decorators are run when the instance doesn't exist yet, so | |
367 | # they can only record the names of the methods they are supposed to |
|
367 | # they can only record the names of the methods they are supposed to | |
368 | # grab. Only now, that the instance exists, can we create the proper |
|
368 | # grab. Only now, that the instance exists, can we create the proper | |
369 | # mapping to bound methods. So we read the info off the original names |
|
369 | # mapping to bound methods. So we read the info off the original names | |
370 | # table and replace each method name by the actual bound method. |
|
370 | # table and replace each method name by the actual bound method. | |
371 | for mtype in magic_kinds: |
|
371 | for mtype in magic_kinds: | |
372 | tab = self.magics[mtype] |
|
372 | tab = self.magics[mtype] | |
373 | # must explicitly use keys, as we're mutating this puppy |
|
373 | # must explicitly use keys, as we're mutating this puppy | |
374 | for magic_name in tab.keys(): |
|
374 | for magic_name in tab.keys(): | |
375 | meth_name = tab[magic_name] |
|
375 | meth_name = tab[magic_name] | |
376 | if isinstance(meth_name, basestring): |
|
376 | if isinstance(meth_name, basestring): | |
377 | tab[magic_name] = getattr(self, meth_name) |
|
377 | tab[magic_name] = getattr(self, meth_name) | |
378 |
|
378 | |||
379 | def arg_err(self,func): |
|
379 | def arg_err(self,func): | |
380 | """Print docstring if incorrect arguments were passed""" |
|
380 | """Print docstring if incorrect arguments were passed""" | |
381 | print 'Error in arguments:' |
|
381 | print 'Error in arguments:' | |
382 | print oinspect.getdoc(func) |
|
382 | print oinspect.getdoc(func) | |
383 |
|
383 | |||
384 | def format_latex(self, strng): |
|
384 | def format_latex(self, strng): | |
385 | """Format a string for latex inclusion.""" |
|
385 | """Format a string for latex inclusion.""" | |
386 |
|
386 | |||
387 | # Characters that need to be escaped for latex: |
|
387 | # Characters that need to be escaped for latex: | |
388 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
388 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
389 | # Magic command names as headers: |
|
389 | # Magic command names as headers: | |
390 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
390 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
391 | re.MULTILINE) |
|
391 | re.MULTILINE) | |
392 | # Magic commands |
|
392 | # Magic commands | |
393 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
393 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
394 | re.MULTILINE) |
|
394 | re.MULTILINE) | |
395 | # Paragraph continue |
|
395 | # Paragraph continue | |
396 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
396 | par_re = re.compile(r'\\$',re.MULTILINE) | |
397 |
|
397 | |||
398 | # The "\n" symbol |
|
398 | # The "\n" symbol | |
399 | newline_re = re.compile(r'\\n') |
|
399 | newline_re = re.compile(r'\\n') | |
400 |
|
400 | |||
401 | # Now build the string for output: |
|
401 | # Now build the string for output: | |
402 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
402 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
403 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
403 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
404 | strng) |
|
404 | strng) | |
405 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
405 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
406 | strng = par_re.sub(r'\\\\',strng) |
|
406 | strng = par_re.sub(r'\\\\',strng) | |
407 | strng = escape_re.sub(r'\\\1',strng) |
|
407 | strng = escape_re.sub(r'\\\1',strng) | |
408 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
408 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
409 | return strng |
|
409 | return strng | |
410 |
|
410 | |||
411 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
411 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): | |
412 | """Parse options passed to an argument string. |
|
412 | """Parse options passed to an argument string. | |
413 |
|
413 | |||
414 | The interface is similar to that of getopt(), but it returns back a |
|
414 | The interface is similar to that of getopt(), but it returns back a | |
415 | Struct with the options as keys and the stripped argument string still |
|
415 | Struct with the options as keys and the stripped argument string still | |
416 | as a string. |
|
416 | as a string. | |
417 |
|
417 | |||
418 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
418 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
419 | This allows us to easily expand variables, glob files, quote |
|
419 | This allows us to easily expand variables, glob files, quote | |
420 | arguments, etc. |
|
420 | arguments, etc. | |
421 |
|
421 | |||
422 | Options: |
|
422 | Options: | |
423 | -mode: default 'string'. If given as 'list', the argument string is |
|
423 | -mode: default 'string'. If given as 'list', the argument string is | |
424 | returned as a list (split on whitespace) instead of a string. |
|
424 | returned as a list (split on whitespace) instead of a string. | |
425 |
|
425 | |||
426 | -list_all: put all option values in lists. Normally only options |
|
426 | -list_all: put all option values in lists. Normally only options | |
427 | appearing more than once are put in a list. |
|
427 | appearing more than once are put in a list. | |
428 |
|
428 | |||
429 | -posix (True): whether to split the input line in POSIX mode or not, |
|
429 | -posix (True): whether to split the input line in POSIX mode or not, | |
430 | as per the conventions outlined in the shlex module from the |
|
430 | as per the conventions outlined in the shlex module from the | |
431 | standard library.""" |
|
431 | standard library.""" | |
432 |
|
432 | |||
433 | # inject default options at the beginning of the input line |
|
433 | # inject default options at the beginning of the input line | |
434 | caller = sys._getframe(1).f_code.co_name |
|
434 | caller = sys._getframe(1).f_code.co_name | |
435 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
435 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
436 |
|
436 | |||
437 | mode = kw.get('mode','string') |
|
437 | mode = kw.get('mode','string') | |
438 | if mode not in ['string','list']: |
|
438 | if mode not in ['string','list']: | |
439 | raise ValueError,'incorrect mode given: %s' % mode |
|
439 | raise ValueError,'incorrect mode given: %s' % mode | |
440 | # Get options |
|
440 | # Get options | |
441 | list_all = kw.get('list_all',0) |
|
441 | list_all = kw.get('list_all',0) | |
442 | posix = kw.get('posix', os.name == 'posix') |
|
442 | posix = kw.get('posix', os.name == 'posix') | |
443 | strict = kw.get('strict', True) |
|
443 | strict = kw.get('strict', True) | |
444 |
|
444 | |||
445 | # Check if we have more than one argument to warrant extra processing: |
|
445 | # Check if we have more than one argument to warrant extra processing: | |
446 | odict = {} # Dictionary with options |
|
446 | odict = {} # Dictionary with options | |
447 | args = arg_str.split() |
|
447 | args = arg_str.split() | |
448 | if len(args) >= 1: |
|
448 | if len(args) >= 1: | |
449 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
449 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
450 | # need to look for options |
|
450 | # need to look for options | |
451 | argv = arg_split(arg_str, posix, strict) |
|
451 | argv = arg_split(arg_str, posix, strict) | |
452 | # Do regular option processing |
|
452 | # Do regular option processing | |
453 | try: |
|
453 | try: | |
454 | opts,args = getopt(argv,opt_str,*long_opts) |
|
454 | opts,args = getopt(argv,opt_str,*long_opts) | |
455 | except GetoptError,e: |
|
455 | except GetoptError,e: | |
456 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
456 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
457 | " ".join(long_opts))) |
|
457 | " ".join(long_opts))) | |
458 | for o,a in opts: |
|
458 | for o,a in opts: | |
459 | if o.startswith('--'): |
|
459 | if o.startswith('--'): | |
460 | o = o[2:] |
|
460 | o = o[2:] | |
461 | else: |
|
461 | else: | |
462 | o = o[1:] |
|
462 | o = o[1:] | |
463 | try: |
|
463 | try: | |
464 | odict[o].append(a) |
|
464 | odict[o].append(a) | |
465 | except AttributeError: |
|
465 | except AttributeError: | |
466 | odict[o] = [odict[o],a] |
|
466 | odict[o] = [odict[o],a] | |
467 | except KeyError: |
|
467 | except KeyError: | |
468 | if list_all: |
|
468 | if list_all: | |
469 | odict[o] = [a] |
|
469 | odict[o] = [a] | |
470 | else: |
|
470 | else: | |
471 | odict[o] = a |
|
471 | odict[o] = a | |
472 |
|
472 | |||
473 | # Prepare opts,args for return |
|
473 | # Prepare opts,args for return | |
474 | opts = Struct(odict) |
|
474 | opts = Struct(odict) | |
475 | if mode == 'string': |
|
475 | if mode == 'string': | |
476 | args = ' '.join(args) |
|
476 | args = ' '.join(args) | |
477 |
|
477 | |||
478 | return opts,args |
|
478 | return opts,args | |
479 |
|
479 | |||
480 | def default_option(self, fn, optstr): |
|
480 | def default_option(self, fn, optstr): | |
481 | """Make an entry in the options_table for fn, with value optstr""" |
|
481 | """Make an entry in the options_table for fn, with value optstr""" | |
482 |
|
482 | |||
483 | if fn not in self.lsmagic(): |
|
483 | if fn not in self.lsmagic(): | |
484 | error("%s is not a magic function" % fn) |
|
484 | error("%s is not a magic function" % fn) | |
485 | self.options_table[fn] = optstr |
|
485 | self.options_table[fn] = optstr |
General Comments 0
You need to be logged in to leave comments.
Login now