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