##// END OF EJS Templates
Refactor %magic into a lsmagic_docs API function.
Bradley M. Froehle -
Show More
@@ -1,592 +1,616 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
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, 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 """Compress a directory history into a new one with at most 20 entries.
65 65
66 66 Return a new list made from the first and last 10 elements of dhist after
67 67 removal of duplicates.
68 68 """
69 69 head, tail = dh[:-10], dh[-10:]
70 70
71 71 newhead = []
72 72 done = set()
73 73 for h in head:
74 74 if h in done:
75 75 continue
76 76 newhead.append(h)
77 77 done.add(h)
78 78
79 79 return newhead + tail
80 80
81 81
82 82 def needs_local_scope(func):
83 83 """Decorator to mark magic functions which need to local scope to run."""
84 84 func.needs_local_scope = True
85 85 return func
86 86
87 87 #-----------------------------------------------------------------------------
88 88 # Class and method decorators for registering magics
89 89 #-----------------------------------------------------------------------------
90 90
91 91 def magics_class(cls):
92 92 """Class decorator for all subclasses of the main Magics class.
93 93
94 94 Any class that subclasses Magics *must* also apply this decorator, to
95 95 ensure that all the methods that have been decorated as line/cell magics
96 96 get correctly registered in the class instance. This is necessary because
97 97 when method decorators run, the class does not exist yet, so they
98 98 temporarily store their information into a module global. Application of
99 99 this class decorator copies that global data to the class instance and
100 100 clears the global.
101 101
102 102 Obviously, this mechanism is not thread-safe, which means that the
103 103 *creation* of subclasses of Magic should only be done in a single-thread
104 104 context. Instantiation of the classes has no restrictions. Given that
105 105 these classes are typically created at IPython startup time and before user
106 106 application code becomes active, in practice this should not pose any
107 107 problems.
108 108 """
109 109 cls.registered = True
110 110 cls.magics = dict(line = magics['line'],
111 111 cell = magics['cell'])
112 112 magics['line'] = {}
113 113 magics['cell'] = {}
114 114 return cls
115 115
116 116
117 117 def record_magic(dct, magic_kind, magic_name, func):
118 118 """Utility function to store a function as a magic of a specific kind.
119 119
120 120 Parameters
121 121 ----------
122 122 dct : dict
123 123 A dictionary with 'line' and 'cell' subdicts.
124 124
125 125 magic_kind : str
126 126 Kind of magic to be stored.
127 127
128 128 magic_name : str
129 129 Key to store the magic as.
130 130
131 131 func : function
132 132 Callable object to store.
133 133 """
134 134 if magic_kind == 'line_cell':
135 135 dct['line'][magic_name] = dct['cell'][magic_name] = func
136 136 else:
137 137 dct[magic_kind][magic_name] = func
138 138
139 139
140 140 def validate_type(magic_kind):
141 141 """Ensure that the given magic_kind is valid.
142 142
143 143 Check that the given magic_kind is one of the accepted spec types (stored
144 144 in the global `magic_spec`), raise ValueError otherwise.
145 145 """
146 146 if magic_kind not in magic_spec:
147 147 raise ValueError('magic_kind must be one of %s, %s given' %
148 148 magic_kinds, magic_kind)
149 149
150 150
151 151 # The docstrings for the decorator below will be fairly similar for the two
152 152 # types (method and function), so we generate them here once and reuse the
153 153 # templates below.
154 154 _docstring_template = \
155 155 """Decorate the given {0} as {1} magic.
156 156
157 157 The decorator can be used with or without arguments, as follows.
158 158
159 159 i) without arguments: it will create a {1} magic named as the {0} being
160 160 decorated::
161 161
162 162 @deco
163 163 def foo(...)
164 164
165 165 will create a {1} magic named `foo`.
166 166
167 167 ii) with one string argument: which will be used as the actual name of the
168 168 resulting magic::
169 169
170 170 @deco('bar')
171 171 def foo(...)
172 172
173 173 will create a {1} magic named `bar`.
174 174 """
175 175
176 176 # These two are decorator factories. While they are conceptually very similar,
177 177 # there are enough differences in the details that it's simpler to have them
178 178 # written as completely standalone functions rather than trying to share code
179 179 # and make a single one with convoluted logic.
180 180
181 181 def _method_magic_marker(magic_kind):
182 182 """Decorator factory for methods in Magics subclasses.
183 183 """
184 184
185 185 validate_type(magic_kind)
186 186
187 187 # This is a closure to capture the magic_kind. We could also use a class,
188 188 # but it's overkill for just that one bit of state.
189 189 def magic_deco(arg):
190 190 call = lambda f, *a, **k: f(*a, **k)
191 191
192 192 if callable(arg):
193 193 # "Naked" decorator call (just @foo, no args)
194 194 func = arg
195 195 name = func.func_name
196 196 retval = decorator(call, func)
197 197 record_magic(magics, magic_kind, name, name)
198 198 elif isinstance(arg, basestring):
199 199 # Decorator called with arguments (@foo('bar'))
200 200 name = arg
201 201 def mark(func, *a, **kw):
202 202 record_magic(magics, magic_kind, name, func.func_name)
203 203 return decorator(call, func)
204 204 retval = mark
205 205 else:
206 206 raise TypeError("Decorator can only be called with "
207 207 "string or function")
208 208 return retval
209 209
210 210 # Ensure the resulting decorator has a usable docstring
211 211 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
212 212 return magic_deco
213 213
214 214
215 215 def _function_magic_marker(magic_kind):
216 216 """Decorator factory for standalone functions.
217 217 """
218 218 validate_type(magic_kind)
219 219
220 220 # This is a closure to capture the magic_kind. We could also use a class,
221 221 # but it's overkill for just that one bit of state.
222 222 def magic_deco(arg):
223 223 call = lambda f, *a, **k: f(*a, **k)
224 224
225 225 # Find get_ipython() in the caller's namespace
226 226 caller = sys._getframe(1)
227 227 for ns in ['f_locals', 'f_globals', 'f_builtins']:
228 228 get_ipython = getattr(caller, ns).get('get_ipython')
229 229 if get_ipython is not None:
230 230 break
231 231 else:
232 232 raise NameError('Decorator can only run in context where '
233 233 '`get_ipython` exists')
234 234
235 235 ip = get_ipython()
236 236
237 237 if callable(arg):
238 238 # "Naked" decorator call (just @foo, no args)
239 239 func = arg
240 240 name = func.func_name
241 241 ip.register_magic_function(func, magic_kind, name)
242 242 retval = decorator(call, func)
243 243 elif isinstance(arg, basestring):
244 244 # Decorator called with arguments (@foo('bar'))
245 245 name = arg
246 246 def mark(func, *a, **kw):
247 247 ip.register_magic_function(func, magic_kind, name)
248 248 return decorator(call, func)
249 249 retval = mark
250 250 else:
251 251 raise TypeError("Decorator can only be called with "
252 252 "string or function")
253 253 return retval
254 254
255 255 # Ensure the resulting decorator has a usable docstring
256 256 ds = _docstring_template.format('function', magic_kind)
257 257
258 258 ds += dedent("""
259 259 Note: this decorator can only be used in a context where IPython is already
260 260 active, so that the `get_ipython()` call succeeds. You can therefore use
261 261 it in your startup files loaded after IPython initializes, but *not* in the
262 262 IPython configuration file itself, which is executed before IPython is
263 263 fully up and running. Any file located in the `startup` subdirectory of
264 264 your configuration profile will be OK in this sense.
265 265 """)
266 266
267 267 magic_deco.__doc__ = ds
268 268 return magic_deco
269 269
270 270
271 271 # Create the actual decorators for public use
272 272
273 273 # These three are used to decorate methods in class definitions
274 274 line_magic = _method_magic_marker('line')
275 275 cell_magic = _method_magic_marker('cell')
276 276 line_cell_magic = _method_magic_marker('line_cell')
277 277
278 278 # These three decorate standalone functions and perform the decoration
279 279 # immediately. They can only run where get_ipython() works
280 280 register_line_magic = _function_magic_marker('line')
281 281 register_cell_magic = _function_magic_marker('cell')
282 282 register_line_cell_magic = _function_magic_marker('line_cell')
283 283
284 284 #-----------------------------------------------------------------------------
285 285 # Core Magic classes
286 286 #-----------------------------------------------------------------------------
287 287
288 288 class MagicsManager(Configurable):
289 289 """Object that handles all magic-related functionality for IPython.
290 290 """
291 291 # Non-configurable class attributes
292 292
293 293 # A two-level dict, first keyed by magic type, then by magic function, and
294 294 # holding the actual callable object as value. This is the dict used for
295 295 # magic function dispatch
296 296 magics = Dict
297 297
298 298 # A registry of the original objects that we've been given holding magics.
299 299 registry = Dict
300 300
301 301 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
302 302
303 303 auto_magic = Bool(True, config=True, help=
304 304 "Automatically call line magics without requiring explicit % prefix")
305 305
306 306 _auto_status = [
307 307 'Automagic is OFF, % prefix IS needed for line magics.',
308 308 'Automagic is ON, % prefix IS NOT needed for line magics.']
309 309
310 310 user_magics = Instance('IPython.core.magics.UserMagics')
311 311
312 312 def __init__(self, shell=None, config=None, user_magics=None, **traits):
313 313
314 314 super(MagicsManager, self).__init__(shell=shell, config=config,
315 315 user_magics=user_magics, **traits)
316 316 self.magics = dict(line={}, cell={})
317 317 # Let's add the user_magics to the registry for uniformity, so *all*
318 318 # registered magic containers can be found there.
319 319 self.registry[user_magics.__class__.__name__] = user_magics
320 320
321 321 def auto_status(self):
322 322 """Return descriptive string with automagic status."""
323 323 return self._auto_status[self.auto_magic]
324 324
325 325 def lsmagic_info(self):
326 326 magic_list = []
327 327 for m_type in self.magics :
328 328 for m_name,mgc in self.magics[m_type].items():
329 329 try :
330 330 magic_list.append({'name':m_name,'type':m_type,'class':mgc.im_class.__name__})
331 331 except AttributeError :
332 332 magic_list.append({'name':m_name,'type':m_type,'class':'Other'})
333 333 return magic_list
334 334
335 335 def lsmagic(self):
336 336 """Return a dict of currently available magic functions.
337 337
338 338 The return dict has the keys 'line' and 'cell', corresponding to the
339 339 two types of magics we support. Each value is a list of names.
340 340 """
341 341 return self.magics
342 342
343 def lsmagic_docs(self, brief=False, missing=''):
344 """Return dict of documentation of magic functions.
345
346 The return dict has the keys 'line' and 'cell', corresponding to the
347 two types of magics we support. Each value is a dict keyed by magic
348 name whose value is the function docstring. If a docstring is
349 unavailable, the value of `missing` is used instead.
350
351 If brief is True, only the first line of each docstring will be returned.
352 """
353 docs = {}
354 for m_type in self.magics:
355 m_docs = {}
356 for m_name, m_func in self.magics[m_type].iteritems():
357 if m_func.__doc__:
358 if brief:
359 m_docs[m_name] = m_func.__doc__.split('\n', 1)[0]
360 else:
361 m_docs[m_name] = m_func.__doc__.rstrip()
362 else:
363 m_docs[m_name] = missing
364 docs[m_type] = m_docs
365 return docs
366
343 367 def register(self, *magic_objects):
344 368 """Register one or more instances of Magics.
345 369
346 370 Take one or more classes or instances of classes that subclass the main
347 371 `core.Magic` class, and register them with IPython to use the magic
348 372 functions they provide. The registration process will then ensure that
349 373 any methods that have decorated to provide line and/or cell magics will
350 374 be recognized with the `%x`/`%%x` syntax as a line/cell magic
351 375 respectively.
352 376
353 377 If classes are given, they will be instantiated with the default
354 378 constructor. If your classes need a custom constructor, you should
355 379 instanitate them first and pass the instance.
356 380
357 381 The provided arguments can be an arbitrary mix of classes and instances.
358 382
359 383 Parameters
360 384 ----------
361 385 magic_objects : one or more classes or instances
362 386 """
363 387 # Start by validating them to ensure they have all had their magic
364 388 # methods registered at the instance level
365 389 for m in magic_objects:
366 390 if not m.registered:
367 391 raise ValueError("Class of magics %r was constructed without "
368 392 "the @register_magics class decorator")
369 393 if type(m) in (type, MetaHasTraits):
370 394 # If we're given an uninstantiated class
371 395 m = m(shell=self.shell)
372 396
373 397 # Now that we have an instance, we can register it and update the
374 398 # table of callables
375 399 self.registry[m.__class__.__name__] = m
376 400 for mtype in magic_kinds:
377 401 self.magics[mtype].update(m.magics[mtype])
378 402
379 403 def register_function(self, func, magic_kind='line', magic_name=None):
380 404 """Expose a standalone function as magic function for IPython.
381 405
382 406 This will create an IPython magic (line, cell or both) from a
383 407 standalone function. The functions should have the following
384 408 signatures:
385 409
386 410 * For line magics: `def f(line)`
387 411 * For cell magics: `def f(line, cell)`
388 412 * For a function that does both: `def f(line, cell=None)`
389 413
390 414 In the latter case, the function will be called with `cell==None` when
391 415 invoked as `%f`, and with cell as a string when invoked as `%%f`.
392 416
393 417 Parameters
394 418 ----------
395 419 func : callable
396 420 Function to be registered as a magic.
397 421
398 422 magic_kind : str
399 423 Kind of magic, one of 'line', 'cell' or 'line_cell'
400 424
401 425 magic_name : optional str
402 426 If given, the name the magic will have in the IPython namespace. By
403 427 default, the name of the function itself is used.
404 428 """
405 429
406 430 # Create the new method in the user_magics and register it in the
407 431 # global table
408 432 validate_type(magic_kind)
409 433 magic_name = func.func_name if magic_name is None else magic_name
410 434 setattr(self.user_magics, magic_name, func)
411 435 record_magic(self.magics, magic_kind, magic_name, func)
412 436
413 437 def define_magic(self, name, func):
414 438 """[Deprecated] Expose own function as magic function for IPython.
415 439
416 440 Example::
417 441
418 442 def foo_impl(self, parameter_s=''):
419 443 'My very own magic!. (Use docstrings, IPython reads them).'
420 444 print 'Magic function. Passed parameter is between < >:'
421 445 print '<%s>' % parameter_s
422 446 print 'The self object is:', self
423 447
424 448 ip.define_magic('foo',foo_impl)
425 449 """
426 450 meth = types.MethodType(func, self.user_magics)
427 451 setattr(self.user_magics, name, meth)
428 452 record_magic(self.magics, 'line', name, meth)
429 453
430 454 # Key base class that provides the central functionality for magics.
431 455
432 456 class Magics(object):
433 457 """Base class for implementing magic functions.
434 458
435 459 Shell functions which can be reached as %function_name. All magic
436 460 functions should accept a string, which they can parse for their own
437 461 needs. This can make some functions easier to type, eg `%cd ../`
438 462 vs. `%cd("../")`
439 463
440 464 Classes providing magic functions need to subclass this class, and they
441 465 MUST:
442 466
443 467 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
444 468 individual methods as magic functions, AND
445 469
446 470 - Use the class decorator `@magics_class` to ensure that the magic
447 471 methods are properly registered at the instance level upon instance
448 472 initialization.
449 473
450 474 See :mod:`magic_functions` for examples of actual implementation classes.
451 475 """
452 476 # Dict holding all command-line options for each magic.
453 477 options_table = None
454 478 # Dict for the mapping of magic names to methods, set by class decorator
455 479 magics = None
456 480 # Flag to check that the class decorator was properly applied
457 481 registered = False
458 482 # Instance of IPython shell
459 483 shell = None
460 484
461 485 def __init__(self, shell):
462 486 if not(self.__class__.registered):
463 487 raise ValueError('Magics subclass without registration - '
464 488 'did you forget to apply @magics_class?')
465 489 self.shell = shell
466 490 self.options_table = {}
467 491 # The method decorators are run when the instance doesn't exist yet, so
468 492 # they can only record the names of the methods they are supposed to
469 493 # grab. Only now, that the instance exists, can we create the proper
470 494 # mapping to bound methods. So we read the info off the original names
471 495 # table and replace each method name by the actual bound method.
472 496 # But we mustn't clobber the *class* mapping, in case of multiple instances.
473 497 class_magics = self.magics
474 498 self.magics = {}
475 499 for mtype in magic_kinds:
476 500 tab = self.magics[mtype] = {}
477 501 cls_tab = class_magics[mtype]
478 502 for magic_name, meth_name in cls_tab.iteritems():
479 503 if isinstance(meth_name, basestring):
480 504 # it's a method name, grab it
481 505 tab[magic_name] = getattr(self, meth_name)
482 506 else:
483 507 # it's the real thing
484 508 tab[magic_name] = meth_name
485 509
486 510 def arg_err(self,func):
487 511 """Print docstring if incorrect arguments were passed"""
488 512 print 'Error in arguments:'
489 513 print oinspect.getdoc(func)
490 514
491 515 def format_latex(self, strng):
492 516 """Format a string for latex inclusion."""
493 517
494 518 # Characters that need to be escaped for latex:
495 519 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
496 520 # Magic command names as headers:
497 521 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
498 522 re.MULTILINE)
499 523 # Magic commands
500 524 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
501 525 re.MULTILINE)
502 526 # Paragraph continue
503 527 par_re = re.compile(r'\\$',re.MULTILINE)
504 528
505 529 # The "\n" symbol
506 530 newline_re = re.compile(r'\\n')
507 531
508 532 # Now build the string for output:
509 533 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
510 534 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
511 535 strng)
512 536 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
513 537 strng = par_re.sub(r'\\\\',strng)
514 538 strng = escape_re.sub(r'\\\1',strng)
515 539 strng = newline_re.sub(r'\\textbackslash{}n',strng)
516 540 return strng
517 541
518 542 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
519 543 """Parse options passed to an argument string.
520 544
521 545 The interface is similar to that of getopt(), but it returns back a
522 546 Struct with the options as keys and the stripped argument string still
523 547 as a string.
524 548
525 549 arg_str is quoted as a true sys.argv vector by using shlex.split.
526 550 This allows us to easily expand variables, glob files, quote
527 551 arguments, etc.
528 552
529 553 Options:
530 554 -mode: default 'string'. If given as 'list', the argument string is
531 555 returned as a list (split on whitespace) instead of a string.
532 556
533 557 -list_all: put all option values in lists. Normally only options
534 558 appearing more than once are put in a list.
535 559
536 560 -posix (True): whether to split the input line in POSIX mode or not,
537 561 as per the conventions outlined in the shlex module from the
538 562 standard library."""
539 563
540 564 # inject default options at the beginning of the input line
541 565 caller = sys._getframe(1).f_code.co_name
542 566 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
543 567
544 568 mode = kw.get('mode','string')
545 569 if mode not in ['string','list']:
546 570 raise ValueError,'incorrect mode given: %s' % mode
547 571 # Get options
548 572 list_all = kw.get('list_all',0)
549 573 posix = kw.get('posix', os.name == 'posix')
550 574 strict = kw.get('strict', True)
551 575
552 576 # Check if we have more than one argument to warrant extra processing:
553 577 odict = {} # Dictionary with options
554 578 args = arg_str.split()
555 579 if len(args) >= 1:
556 580 # If the list of inputs only has 0 or 1 thing in it, there's no
557 581 # need to look for options
558 582 argv = arg_split(arg_str, posix, strict)
559 583 # Do regular option processing
560 584 try:
561 585 opts,args = getopt(argv, opt_str, long_opts)
562 586 except GetoptError,e:
563 587 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
564 588 " ".join(long_opts)))
565 589 for o,a in opts:
566 590 if o.startswith('--'):
567 591 o = o[2:]
568 592 else:
569 593 o = o[1:]
570 594 try:
571 595 odict[o].append(a)
572 596 except AttributeError:
573 597 odict[o] = [odict[o],a]
574 598 except KeyError:
575 599 if list_all:
576 600 odict[o] = [a]
577 601 else:
578 602 odict[o] = a
579 603
580 604 # Prepare opts,args for return
581 605 opts = Struct(odict)
582 606 if mode == 'string':
583 607 args = ' '.join(args)
584 608
585 609 return opts,args
586 610
587 611 def default_option(self, fn, optstr):
588 612 """Make an entry in the options_table for fn, with value optstr"""
589 613
590 614 if fn not in self.lsmagic():
591 615 error("%s is not a magic function" % fn)
592 616 self.options_table[fn] = optstr
@@ -1,538 +1,528 b''
1 1 """Implementation of basic magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14 from __future__ import print_function
15 15
16 16 # Stdlib
17 17 import io
18 18 import sys
19 19 from pprint import pformat
20 20
21 21 # Our own packages
22 22 from IPython.core.error import UsageError
23 23 from IPython.core.inputsplitter import ESC_MAGIC
24 24 from IPython.core.magic import Magics, magics_class, line_magic
25 25 from IPython.utils.text import format_screen
26 26 from IPython.core import magic_arguments, page
27 27 from IPython.testing.skipdoctest import skip_doctest
28 28 from IPython.utils.ipstruct import Struct
29 29 from IPython.utils.path import unquote_filename
30 30 from IPython.utils.warn import warn, error
31 31
32 32 #-----------------------------------------------------------------------------
33 33 # Magics class implementation
34 34 #-----------------------------------------------------------------------------
35 35
36 36 @magics_class
37 37 class BasicMagics(Magics):
38 38 """Magics that provide central IPython functionality.
39 39
40 40 These are various magics that don't fit into specific categories but that
41 41 are all part of the base 'IPython experience'."""
42 42
43 43 def _lsmagic(self):
44 44 mesc = ESC_MAGIC
45 45 cesc = mesc*2
46 46 mman = self.shell.magics_manager
47 47 magics = mman.lsmagic()
48 48 out = ['Available line magics:',
49 49 mesc + (' '+mesc).join(sorted(magics['line'])),
50 50 '',
51 51 'Available cell magics:',
52 52 cesc + (' '+cesc).join(sorted(magics['cell'])),
53 53 '',
54 54 mman.auto_status()]
55 55 return '\n'.join(out)
56 56
57 57 @line_magic
58 58 def lsmagic(self, parameter_s=''):
59 59 """List currently available magic functions."""
60 60 print(self._lsmagic())
61 61
62 def _magic_docs(self, brief=False, rest=False):
63 """Return docstrings from magic functions."""
64 mman = self.shell.magics_manager
65 docs = mman.lsmagic_docs(brief, missing='No documentation')
66
67 if rest:
68 format_string = '**%s%s**::\n\n\t%s\n\n'
69 else:
70 format_string = '%s%s:\n\t%s\n'
71
72 return ''.join(
73 [format_string % (ESC_MAGIC, fname, fndoc)
74 for fname, fndoc in sorted(docs['line'].items())]
75 +
76 [format_string % (ESC_MAGIC*2, fname, fndoc)
77 for fname, fndoc in sorted(docs['cell'].items())]
78 )
79
62 80 @line_magic
63 81 def magic(self, parameter_s=''):
64 82 """Print information about the magic function system.
65 83
66 84 Supported formats: -latex, -brief, -rest
67 85 """
68 86
69 87 mode = ''
70 88 try:
71 89 mode = parameter_s.split()[0][1:]
72 90 if mode == 'rest':
73 91 rest_docs = []
74 92 except IndexError:
75 93 pass
76 94
77 magic_docs = []
78 escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2)
79 magics = self.shell.magics_manager.magics
80
81 for mtype in ('line', 'cell'):
82 escape = escapes[mtype]
83 for fname, fn in sorted(magics[mtype].items()):
84
85 if mode == 'brief':
86 # only first line
87 if fn.__doc__:
88 fndoc = fn.__doc__.split('\n',1)[0]
89 else:
90 fndoc = 'No documentation'
91 else:
92 if fn.__doc__:
93 fndoc = fn.__doc__.rstrip()
94 else:
95 fndoc = 'No documentation'
96
97 if mode == 'rest':
98 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %
99 (escape, fname, fndoc))
100 else:
101 magic_docs.append('%s%s:\n\t%s\n' %
102 (escape, fname, fndoc))
103
104 magic_docs = ''.join(magic_docs)
105
106 if mode == 'rest':
107 return "".join(rest_docs)
95 brief = (mode == 'brief')
96 rest = (mode == 'rest')
97 magic_docs = self._magic_docs(brief, rest)
108 98
109 99 if mode == 'latex':
110 100 print(self.format_latex(magic_docs))
111 101 return
112 102 else:
113 103 magic_docs = format_screen(magic_docs)
114 104 if mode == 'brief':
115 105 return magic_docs
116 106
117 107 out = ["""
118 108 IPython's 'magic' functions
119 109 ===========================
120 110
121 111 The magic function system provides a series of functions which allow you to
122 112 control the behavior of IPython itself, plus a lot of system-type
123 113 features. There are two kinds of magics, line-oriented and cell-oriented.
124 114
125 115 Line magics are prefixed with the % character and work much like OS
126 116 command-line calls: they get as an argument the rest of the line, where
127 117 arguments are passed without parentheses or quotes. For example, this will
128 118 time the given statement::
129 119
130 120 %timeit range(1000)
131 121
132 122 Cell magics are prefixed with a double %%, and they are functions that get as
133 123 an argument not only the rest of the line, but also the lines below it in a
134 124 separate argument. These magics are called with two arguments: the rest of the
135 125 call line and the body of the cell, consisting of the lines below the first.
136 126 For example::
137 127
138 128 %%timeit x = numpy.random.randn((100, 100))
139 129 numpy.linalg.svd(x)
140 130
141 131 will time the execution of the numpy svd routine, running the assignment of x
142 132 as part of the setup phase, which is not timed.
143 133
144 134 In a line-oriented client (the terminal or Qt console IPython), starting a new
145 135 input with %% will automatically enter cell mode, and IPython will continue
146 136 reading input until a blank line is given. In the notebook, simply type the
147 137 whole cell as one entity, but keep in mind that the %% escape can only be at
148 138 the very start of the cell.
149 139
150 140 NOTE: If you have 'automagic' enabled (via the command line option or with the
151 141 %automagic function), you don't need to type in the % explicitly for line
152 142 magics; cell magics always require an explicit '%%' escape. By default,
153 143 IPython ships with automagic on, so you should only rarely need the % escape.
154 144
155 145 Example: typing '%cd mydir' (without the quotes) changes you working directory
156 146 to 'mydir', if it exists.
157 147
158 148 For a list of the available magic functions, use %lsmagic. For a description
159 149 of any of them, type %magic_name?, e.g. '%cd?'.
160 150
161 151 Currently the magic system has the following functions:""",
162 152 magic_docs,
163 153 "Summary of magic functions (from %slsmagic):",
164 154 self._lsmagic(),
165 155 ]
166 156 page.page('\n'.join(out))
167 157
168 158
169 159 @line_magic
170 160 def page(self, parameter_s=''):
171 161 """Pretty print the object and display it through a pager.
172 162
173 163 %page [options] OBJECT
174 164
175 165 If no object is given, use _ (last output).
176 166
177 167 Options:
178 168
179 169 -r: page str(object), don't pretty-print it."""
180 170
181 171 # After a function contributed by Olivier Aubert, slightly modified.
182 172
183 173 # Process options/args
184 174 opts, args = self.parse_options(parameter_s, 'r')
185 175 raw = 'r' in opts
186 176
187 177 oname = args and args or '_'
188 178 info = self.shell._ofind(oname)
189 179 if info['found']:
190 180 txt = (raw and str or pformat)( info['obj'] )
191 181 page.page(txt)
192 182 else:
193 183 print('Object `%s` not found' % oname)
194 184
195 185 @line_magic
196 186 def profile(self, parameter_s=''):
197 187 """Print your currently active IPython profile."""
198 188 from IPython.core.application import BaseIPythonApplication
199 189 if BaseIPythonApplication.initialized():
200 190 print(BaseIPythonApplication.instance().profile)
201 191 else:
202 192 error("profile is an application-level value, but you don't appear to be in an IPython application")
203 193
204 194 @line_magic
205 195 def pprint(self, parameter_s=''):
206 196 """Toggle pretty printing on/off."""
207 197 ptformatter = self.shell.display_formatter.formatters['text/plain']
208 198 ptformatter.pprint = bool(1 - ptformatter.pprint)
209 199 print('Pretty printing has been turned',
210 200 ['OFF','ON'][ptformatter.pprint])
211 201
212 202 @line_magic
213 203 def colors(self, parameter_s=''):
214 204 """Switch color scheme for prompts, info system and exception handlers.
215 205
216 206 Currently implemented schemes: NoColor, Linux, LightBG.
217 207
218 208 Color scheme names are not case-sensitive.
219 209
220 210 Examples
221 211 --------
222 212 To get a plain black and white terminal::
223 213
224 214 %colors nocolor
225 215 """
226 216 def color_switch_err(name):
227 217 warn('Error changing %s color schemes.\n%s' %
228 218 (name, sys.exc_info()[1]))
229 219
230 220
231 221 new_scheme = parameter_s.strip()
232 222 if not new_scheme:
233 223 raise UsageError(
234 224 "%colors: you must specify a color scheme. See '%colors?'")
235 225 return
236 226 # local shortcut
237 227 shell = self.shell
238 228
239 229 import IPython.utils.rlineimpl as readline
240 230
241 231 if not shell.colors_force and \
242 232 not readline.have_readline and sys.platform == "win32":
243 233 msg = """\
244 234 Proper color support under MS Windows requires the pyreadline library.
245 235 You can find it at:
246 236 http://ipython.org/pyreadline.html
247 237 Gary's readline needs the ctypes module, from:
248 238 http://starship.python.net/crew/theller/ctypes
249 239 (Note that ctypes is already part of Python versions 2.5 and newer).
250 240
251 241 Defaulting color scheme to 'NoColor'"""
252 242 new_scheme = 'NoColor'
253 243 warn(msg)
254 244
255 245 # readline option is 0
256 246 if not shell.colors_force and not shell.has_readline:
257 247 new_scheme = 'NoColor'
258 248
259 249 # Set prompt colors
260 250 try:
261 251 shell.prompt_manager.color_scheme = new_scheme
262 252 except:
263 253 color_switch_err('prompt')
264 254 else:
265 255 shell.colors = \
266 256 shell.prompt_manager.color_scheme_table.active_scheme_name
267 257 # Set exception colors
268 258 try:
269 259 shell.InteractiveTB.set_colors(scheme = new_scheme)
270 260 shell.SyntaxTB.set_colors(scheme = new_scheme)
271 261 except:
272 262 color_switch_err('exception')
273 263
274 264 # Set info (for 'object?') colors
275 265 if shell.color_info:
276 266 try:
277 267 shell.inspector.set_active_scheme(new_scheme)
278 268 except:
279 269 color_switch_err('object inspector')
280 270 else:
281 271 shell.inspector.set_active_scheme('NoColor')
282 272
283 273 @line_magic
284 274 def xmode(self, parameter_s=''):
285 275 """Switch modes for the exception handlers.
286 276
287 277 Valid modes: Plain, Context and Verbose.
288 278
289 279 If called without arguments, acts as a toggle."""
290 280
291 281 def xmode_switch_err(name):
292 282 warn('Error changing %s exception modes.\n%s' %
293 283 (name,sys.exc_info()[1]))
294 284
295 285 shell = self.shell
296 286 new_mode = parameter_s.strip().capitalize()
297 287 try:
298 288 shell.InteractiveTB.set_mode(mode=new_mode)
299 289 print('Exception reporting mode:',shell.InteractiveTB.mode)
300 290 except:
301 291 xmode_switch_err('user')
302 292
303 293 @line_magic
304 294 def quickref(self,arg):
305 295 """ Show a quick reference sheet """
306 296 from IPython.core.usage import quick_reference
307 297 qr = quick_reference + self.magic('-brief')
308 298 page.page(qr)
309 299
310 300 @line_magic
311 301 def doctest_mode(self, parameter_s=''):
312 302 """Toggle doctest mode on and off.
313 303
314 304 This mode is intended to make IPython behave as much as possible like a
315 305 plain Python shell, from the perspective of how its prompts, exceptions
316 306 and output look. This makes it easy to copy and paste parts of a
317 307 session into doctests. It does so by:
318 308
319 309 - Changing the prompts to the classic ``>>>`` ones.
320 310 - Changing the exception reporting mode to 'Plain'.
321 311 - Disabling pretty-printing of output.
322 312
323 313 Note that IPython also supports the pasting of code snippets that have
324 314 leading '>>>' and '...' prompts in them. This means that you can paste
325 315 doctests from files or docstrings (even if they have leading
326 316 whitespace), and the code will execute correctly. You can then use
327 317 '%history -t' to see the translated history; this will give you the
328 318 input after removal of all the leading prompts and whitespace, which
329 319 can be pasted back into an editor.
330 320
331 321 With these features, you can switch into this mode easily whenever you
332 322 need to do testing and changes to doctests, without having to leave
333 323 your existing IPython session.
334 324 """
335 325
336 326 # Shorthands
337 327 shell = self.shell
338 328 pm = shell.prompt_manager
339 329 meta = shell.meta
340 330 disp_formatter = self.shell.display_formatter
341 331 ptformatter = disp_formatter.formatters['text/plain']
342 332 # dstore is a data store kept in the instance metadata bag to track any
343 333 # changes we make, so we can undo them later.
344 334 dstore = meta.setdefault('doctest_mode',Struct())
345 335 save_dstore = dstore.setdefault
346 336
347 337 # save a few values we'll need to recover later
348 338 mode = save_dstore('mode',False)
349 339 save_dstore('rc_pprint',ptformatter.pprint)
350 340 save_dstore('xmode',shell.InteractiveTB.mode)
351 341 save_dstore('rc_separate_out',shell.separate_out)
352 342 save_dstore('rc_separate_out2',shell.separate_out2)
353 343 save_dstore('rc_prompts_pad_left',pm.justify)
354 344 save_dstore('rc_separate_in',shell.separate_in)
355 345 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
356 346 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
357 347
358 348 if mode == False:
359 349 # turn on
360 350 pm.in_template = '>>> '
361 351 pm.in2_template = '... '
362 352 pm.out_template = ''
363 353
364 354 # Prompt separators like plain python
365 355 shell.separate_in = ''
366 356 shell.separate_out = ''
367 357 shell.separate_out2 = ''
368 358
369 359 pm.justify = False
370 360
371 361 ptformatter.pprint = False
372 362 disp_formatter.plain_text_only = True
373 363
374 364 shell.magic('xmode Plain')
375 365 else:
376 366 # turn off
377 367 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
378 368
379 369 shell.separate_in = dstore.rc_separate_in
380 370
381 371 shell.separate_out = dstore.rc_separate_out
382 372 shell.separate_out2 = dstore.rc_separate_out2
383 373
384 374 pm.justify = dstore.rc_prompts_pad_left
385 375
386 376 ptformatter.pprint = dstore.rc_pprint
387 377 disp_formatter.plain_text_only = dstore.rc_plain_text_only
388 378
389 379 shell.magic('xmode ' + dstore.xmode)
390 380
391 381 # Store new mode and inform
392 382 dstore.mode = bool(1-int(mode))
393 383 mode_label = ['OFF','ON'][dstore.mode]
394 384 print('Doctest mode is:', mode_label)
395 385
396 386 @line_magic
397 387 def gui(self, parameter_s=''):
398 388 """Enable or disable IPython GUI event loop integration.
399 389
400 390 %gui [GUINAME]
401 391
402 392 This magic replaces IPython's threaded shells that were activated
403 393 using the (pylab/wthread/etc.) command line flags. GUI toolkits
404 394 can now be enabled at runtime and keyboard
405 395 interrupts should work without any problems. The following toolkits
406 396 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
407 397
408 398 %gui wx # enable wxPython event loop integration
409 399 %gui qt4|qt # enable PyQt4 event loop integration
410 400 %gui gtk # enable PyGTK event loop integration
411 401 %gui gtk3 # enable Gtk3 event loop integration
412 402 %gui tk # enable Tk event loop integration
413 403 %gui osx # enable Cocoa event loop integration
414 404 # (requires %matplotlib 1.1)
415 405 %gui # disable all event loop integration
416 406
417 407 WARNING: after any of these has been called you can simply create
418 408 an application object, but DO NOT start the event loop yourself, as
419 409 we have already handled that.
420 410 """
421 411 opts, arg = self.parse_options(parameter_s, '')
422 412 if arg=='': arg = None
423 413 try:
424 414 return self.shell.enable_gui(arg)
425 415 except Exception as e:
426 416 # print simple error message, rather than traceback if we can't
427 417 # hook up the GUI
428 418 error(str(e))
429 419
430 420 @skip_doctest
431 421 @line_magic
432 422 def precision(self, s=''):
433 423 """Set floating point precision for pretty printing.
434 424
435 425 Can set either integer precision or a format string.
436 426
437 427 If numpy has been imported and precision is an int,
438 428 numpy display precision will also be set, via ``numpy.set_printoptions``.
439 429
440 430 If no argument is given, defaults will be restored.
441 431
442 432 Examples
443 433 --------
444 434 ::
445 435
446 436 In [1]: from math import pi
447 437
448 438 In [2]: %precision 3
449 439 Out[2]: u'%.3f'
450 440
451 441 In [3]: pi
452 442 Out[3]: 3.142
453 443
454 444 In [4]: %precision %i
455 445 Out[4]: u'%i'
456 446
457 447 In [5]: pi
458 448 Out[5]: 3
459 449
460 450 In [6]: %precision %e
461 451 Out[6]: u'%e'
462 452
463 453 In [7]: pi**10
464 454 Out[7]: 9.364805e+04
465 455
466 456 In [8]: %precision
467 457 Out[8]: u'%r'
468 458
469 459 In [9]: pi**10
470 460 Out[9]: 93648.047476082982
471 461 """
472 462 ptformatter = self.shell.display_formatter.formatters['text/plain']
473 463 ptformatter.float_precision = s
474 464 return ptformatter.float_format
475 465
476 466 @magic_arguments.magic_arguments()
477 467 @magic_arguments.argument(
478 468 '-e', '--export', action='store_true', default=False,
479 469 help='Export IPython history as a notebook. The filename argument '
480 470 'is used to specify the notebook name and format. For example '
481 471 'a filename of notebook.ipynb will result in a notebook name '
482 472 'of "notebook" and a format of "xml". Likewise using a ".json" '
483 473 'or ".py" file extension will write the notebook in the json '
484 474 'or py formats.'
485 475 )
486 476 @magic_arguments.argument(
487 477 '-f', '--format',
488 478 help='Convert an existing IPython notebook to a new format. This option '
489 479 'specifies the new format and can have the values: xml, json, py. '
490 480 'The target filename is chosen automatically based on the new '
491 481 'format. The filename argument gives the name of the source file.'
492 482 )
493 483 @magic_arguments.argument(
494 484 'filename', type=unicode,
495 485 help='Notebook name or filename'
496 486 )
497 487 @line_magic
498 488 def notebook(self, s):
499 489 """Export and convert IPython notebooks.
500 490
501 491 This function can export the current IPython history to a notebook file
502 492 or can convert an existing notebook file into a different format. For
503 493 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
504 494 To export the history to "foo.py" do "%notebook -e foo.py". To convert
505 495 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
506 496 formats include (json/ipynb, py).
507 497 """
508 498 args = magic_arguments.parse_argstring(self.notebook, s)
509 499
510 500 from IPython.nbformat import current
511 501 args.filename = unquote_filename(args.filename)
512 502 if args.export:
513 503 fname, name, format = current.parse_filename(args.filename)
514 504 cells = []
515 505 hist = list(self.shell.history_manager.get_range())
516 506 for session, prompt_number, input in hist[:-1]:
517 507 cells.append(current.new_code_cell(prompt_number=prompt_number,
518 508 input=input))
519 509 worksheet = current.new_worksheet(cells=cells)
520 510 nb = current.new_notebook(name=name,worksheets=[worksheet])
521 511 with io.open(fname, 'w', encoding='utf-8') as f:
522 512 current.write(nb, f, format);
523 513 elif args.format is not None:
524 514 old_fname, old_name, old_format = current.parse_filename(args.filename)
525 515 new_format = args.format
526 516 if new_format == u'xml':
527 517 raise ValueError('Notebooks cannot be written as xml.')
528 518 elif new_format == u'ipynb' or new_format == u'json':
529 519 new_fname = old_name + u'.ipynb'
530 520 new_format = u'json'
531 521 elif new_format == u'py':
532 522 new_fname = old_name + u'.py'
533 523 else:
534 524 raise ValueError('Invalid notebook format: %s' % new_format)
535 525 with io.open(old_fname, 'r', encoding='utf-8') as f:
536 526 nb = current.read(f, old_format)
537 527 with io.open(new_fname, 'w', encoding='utf-8') as f:
538 528 current.write(nb, f, new_format)
General Comments 0
You need to be logged in to leave comments. Login now