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