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