##// END OF EJS Templates
Create core.magics.basic according to new API.
Fernando Perez -
Show More
This diff has been collapsed as it changes many lines, (513 lines changed) Show them Hide them
@@ -0,0 +1,513 b''
1 """Implementation of basic magic functions.
2 """
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
10
11 #-----------------------------------------------------------------------------
12 # Imports
13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
15
16 # Stdlib
17 import io
18 import sys
19 from pprint import pformat
20
21 # Our own packages
22 from IPython.core.error import UsageError
23 from IPython.core.magic import Magics, register_magics, line_magic
24 from IPython.core.prefilter import ESC_MAGIC
25 from IPython.utils.text import format_screen
26 from IPython.core import magic_arguments, page
27 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.utils.ipstruct import Struct
29 from IPython.utils.path import unquote_filename
30 from IPython.utils.warn import warn, error
31
32 #-----------------------------------------------------------------------------
33 # Magics class implementation
34 #-----------------------------------------------------------------------------
35
36 @register_magics
37 class BasicMagics(Magics):
38 """Magics that provide central IPython functionality.
39
40 These are various magics that don't fit into specific categories but that
41 are all part of the base 'IPython experience'."""
42
43 def _lsmagic(self):
44 mesc = ESC_MAGIC
45 cesc = mesc*2
46 mman = self.shell.magics_manager
47 magics = mman.lsmagic()
48 out = ['Available line magics:',
49 mesc + (' '+mesc).join(magics['line']),
50 '',
51 'Available cell magics:',
52 cesc + (' '+cesc).join(magics['cell']),
53 '',
54 mman.auto_status()]
55 return '\n'.join(out)
56
57 @line_magic
58 def lsmagic(self, parameter_s=''):
59 """List currently available magic functions."""
60 print(self._lsmagic())
61
62 @line_magic
63 def magic(self, parameter_s=''):
64 """Print information about the magic function system.
65
66 Supported formats: -latex, -brief, -rest
67 """
68
69 mode = ''
70 try:
71 mode = parameter_s.split()[0][1:]
72 if mode == 'rest':
73 rest_docs = []
74 except:
75 pass
76
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 magics[mtype].iteritems():
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)
108
109 if mode == 'latex':
110 print(self.format_latex(magic_docs))
111 return
112 else:
113 magic_docs = format_screen(magic_docs)
114 if mode == 'brief':
115 return magic_docs
116
117 out = ["""
118 IPython's 'magic' functions
119 ===========================
120
121 The magic function system provides a series of functions which allow you to
122 control the behavior of IPython itself, plus a lot of system-type
123 features. All these functions are prefixed with a % character, but parameters
124 are given without parentheses or quotes.
125
126 NOTE: If you have 'automagic' enabled (via the command line option or with the
127 %automagic function), you don't need to type in the % explicitly. By default,
128 IPython ships with automagic on, so you should only rarely need the % escape.
129
130 Example: typing '%cd mydir' (without the quotes) changes you working directory
131 to 'mydir', if it exists.
132
133 For a list of the available magic functions, use %lsmagic. For a description
134 of any of them, type %magic_name?, e.g. '%cd?'.
135
136 Currently the magic system has the following functions:""",
137 magic_docs,
138 "Summary of magic functions (from %slsmagic):",
139 self._lsmagic(),
140 ]
141 page.page('\n'.join(out))
142
143
144 @line_magic
145 def page(self, parameter_s=''):
146 """Pretty print the object and display it through a pager.
147
148 %page [options] OBJECT
149
150 If no object is given, use _ (last output).
151
152 Options:
153
154 -r: page str(object), don't pretty-print it."""
155
156 # After a function contributed by Olivier Aubert, slightly modified.
157
158 # Process options/args
159 opts, args = self.parse_options(parameter_s, 'r')
160 raw = 'r' in opts
161
162 oname = args and args or '_'
163 info = self._ofind(oname)
164 if info['found']:
165 txt = (raw and str or pformat)( info['obj'] )
166 page.page(txt)
167 else:
168 print('Object `%s` not found' % oname)
169
170 @line_magic
171 def profile(self, parameter_s=''):
172 """Print your currently active IPython profile."""
173 from IPython.core.application import BaseIPythonApplication
174 if BaseIPythonApplication.initialized():
175 print(BaseIPythonApplication.instance().profile)
176 else:
177 error("profile is an application-level value, but you don't appear to be in an IPython application")
178
179 @line_magic
180 def pprint(self, parameter_s=''):
181 """Toggle pretty printing on/off."""
182 ptformatter = self.shell.display_formatter.formatters['text/plain']
183 ptformatter.pprint = bool(1 - ptformatter.pprint)
184 print('Pretty printing has been turned',
185 ['OFF','ON'][ptformatter.pprint])
186
187 @line_magic
188 def colors(self, parameter_s=''):
189 """Switch color scheme for prompts, info system and exception handlers.
190
191 Currently implemented schemes: NoColor, Linux, LightBG.
192
193 Color scheme names are not case-sensitive.
194
195 Examples
196 --------
197 To get a plain black and white terminal::
198
199 %colors nocolor
200 """
201 def color_switch_err(name):
202 warn('Error changing %s color schemes.\n%s' %
203 (name, sys.exc_info()[1]))
204
205
206 new_scheme = parameter_s.strip()
207 if not new_scheme:
208 raise UsageError(
209 "%colors: you must specify a color scheme. See '%colors?'")
210 return
211 # local shortcut
212 shell = self.shell
213
214 import IPython.utils.rlineimpl as readline
215
216 if not shell.colors_force and \
217 not readline.have_readline and sys.platform == "win32":
218 msg = """\
219 Proper color support under MS Windows requires the pyreadline library.
220 You can find it at:
221 http://ipython.org/pyreadline.html
222 Gary's readline needs the ctypes module, from:
223 http://starship.python.net/crew/theller/ctypes
224 (Note that ctypes is already part of Python versions 2.5 and newer).
225
226 Defaulting color scheme to 'NoColor'"""
227 new_scheme = 'NoColor'
228 warn(msg)
229
230 # readline option is 0
231 if not shell.colors_force and not shell.has_readline:
232 new_scheme = 'NoColor'
233
234 # Set prompt colors
235 try:
236 shell.prompt_manager.color_scheme = new_scheme
237 except:
238 color_switch_err('prompt')
239 else:
240 shell.colors = \
241 shell.prompt_manager.color_scheme_table.active_scheme_name
242 # Set exception colors
243 try:
244 shell.InteractiveTB.set_colors(scheme = new_scheme)
245 shell.SyntaxTB.set_colors(scheme = new_scheme)
246 except:
247 color_switch_err('exception')
248
249 # Set info (for 'object?') colors
250 if shell.color_info:
251 try:
252 shell.inspector.set_active_scheme(new_scheme)
253 except:
254 color_switch_err('object inspector')
255 else:
256 shell.inspector.set_active_scheme('NoColor')
257
258 @line_magic
259 def xmode(self, parameter_s=''):
260 """Switch modes for the exception handlers.
261
262 Valid modes: Plain, Context and Verbose.
263
264 If called without arguments, acts as a toggle."""
265
266 def xmode_switch_err(name):
267 warn('Error changing %s exception modes.\n%s' %
268 (name,sys.exc_info()[1]))
269
270 shell = self.shell
271 new_mode = parameter_s.strip().capitalize()
272 try:
273 shell.InteractiveTB.set_mode(mode=new_mode)
274 print('Exception reporting mode:',shell.InteractiveTB.mode)
275 except:
276 xmode_switch_err('user')
277
278 @line_magic
279 def quickref(self,arg):
280 """ Show a quick reference sheet """
281 from IPython.core.usage import quick_reference
282 qr = quick_reference + self.magic('-brief')
283 page.page(qr)
284
285 @line_magic
286 def doctest_mode(self, parameter_s=''):
287 """Toggle doctest mode on and off.
288
289 This mode is intended to make IPython behave as much as possible like a
290 plain Python shell, from the perspective of how its prompts, exceptions
291 and output look. This makes it easy to copy and paste parts of a
292 session into doctests. It does so by:
293
294 - Changing the prompts to the classic ``>>>`` ones.
295 - Changing the exception reporting mode to 'Plain'.
296 - Disabling pretty-printing of output.
297
298 Note that IPython also supports the pasting of code snippets that have
299 leading '>>>' and '...' prompts in them. This means that you can paste
300 doctests from files or docstrings (even if they have leading
301 whitespace), and the code will execute correctly. You can then use
302 '%history -t' to see the translated history; this will give you the
303 input after removal of all the leading prompts and whitespace, which
304 can be pasted back into an editor.
305
306 With these features, you can switch into this mode easily whenever you
307 need to do testing and changes to doctests, without having to leave
308 your existing IPython session.
309 """
310
311 # Shorthands
312 shell = self.shell
313 pm = shell.prompt_manager
314 meta = shell.meta
315 disp_formatter = self.shell.display_formatter
316 ptformatter = disp_formatter.formatters['text/plain']
317 # dstore is a data store kept in the instance metadata bag to track any
318 # changes we make, so we can undo them later.
319 dstore = meta.setdefault('doctest_mode',Struct())
320 save_dstore = dstore.setdefault
321
322 # save a few values we'll need to recover later
323 mode = save_dstore('mode',False)
324 save_dstore('rc_pprint',ptformatter.pprint)
325 save_dstore('xmode',shell.InteractiveTB.mode)
326 save_dstore('rc_separate_out',shell.separate_out)
327 save_dstore('rc_separate_out2',shell.separate_out2)
328 save_dstore('rc_prompts_pad_left',pm.justify)
329 save_dstore('rc_separate_in',shell.separate_in)
330 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
331 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
332
333 if mode == False:
334 # turn on
335 pm.in_template = '>>> '
336 pm.in2_template = '... '
337 pm.out_template = ''
338
339 # Prompt separators like plain python
340 shell.separate_in = ''
341 shell.separate_out = ''
342 shell.separate_out2 = ''
343
344 pm.justify = False
345
346 ptformatter.pprint = False
347 disp_formatter.plain_text_only = True
348
349 shell.magic('xmode Plain')
350 else:
351 # turn off
352 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
353
354 shell.separate_in = dstore.rc_separate_in
355
356 shell.separate_out = dstore.rc_separate_out
357 shell.separate_out2 = dstore.rc_separate_out2
358
359 pm.justify = dstore.rc_prompts_pad_left
360
361 ptformatter.pprint = dstore.rc_pprint
362 disp_formatter.plain_text_only = dstore.rc_plain_text_only
363
364 shell.magic('xmode ' + dstore.xmode)
365
366 # Store new mode and inform
367 dstore.mode = bool(1-int(mode))
368 mode_label = ['OFF','ON'][dstore.mode]
369 print('Doctest mode is:', mode_label)
370
371 @line_magic
372 def gui(self, parameter_s=''):
373 """Enable or disable IPython GUI event loop integration.
374
375 %gui [GUINAME]
376
377 This magic replaces IPython's threaded shells that were activated
378 using the (pylab/wthread/etc.) command line flags. GUI toolkits
379 can now be enabled at runtime and keyboard
380 interrupts should work without any problems. The following toolkits
381 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
382
383 %gui wx # enable wxPython event loop integration
384 %gui qt4|qt # enable PyQt4 event loop integration
385 %gui gtk # enable PyGTK event loop integration
386 %gui gtk3 # enable Gtk3 event loop integration
387 %gui tk # enable Tk event loop integration
388 %gui OSX # enable Cocoa event loop integration
389 # (requires %matplotlib 1.1)
390 %gui # disable all event loop integration
391
392 WARNING: after any of these has been called you can simply create
393 an application object, but DO NOT start the event loop yourself, as
394 we have already handled that.
395 """
396 opts, arg = self.parse_options(parameter_s, '')
397 if arg=='': arg = None
398 try:
399 return self.enable_gui(arg)
400 except Exception as e:
401 # print simple error message, rather than traceback if we can't
402 # hook up the GUI
403 error(str(e))
404
405 @skip_doctest
406 @line_magic
407 def precision(self, s=''):
408 """Set floating point precision for pretty printing.
409
410 Can set either integer precision or a format string.
411
412 If numpy has been imported and precision is an int,
413 numpy display precision will also be set, via ``numpy.set_printoptions``.
414
415 If no argument is given, defaults will be restored.
416
417 Examples
418 --------
419 ::
420
421 In [1]: from math import pi
422
423 In [2]: %precision 3
424 Out[2]: u'%.3f'
425
426 In [3]: pi
427 Out[3]: 3.142
428
429 In [4]: %precision %i
430 Out[4]: u'%i'
431
432 In [5]: pi
433 Out[5]: 3
434
435 In [6]: %precision %e
436 Out[6]: u'%e'
437
438 In [7]: pi**10
439 Out[7]: 9.364805e+04
440
441 In [8]: %precision
442 Out[8]: u'%r'
443
444 In [9]: pi**10
445 Out[9]: 93648.047476082982
446 """
447 ptformatter = self.shell.display_formatter.formatters['text/plain']
448 ptformatter.float_precision = s
449 return ptformatter.float_format
450
451 @magic_arguments.magic_arguments()
452 @magic_arguments.argument(
453 '-e', '--export', action='store_true', default=False,
454 help='Export IPython history as a notebook. The filename argument '
455 'is used to specify the notebook name and format. For example '
456 'a filename of notebook.ipynb will result in a notebook name '
457 'of "notebook" and a format of "xml". Likewise using a ".json" '
458 'or ".py" file extension will write the notebook in the json '
459 'or py formats.'
460 )
461 @magic_arguments.argument(
462 '-f', '--format',
463 help='Convert an existing IPython notebook to a new format. This option '
464 'specifies the new format and can have the values: xml, json, py. '
465 'The target filename is chosen automatically based on the new '
466 'format. The filename argument gives the name of the source file.'
467 )
468 @magic_arguments.argument(
469 'filename', type=unicode,
470 help='Notebook name or filename'
471 )
472 @line_magic
473 def notebook(self, s):
474 """Export and convert IPython notebooks.
475
476 This function can export the current IPython history to a notebook file
477 or can convert an existing notebook file into a different format. For
478 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
479 To export the history to "foo.py" do "%notebook -e foo.py". To convert
480 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
481 formats include (json/ipynb, py).
482 """
483 args = magic_arguments.parse_argstring(self.notebook, s)
484
485 from IPython.nbformat import current
486 args.filename = unquote_filename(args.filename)
487 if args.export:
488 fname, name, format = current.parse_filename(args.filename)
489 cells = []
490 hist = list(self.shell.history_manager.get_range())
491 for session, prompt_number, input in hist[:-1]:
492 cells.append(current.new_code_cell(prompt_number=prompt_number,
493 input=input))
494 worksheet = current.new_worksheet(cells=cells)
495 nb = current.new_notebook(name=name,worksheets=[worksheet])
496 with io.open(fname, 'w', encoding='utf-8') as f:
497 current.write(nb, f, format);
498 elif args.format is not None:
499 old_fname, old_name, old_format = current.parse_filename(args.filename)
500 new_format = args.format
501 if new_format == u'xml':
502 raise ValueError('Notebooks cannot be written as xml.')
503 elif new_format == u'ipynb' or new_format == u'json':
504 new_fname = old_name + u'.ipynb'
505 new_format = u'json'
506 elif new_format == u'py':
507 new_fname = old_name + u'.py'
508 else:
509 raise ValueError('Invalid notebook format: %s' % new_format)
510 with io.open(old_fname, 'r', encoding='utf-8') as f:
511 nb = current.read(f, old_format)
512 with io.open(new_fname, 'w', encoding='utf-8') as f:
513 current.write(nb, f, new_format)
@@ -2005,7 +2005,7 b' class InteractiveShell(SingletonConfigurable):'
2005 self.register_magic_function = self.magics_manager.register_function
2005 self.register_magic_function = self.magics_manager.register_function
2006 self.define_magic = self.magics_manager.define_magic
2006 self.define_magic = self.magics_manager.define_magic
2007
2007
2008 self.register_magics(mf.BasicMagics, mf.CodeMagics, mf.ConfigMagics,
2008 self.register_magics(m.BasicMagics, mf.CodeMagics, mf.ConfigMagics,
2009 mf.ExecutionMagics, mf.NamespaceMagics, mf.AutoMagics,
2009 mf.ExecutionMagics, mf.NamespaceMagics, mf.AutoMagics,
2010 mf.OSMagics, mf.LoggingMagics, mf.ExtensionsMagics,
2010 mf.OSMagics, mf.LoggingMagics, mf.ExtensionsMagics,
2011 mf.PylabMagics, m.HistoryMagics, mf.DeprecatedMagics)
2011 mf.PylabMagics, m.HistoryMagics, mf.DeprecatedMagics)
@@ -40,13 +40,12 b' except ImportError:'
40
40
41 from IPython.config.application import Application
41 from IPython.config.application import Application
42 from IPython.core import debugger, oinspect
42 from IPython.core import debugger, oinspect
43 from IPython.core import magic_arguments, page
43 from IPython.core import page
44 from IPython.core.error import UsageError, StdinNotImplementedError, TryNext
44 from IPython.core.error import UsageError, StdinNotImplementedError, TryNext
45 from IPython.core.macro import Macro
45 from IPython.core.macro import Macro
46 from IPython.core.magic import (Bunch, Magics, compress_dhist,
46 from IPython.core.magic import (Bunch, Magics, compress_dhist,
47 on_off, needs_local_scope,
47 on_off, needs_local_scope,
48 register_magics, line_magic, cell_magic)
48 register_magics, line_magic, cell_magic)
49 from IPython.core.prefilter import ESC_MAGIC
50 from IPython.testing.skipdoctest import skip_doctest
49 from IPython.testing.skipdoctest import skip_doctest
51 from IPython.utils import openpy
50 from IPython.utils import openpy
52 from IPython.utils import py3compat
51 from IPython.utils import py3compat
@@ -57,489 +56,9 b' from IPython.utils.module_paths import find_mod'
57 from IPython.utils.path import get_py_filename, unquote_filename
56 from IPython.utils.path import get_py_filename, unquote_filename
58 from IPython.utils.process import abbrev_cwd
57 from IPython.utils.process import abbrev_cwd
59 from IPython.utils.terminal import set_term_title
58 from IPython.utils.terminal import set_term_title
60 from IPython.utils.text import format_screen
61 from IPython.utils.timing import clock, clock2
59 from IPython.utils.timing import clock, clock2
62 from IPython.utils.warn import warn, error
60 from IPython.utils.warn import warn, error
63
61
64 @register_magics
65 class BasicMagics(Magics):
66 """Magics that provide central IPython functionality.
67
68 These are various magics that don't fit into specific categories but that
69 are all part of the base 'IPython experience'."""
70
71 def _lsmagic(self):
72 mesc = ESC_MAGIC
73 cesc = mesc*2
74 mman = self.shell.magics_manager
75 magics = mman.lsmagic()
76 out = ['Available line magics:',
77 mesc + (' '+mesc).join(magics['line']),
78 '',
79 'Available cell magics:',
80 cesc + (' '+cesc).join(magics['cell']),
81 '',
82 mman.auto_status()]
83 return '\n'.join(out)
84
85 @line_magic
86 def lsmagic(self, parameter_s=''):
87 """List currently available magic functions."""
88 print self._lsmagic()
89
90 @line_magic
91 def magic(self, parameter_s=''):
92 """Print information about the magic function system.
93
94 Supported formats: -latex, -brief, -rest
95 """
96
97 mode = ''
98 try:
99 mode = parameter_s.split()[0][1:]
100 if mode == 'rest':
101 rest_docs = []
102 except:
103 pass
104
105 magic_docs = []
106 escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2)
107 magics = self.shell.magics_manager.magics
108
109 for mtype in ('line', 'cell'):
110 escape = escapes[mtype]
111 for fname, fn in magics[mtype].iteritems():
112
113 if mode == 'brief':
114 # only first line
115 if fn.__doc__:
116 fndoc = fn.__doc__.split('\n',1)[0]
117 else:
118 fndoc = 'No documentation'
119 else:
120 if fn.__doc__:
121 fndoc = fn.__doc__.rstrip()
122 else:
123 fndoc = 'No documentation'
124
125 if mode == 'rest':
126 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %
127 (escape, fname, fndoc))
128 else:
129 magic_docs.append('%s%s:\n\t%s\n' %
130 (escape, fname, fndoc))
131
132 magic_docs = ''.join(magic_docs)
133
134 if mode == 'rest':
135 return "".join(rest_docs)
136
137 if mode == 'latex':
138 print self.format_latex(magic_docs)
139 return
140 else:
141 magic_docs = format_screen(magic_docs)
142 if mode == 'brief':
143 return magic_docs
144
145 out = ["""
146 IPython's 'magic' functions
147 ===========================
148
149 The magic function system provides a series of functions which allow you to
150 control the behavior of IPython itself, plus a lot of system-type
151 features. All these functions are prefixed with a % character, but parameters
152 are given without parentheses or quotes.
153
154 NOTE: If you have 'automagic' enabled (via the command line option or with the
155 %automagic function), you don't need to type in the % explicitly. By default,
156 IPython ships with automagic on, so you should only rarely need the % escape.
157
158 Example: typing '%cd mydir' (without the quotes) changes you working directory
159 to 'mydir', if it exists.
160
161 For a list of the available magic functions, use %lsmagic. For a description
162 of any of them, type %magic_name?, e.g. '%cd?'.
163
164 Currently the magic system has the following functions:""",
165 magic_docs,
166 "Summary of magic functions (from %slsmagic):",
167 self._lsmagic(),
168 ]
169 page.page('\n'.join(out))
170
171
172 @line_magic
173 def page(self, parameter_s=''):
174 """Pretty print the object and display it through a pager.
175
176 %page [options] OBJECT
177
178 If no object is given, use _ (last output).
179
180 Options:
181
182 -r: page str(object), don't pretty-print it."""
183
184 # After a function contributed by Olivier Aubert, slightly modified.
185
186 # Process options/args
187 opts, args = self.parse_options(parameter_s, 'r')
188 raw = 'r' in opts
189
190 oname = args and args or '_'
191 info = self._ofind(oname)
192 if info['found']:
193 txt = (raw and str or pformat)( info['obj'] )
194 page.page(txt)
195 else:
196 print 'Object `%s` not found' % oname
197
198 @line_magic
199 def profile(self, parameter_s=''):
200 """Print your currently active IPython profile."""
201 from IPython.core.application import BaseIPythonApplication
202 if BaseIPythonApplication.initialized():
203 print BaseIPythonApplication.instance().profile
204 else:
205 error("profile is an application-level value, but you don't appear to be in an IPython application")
206
207 @line_magic
208 def pprint(self, parameter_s=''):
209 """Toggle pretty printing on/off."""
210 ptformatter = self.shell.display_formatter.formatters['text/plain']
211 ptformatter.pprint = bool(1 - ptformatter.pprint)
212 print 'Pretty printing has been turned', \
213 ['OFF','ON'][ptformatter.pprint]
214
215 @line_magic
216 def colors(self, parameter_s=''):
217 """Switch color scheme for prompts, info system and exception handlers.
218
219 Currently implemented schemes: NoColor, Linux, LightBG.
220
221 Color scheme names are not case-sensitive.
222
223 Examples
224 --------
225 To get a plain black and white terminal::
226
227 %colors nocolor
228 """
229 def color_switch_err(name):
230 warn('Error changing %s color schemes.\n%s' %
231 (name,sys.exc_info()[1]))
232
233
234 new_scheme = parameter_s.strip()
235 if not new_scheme:
236 raise UsageError(
237 "%colors: you must specify a color scheme. See '%colors?'")
238 return
239 # local shortcut
240 shell = self.shell
241
242 import IPython.utils.rlineimpl as readline
243
244 if not shell.colors_force and \
245 not readline.have_readline and sys.platform == "win32":
246 msg = """\
247 Proper color support under MS Windows requires the pyreadline library.
248 You can find it at:
249 http://ipython.org/pyreadline.html
250 Gary's readline needs the ctypes module, from:
251 http://starship.python.net/crew/theller/ctypes
252 (Note that ctypes is already part of Python versions 2.5 and newer).
253
254 Defaulting color scheme to 'NoColor'"""
255 new_scheme = 'NoColor'
256 warn(msg)
257
258 # readline option is 0
259 if not shell.colors_force and not shell.has_readline:
260 new_scheme = 'NoColor'
261
262 # Set prompt colors
263 try:
264 shell.prompt_manager.color_scheme = new_scheme
265 except:
266 color_switch_err('prompt')
267 else:
268 shell.colors = \
269 shell.prompt_manager.color_scheme_table.active_scheme_name
270 # Set exception colors
271 try:
272 shell.InteractiveTB.set_colors(scheme = new_scheme)
273 shell.SyntaxTB.set_colors(scheme = new_scheme)
274 except:
275 color_switch_err('exception')
276
277 # Set info (for 'object?') colors
278 if shell.color_info:
279 try:
280 shell.inspector.set_active_scheme(new_scheme)
281 except:
282 color_switch_err('object inspector')
283 else:
284 shell.inspector.set_active_scheme('NoColor')
285
286 @line_magic
287 def xmode(self, parameter_s=''):
288 """Switch modes for the exception handlers.
289
290 Valid modes: Plain, Context and Verbose.
291
292 If called without arguments, acts as a toggle."""
293
294 def xmode_switch_err(name):
295 warn('Error changing %s exception modes.\n%s' %
296 (name,sys.exc_info()[1]))
297
298 shell = self.shell
299 new_mode = parameter_s.strip().capitalize()
300 try:
301 shell.InteractiveTB.set_mode(mode=new_mode)
302 print 'Exception reporting mode:',shell.InteractiveTB.mode
303 except:
304 xmode_switch_err('user')
305
306 @line_magic
307 def quickref(self,arg):
308 """ Show a quick reference sheet """
309 from IPython.core.usage import quick_reference
310 qr = quick_reference + self.magic('-brief')
311 page.page(qr)
312
313 @line_magic
314 def doctest_mode(self, parameter_s=''):
315 """Toggle doctest mode on and off.
316
317 This mode is intended to make IPython behave as much as possible like a
318 plain Python shell, from the perspective of how its prompts, exceptions
319 and output look. This makes it easy to copy and paste parts of a
320 session into doctests. It does so by:
321
322 - Changing the prompts to the classic ``>>>`` ones.
323 - Changing the exception reporting mode to 'Plain'.
324 - Disabling pretty-printing of output.
325
326 Note that IPython also supports the pasting of code snippets that have
327 leading '>>>' and '...' prompts in them. This means that you can paste
328 doctests from files or docstrings (even if they have leading
329 whitespace), and the code will execute correctly. You can then use
330 '%history -t' to see the translated history; this will give you the
331 input after removal of all the leading prompts and whitespace, which
332 can be pasted back into an editor.
333
334 With these features, you can switch into this mode easily whenever you
335 need to do testing and changes to doctests, without having to leave
336 your existing IPython session.
337 """
338
339 # Shorthands
340 shell = self.shell
341 pm = shell.prompt_manager
342 meta = shell.meta
343 disp_formatter = self.shell.display_formatter
344 ptformatter = disp_formatter.formatters['text/plain']
345 # dstore is a data store kept in the instance metadata bag to track any
346 # changes we make, so we can undo them later.
347 dstore = meta.setdefault('doctest_mode',Struct())
348 save_dstore = dstore.setdefault
349
350 # save a few values we'll need to recover later
351 mode = save_dstore('mode',False)
352 save_dstore('rc_pprint',ptformatter.pprint)
353 save_dstore('xmode',shell.InteractiveTB.mode)
354 save_dstore('rc_separate_out',shell.separate_out)
355 save_dstore('rc_separate_out2',shell.separate_out2)
356 save_dstore('rc_prompts_pad_left',pm.justify)
357 save_dstore('rc_separate_in',shell.separate_in)
358 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
359 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
360
361 if mode == False:
362 # turn on
363 pm.in_template = '>>> '
364 pm.in2_template = '... '
365 pm.out_template = ''
366
367 # Prompt separators like plain python
368 shell.separate_in = ''
369 shell.separate_out = ''
370 shell.separate_out2 = ''
371
372 pm.justify = False
373
374 ptformatter.pprint = False
375 disp_formatter.plain_text_only = True
376
377 shell.magic('xmode Plain')
378 else:
379 # turn off
380 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
381
382 shell.separate_in = dstore.rc_separate_in
383
384 shell.separate_out = dstore.rc_separate_out
385 shell.separate_out2 = dstore.rc_separate_out2
386
387 pm.justify = dstore.rc_prompts_pad_left
388
389 ptformatter.pprint = dstore.rc_pprint
390 disp_formatter.plain_text_only = dstore.rc_plain_text_only
391
392 shell.magic('xmode ' + dstore.xmode)
393
394 # Store new mode and inform
395 dstore.mode = bool(1-int(mode))
396 mode_label = ['OFF','ON'][dstore.mode]
397 print 'Doctest mode is:', mode_label
398
399 @line_magic
400 def gui(self, parameter_s=''):
401 """Enable or disable IPython GUI event loop integration.
402
403 %gui [GUINAME]
404
405 This magic replaces IPython's threaded shells that were activated
406 using the (pylab/wthread/etc.) command line flags. GUI toolkits
407 can now be enabled at runtime and keyboard
408 interrupts should work without any problems. The following toolkits
409 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
410
411 %gui wx # enable wxPython event loop integration
412 %gui qt4|qt # enable PyQt4 event loop integration
413 %gui gtk # enable PyGTK event loop integration
414 %gui gtk3 # enable Gtk3 event loop integration
415 %gui tk # enable Tk event loop integration
416 %gui OSX # enable Cocoa event loop integration
417 # (requires %matplotlib 1.1)
418 %gui # disable all event loop integration
419
420 WARNING: after any of these has been called you can simply create
421 an application object, but DO NOT start the event loop yourself, as
422 we have already handled that.
423 """
424 opts, arg = self.parse_options(parameter_s, '')
425 if arg=='': arg = None
426 try:
427 return self.enable_gui(arg)
428 except Exception as e:
429 # print simple error message, rather than traceback if we can't
430 # hook up the GUI
431 error(str(e))
432
433 @skip_doctest
434 @line_magic
435 def precision(self, s=''):
436 """Set floating point precision for pretty printing.
437
438 Can set either integer precision or a format string.
439
440 If numpy has been imported and precision is an int,
441 numpy display precision will also be set, via ``numpy.set_printoptions``.
442
443 If no argument is given, defaults will be restored.
444
445 Examples
446 --------
447 ::
448
449 In [1]: from math import pi
450
451 In [2]: %precision 3
452 Out[2]: u'%.3f'
453
454 In [3]: pi
455 Out[3]: 3.142
456
457 In [4]: %precision %i
458 Out[4]: u'%i'
459
460 In [5]: pi
461 Out[5]: 3
462
463 In [6]: %precision %e
464 Out[6]: u'%e'
465
466 In [7]: pi**10
467 Out[7]: 9.364805e+04
468
469 In [8]: %precision
470 Out[8]: u'%r'
471
472 In [9]: pi**10
473 Out[9]: 93648.047476082982
474 """
475 ptformatter = self.shell.display_formatter.formatters['text/plain']
476 ptformatter.float_precision = s
477 return ptformatter.float_format
478
479 @magic_arguments.magic_arguments()
480 @magic_arguments.argument(
481 '-e', '--export', action='store_true', default=False,
482 help='Export IPython history as a notebook. The filename argument '
483 'is used to specify the notebook name and format. For example '
484 'a filename of notebook.ipynb will result in a notebook name '
485 'of "notebook" and a format of "xml". Likewise using a ".json" '
486 'or ".py" file extension will write the notebook in the json '
487 'or py formats.'
488 )
489 @magic_arguments.argument(
490 '-f', '--format',
491 help='Convert an existing IPython notebook to a new format. This option '
492 'specifies the new format and can have the values: xml, json, py. '
493 'The target filename is chosen automatically based on the new '
494 'format. The filename argument gives the name of the source file.'
495 )
496 @magic_arguments.argument(
497 'filename', type=unicode,
498 help='Notebook name or filename'
499 )
500 @line_magic
501 def notebook(self, s):
502 """Export and convert IPython notebooks.
503
504 This function can export the current IPython history to a notebook file
505 or can convert an existing notebook file into a different format. For
506 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
507 To export the history to "foo.py" do "%notebook -e foo.py". To convert
508 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
509 formats include (json/ipynb, py).
510 """
511 args = magic_arguments.parse_argstring(self.notebook, s)
512
513 from IPython.nbformat import current
514 args.filename = unquote_filename(args.filename)
515 if args.export:
516 fname, name, format = current.parse_filename(args.filename)
517 cells = []
518 hist = list(self.shell.history_manager.get_range())
519 for session, prompt_number, input in hist[:-1]:
520 cells.append(current.new_code_cell(prompt_number=prompt_number,
521 input=input))
522 worksheet = current.new_worksheet(cells=cells)
523 nb = current.new_notebook(name=name,worksheets=[worksheet])
524 with io.open(fname, 'w', encoding='utf-8') as f:
525 current.write(nb, f, format);
526 elif args.format is not None:
527 old_fname, old_name, old_format = current.parse_filename(args.filename)
528 new_format = args.format
529 if new_format == u'xml':
530 raise ValueError('Notebooks cannot be written as xml.')
531 elif new_format == u'ipynb' or new_format == u'json':
532 new_fname = old_name + u'.ipynb'
533 new_format = u'json'
534 elif new_format == u'py':
535 new_fname = old_name + u'.py'
536 else:
537 raise ValueError('Invalid notebook format: %s' % new_format)
538 with io.open(old_fname, 'r', encoding='utf-8') as f:
539 nb = current.read(f, old_format)
540 with io.open(new_fname, 'w', encoding='utf-8') as f:
541 current.write(nb, f, new_format)
542
543
62
544 # Used for exception handling in magic_edit
63 # Used for exception handling in magic_edit
545 class MacroToEdit(ValueError): pass
64 class MacroToEdit(ValueError): pass
@@ -11,9 +11,10 b''
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 from IPython.core.magic import Magics, register_magics
15 from history import (HistoryMagics)
16
14
15 from IPython.core.magic import Magics, register_magics
16 from basic import BasicMagics
17 from history import HistoryMagics
17
18
18 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
19 # Magic implementation classes
20 # Magic implementation classes
General Comments 0
You need to be logged in to leave comments. Login now