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