##// END OF EJS Templates
Merge pull request #6679 from takluyver/doc-magics...
Matthias Bussonnier -
r18361:03084f4d merge
parent child Browse files
Show More
@@ -0,0 +1,64 b''
1 from IPython.core.alias import Alias
2 from IPython.core.interactiveshell import InteractiveShell
3 from IPython.core.magic import MagicAlias
4 from IPython.utils.text import dedent, indent
5
6 shell = InteractiveShell.instance()
7 magics = shell.magics_manager.magics
8
9 def _strip_underline(line):
10 chars = set(line.strip())
11 if len(chars) == 1 and ('-' in chars or '=' in chars):
12 return ""
13 else:
14 return line
15
16 def format_docstring(func):
17 docstring = (func.__doc__ or "Undocumented").rstrip()
18 docstring = indent(dedent(docstring))
19 # Sphinx complains if indented bits have rst headings in, so strip out
20 # any underlines in the docstring.
21 lines = [_strip_underline(l) for l in docstring.splitlines()]
22 return "\n".join(lines)
23
24 output = [
25 "Line magics",
26 "===========",
27 "",
28 ]
29
30 # Case insensitive sort by name
31 def sortkey(s): return s[0].lower()
32
33 for name, func in sorted(magics['line'].items(), key=sortkey):
34 if isinstance(func, Alias) or isinstance(func, MagicAlias):
35 # Aliases are magics, but shouldn't be documented here
36 # Also skip aliases to other magics
37 continue
38 output.extend([".. magic:: {}".format(name),
39 "",
40 format_docstring(func),
41 ""])
42
43 output.extend([
44 "Cell magics",
45 "===========",
46 "",
47 ])
48
49 for name, func in sorted(magics['cell'].items(), key=sortkey):
50 if name == "!":
51 # Special case - don't encourage people to use %%!
52 continue
53 if func == magics['line'].get(name, 'QQQP'):
54 # Don't redocument line magics that double as cell magics
55 continue
56 if isinstance(func, MagicAlias):
57 continue
58 output.extend([".. cellmagic:: {}".format(name),
59 "",
60 format_docstring(func),
61 ""])
62
63 with open("source/interactive/magics-generated.txt", "w") as f:
64 f.write("\n".join(output)) No newline at end of file
@@ -0,0 +1,5 b''
1 =======================
2 Built-in magic commands
3 =======================
4
5 .. include:: magics-generated.txt
@@ -0,0 +1,42 b''
1 import re
2 from sphinx import addnodes
3 from sphinx.domains.std import StandardDomain
4 from sphinx.roles import XRefRole
5
6 name_re = re.compile(r"[\w_]+")
7
8 def parse_magic(env, sig, signode):
9 m = name_re.match(sig)
10 if not m:
11 raise Exception("Invalid magic command: %s" % sig)
12 name = "%" + sig
13 signode += addnodes.desc_name(name, name)
14 return m.group(0)
15
16 class LineMagicRole(XRefRole):
17 """Cross reference role displayed with a % prefix"""
18 prefix = "%"
19
20 def process_link(self, env, refnode, has_explicit_title, title, target):
21 if not has_explicit_title:
22 title = self.prefix + title.lstrip("%")
23 target = target.lstrip("%")
24 return title, target
25
26 def parse_cell_magic(env, sig, signode):
27 m = name_re.match(sig)
28 if not m:
29 raise ValueError("Invalid cell magic: %s" % sig)
30 name = "%%" + sig
31 signode += addnodes.desc_name(name, name)
32 return m.group(0)
33
34 class CellMagicRole(LineMagicRole):
35 """Cross reference role displayed with a %% prefix"""
36 prefix = "%%"
37
38 def setup(app):
39 app.add_object_type('magic', 'magic', 'pair: %s; magic command', parse_magic)
40 StandardDomain.roles['magic'] = LineMagicRole()
41 app.add_object_type('cellmagic', 'cellmagic', 'pair: %s; cell magic', parse_cell_magic)
42 StandardDomain.roles['cellmagic'] = CellMagicRole()
@@ -5,6 +5,7 b' _build'
5 5 docs/man/*.gz
6 6 docs/source/api/generated
7 7 docs/source/config/options
8 docs/source/interactive/magics-generated.txt
8 9 docs/gh-pages
9 10 IPython/html/notebook/static/mathjax
10 11 IPython/html/static/style/*.map
@@ -42,6 +42,7 b' clean: clean_api'
42 42 -rm -rf build/* dist/*
43 43 -cd $(SRCDIR)/config/options; cat generated | xargs -r rm -f
44 44 -rm -rf $(SRCDIR)/config/options/generated
45 -rm -f $(SRCDIR)/interactive/magics-generated.txt
45 46
46 47 pdf: latex
47 48 cd build/latex && make all-pdf
@@ -58,8 +59,8 b' dist: html'
58 59 cp -al build/html .
59 60 @echo "Build finished. Final docs are in html/"
60 61
61 html: api autoconfig
62 html_noapi: clean_api autoconfig
62 html: api autoconfig automagic
63 html_noapi: clean_api autoconfig automagic
63 64
64 65 html html_noapi:
65 66 mkdir -p build/html build/doctrees
@@ -67,6 +68,12 b' html html_noapi:'
67 68 @echo
68 69 @echo "Build finished. The HTML pages are in build/html."
69 70
71 automagic: source/interactive/magics-generated.txt
72
73 source/interactive/magics-generated.txt: autogen_magics.py
74 python autogen_magics.py
75 @echo "Created docs for line & cell magics"
76
70 77 autoconfig: source/config/options/generated
71 78
72 79 source/config/options/generated:
@@ -25,6 +25,8 b" if __name__ == '__main__':"
25 25 r'\.nbformat\.v\d+',
26 26 # Public API for this is in kernel.zmq.eventloops
27 27 r'\.kernel\.zmq\.gui',
28 # Magics are documented separately
29 r'\.core\.magics',
28 30 ]
29 31
30 32 # The inputhook* modules often cause problems on import, such as trying to
@@ -52,6 +52,7 b' extensions = ['
52 52 'IPython.sphinxext.ipython_directive',
53 53 'numpydoc', # to preprocess docstrings
54 54 'github', # for easy GitHub links
55 'magics',
55 56 ]
56 57
57 58 if ON_RTD:
@@ -8,6 +8,7 b' Using IPython for interactive work'
8 8 tutorial
9 9 tips
10 10 reference
11 magics
11 12 shell
12 13 qtconsole
13 14
@@ -88,13 +88,13 b' current execution block. Cell magics can in fact make arbitrary modifications'
88 88 to the input they receive, which need not even be valid Python code at all.
89 89 They receive the whole block as a single string.
90 90
91 As a line magic example, the ``%cd`` magic works just like the OS command of
91 As a line magic example, the :magic:`cd` magic works just like the OS command of
92 92 the same name::
93 93
94 94 In [8]: %cd
95 95 /home/fperez
96 96
97 The following uses the builtin ``timeit`` in cell mode::
97 The following uses the builtin :magic:`timeit` in cell mode::
98 98
99 99 In [10]: %%timeit x = range(10000)
100 100 ...: min(x)
@@ -104,7 +104,7 b' The following uses the builtin ``timeit`` in cell mode::'
104 104
105 105 In this case, ``x = range(10000)`` is called as the line argument, and the
106 106 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
107 ``timeit`` magic receives both.
107 :magic:`timeit` magic receives both.
108 108
109 109 If you have 'automagic' enabled (as it by default), you don't need to type in
110 110 the single ``%`` explicitly for line magics; IPython will scan its internal
@@ -156,6 +156,9 b' docstrings of all currently available magic commands.'
156 156
157 157 .. seealso::
158 158
159 :doc:`magics`
160 A list of the line and cell magics available in IPython by default
161
159 162 :ref:`defining_magics`
160 163 How to define and register additional magic functions
161 164
@@ -185,21 +188,19 b' Typing ``??word`` or ``word??`` gives access to the full information, including'
185 188 the source code where possible. Long strings are not snipped.
186 189
187 190 The following magic functions are particularly useful for gathering
188 information about your working environment. You can get more details by
189 typing ``%magic`` or querying them individually (``%function_name?``);
190 this is just a summary:
191 information about your working environment:
191 192
192 * **%pdoc <object>**: Print (or run through a pager if too long) the
193 * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the
193 194 docstring for an object. If the given object is a class, it will
194 195 print both the class and the constructor docstrings.
195 * **%pdef <object>**: Print the call signature for any callable
196 * :magic:`pdef` **<object>**: Print the call signature for any callable
196 197 object. If the object is a class, print the constructor information.
197 * **%psource <object>**: Print (or run through a pager if too long)
198 * :magic:`psource` **<object>**: Print (or run through a pager if too long)
198 199 the source code for an object.
199 * **%pfile <object>**: Show the entire source file where an object was
200 * :magic:`pfile` **<object>**: Show the entire source file where an object was
200 201 defined via a pager, opening it at the line where the object
201 202 definition begins.
202 * **%who/%whos**: These functions give information about identifiers
203 * :magic:`who`/:magic:`whos`: These functions give information about identifiers
203 204 you have defined interactively (not things you loaded or defined
204 205 in your configuration files). %who just prints a list of
205 206 identifiers and %whos prints a table with some basic details about
@@ -310,7 +311,7 b' Session logging and restoring'
310 311
311 312 You can log all input from a session either by starting IPython with the
312 313 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
313 or by activating the logging at any moment with the magic function %logstart.
314 or by activating the logging at any moment with the magic function :magic:`logstart`.
314 315
315 316 Log files can later be reloaded by running them as scripts and IPython
316 317 will attempt to 'replay' the log by executing all the lines in it, thus
@@ -322,7 +323,7 b' any code you wrote while experimenting. Log files are regular text files'
322 323 which you can later open in your favorite text editor to extract code or
323 324 to 'clean them up' before using them to replay a session.
324 325
325 The `%logstart` function for activating logging in mid-session is used as
326 The :magic:`logstart` function for activating logging in mid-session is used as
326 327 follows::
327 328
328 329 %logstart [log_name [log_mode]]
@@ -341,7 +342,7 b' one of (note that the modes are given unquoted):'
341 342 * [append:] well, that says it.
342 343 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
343 344
344 The %logoff and %logon functions allow you to temporarily stop and
345 The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and
345 346 resume logging to a file which had previously been started with
346 347 %logstart. They will fail (with an explanation) if you try to use them
347 348 before logging has been started.
@@ -362,7 +363,7 b' You can assign the result of a system command to a Python variable with the'
362 363 syntax ``myfiles = !ls``. This gets machine readable output from stdout
363 364 (e.g. without colours), and splits on newlines. To explicitly get this sort of
364 365 output without assigning to a variable, use two exclamation marks (``!!ls``) or
365 the ``%sx`` magic command.
366 the :magic:`sx` magic command.
366 367
367 368 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
368 369 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
@@ -392,7 +393,7 b' Note that `$$` is used to represent a literal `$`.'
392 393 System command aliases
393 394 ----------------------
394 395
395 The %alias magic function allows you to define magic functions which are in fact
396 The :magic:`alias` magic function allows you to define magic functions which are in fact
396 397 system shell commands. These aliases can have parameters.
397 398
398 399 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
@@ -411,10 +412,10 b' replaced by a positional parameter to the call to %parts::'
411 412 In [3]: parts A
412 413 ERROR: Alias <parts> requires 2 arguments, 1 given.
413 414
414 If called with no parameters, %alias prints the table of currently
415 If called with no parameters, :magic:`alias` prints the table of currently
415 416 defined aliases.
416 417
417 The %rehashx magic allows you to load your entire $PATH as
418 The :magic:`rehashx` magic allows you to load your entire $PATH as
418 419 ipython aliases. See its docstring for further details.
419 420
420 421
@@ -440,7 +441,7 b' detailed tracebacks. Furthermore, both normal and verbose tracebacks can'
440 441 be colored (if your terminal supports it) which makes them much easier
441 442 to parse visually.
442 443
443 See the magic xmode and colors functions for details.
444 See the magic :magic:`xmode` and :magic:`colors` functions for details.
444 445
445 446 These features are basically a terminal version of Ka-Ping Yee's cgitb
446 447 module, now part of the standard Python library.
@@ -454,7 +455,7 b' Input caching system'
454 455 IPython offers numbered prompts (In/Out) with input and output caching
455 456 (also referred to as 'input history'). All input is saved and can be
456 457 retrieved as variables (besides the usual arrow key recall), in
457 addition to the %rep magic command that brings a history entry
458 addition to the :magic:`rep` magic command that brings a history entry
458 459 up for editing on the next command line.
459 460
460 461 The following variables always exist:
@@ -476,17 +477,17 b' characters. You can also manipulate them like regular variables (they'
476 477 are strings), modify or exec them.
477 478
478 479 You can also re-execute multiple lines of input easily by using the
479 magic %rerun or %macro functions. The macro system also allows you to re-execute
480 magic :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to re-execute
480 481 previous lines which include magic function calls (which require special
481 482 processing). Type %macro? for more details on the macro system.
482 483
483 A history function %hist allows you to see any part of your input
484 A history function :magic:`history` allows you to see any part of your input
484 485 history by printing a range of the _i variables.
485 486
486 487 You can also search ('grep') through your history by typing
487 488 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
488 489 etc. You can bring history entries listed by '%hist -g' up for editing
489 with the %recall command, or run them immediately with %rerun.
490 with the %recall command, or run them immediately with :magic:`rerun`.
490 491
491 492 .. _output_caching:
492 493
@@ -522,15 +523,15 b' This system obviously can potentially put heavy memory demands on your'
522 523 system, since it prevents Python's garbage collector from removing any
523 524 previously computed results. You can control how many results are kept
524 525 in memory with the configuration option ``InteractiveShell.cache_size``.
525 If you set it to 0, output caching is disabled. You can also use the ``%reset``
526 and ``%xdel`` magics to clear large items from memory.
526 If you set it to 0, output caching is disabled. You can also use the :magic:`reset`
527 and :magic:`xdel` magics to clear large items from memory.
527 528
528 529 Directory history
529 530 -----------------
530 531
531 532 Your history of visited directories is kept in the global list _dh, and
532 the magic %cd command can be used to go to any entry in that list. The
533 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
533 the magic :magic:`cd` command can be used to go to any entry in that list. The
534 :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to
534 535 conveniently view the directory history.
535 536
536 537
@@ -707,7 +708,7 b' allows you to step through code, set breakpoints, watch variables,'
707 708 etc. IPython makes it very easy to start any script under the control
708 709 of pdb, regardless of whether you have wrapped it into a 'main()'
709 710 function or not. For this, simply type ``%run -d myscript`` at an
710 IPython prompt. See the %run command's documentation for more details, including
711 IPython prompt. See the :magic:`run` command's documentation for more details, including
711 712 how to control where pdb will stop execution first.
712 713
713 714 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
@@ -724,9 +725,9 b" while your program is at this point 'dead', all the data is still"
724 725 available and you can walk up and down the stack frame and understand
725 726 the origin of the problem.
726 727
727 You can use the ``%debug`` magic after an exception has occurred to start
728 You can use the :magic:`debug` magic after an exception has occurred to start
728 729 post-mortem debugging. IPython can also call debugger every time your code
729 triggers an uncaught exception. This feature can be toggled with the %pdb magic
730 triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic
730 731 command, or you can start IPython with the ``--pdb`` option.
731 732
732 733 For a post-mortem debugger in your programs outside IPython,
@@ -805,7 +806,7 b' advantages of this are:'
805 806 all of these things.
806 807
807 808 For users, enabling GUI event loop integration is simple. You simple use the
808 ``%gui`` magic as follows::
809 :magic:`gui` magic as follows::
809 810
810 811 %gui [GUINAME]
811 812
@@ -904,7 +905,7 b' scientific computing, all with a syntax compatible with that of the popular'
904 905 Matlab program.
905 906
906 907 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
907 IPython is already running, you can run the ``%matplotlib`` magic. If no
908 IPython is already running, you can run the :magic:`matplotlib` magic. If no
908 909 arguments are given, IPython will automatically detect your choice of
909 910 matplotlib backend. You can also request a specific backend with
910 911 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
@@ -60,7 +60,7 b' prefixed with a double ``%%``, and they are functions that get as an argument'
60 60 not only the rest of the line, but also the lines below it in a separate
61 61 argument.
62 62
63 The following examples show how to call the builtin ``timeit`` magic, both in
63 The following examples show how to call the builtin :magic:`timeit` magic, both in
64 64 line and cell mode::
65 65
66 66 In [1]: %timeit range(1000)
@@ -73,19 +73,19 b' line and cell mode::'
73 73
74 74 The builtin magics include:
75 75
76 - Functions that work with code: ``%run``, ``%edit``, ``%save``, ``%macro``,
77 ``%recall``, etc.
78 - Functions which affect the shell: ``%colors``, ``%xmode``, ``%autoindent``,
79 ``%automagic``, etc.
80 - Other functions such as ``%reset``, ``%timeit``, ``%%file``, ``%load``, or
81 ``%paste``.
76 - Functions that work with code: :magic`run`, :magic:`edit`, :magic:`save`, :magic:`macro`,
77 :magic:`recall`, etc.
78 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`, :magic:`autoindent`,
79 :magic:`automagic`, etc.
80 - Other functions such as :magic:`reset`, :magic:`timeit`, :cellmagic:`writefile`, :magic:`load`, or
81 :magic:`paste`.
82 82
83 83 You can always call them using the ``%`` prefix, and if you're calling a line
84 84 magic on a line by itself, you can omit even that::
85 85
86 86 run thescript.py
87 87
88 You can toggle this behavior by running the ``%automagic`` magic. Cell magics
88 You can toggle this behavior by running the :magic:`automagic` magic. Cell magics
89 89 must always have the ``%%`` prefix.
90 90
91 91 A more detailed explanation of the magic system can be obtained by calling
@@ -95,12 +95,14 b' read its docstring. To see all the available magic functions, call'
95 95
96 96 .. seealso::
97 97
98 :doc:`magics`
99
98 100 `Cell magics`_ example notebook
99 101
100 102 Running and Editing
101 103 -------------------
102 104
103 The ``%run`` magic command allows you to run any python script and load all of
105 The :magic:`run` magic command allows you to run any python script and load all of
104 106 its data directly into the interactive namespace. Since the file is re-read
105 107 from disk each time, changes you make to it are reflected immediately (unlike
106 108 imported modules, which have to be specifically reloaded). IPython also
@@ -110,15 +112,15 b' includes :ref:`dreload <dreload>`, a recursive reload function.'
110 112 for running them under the control of either Python's pdb debugger (-d) or
111 113 profiler (-p).
112 114
113 The ``%edit`` command gives a reasonable approximation of multiline editing,
115 The :magic:`edit` command gives a reasonable approximation of multiline editing,
114 116 by invoking your favorite editor on the spot. IPython will execute the
115 117 code you type in there as if it were typed interactively.
116 118
117 119 Debugging
118 120 ---------
119 121
120 After an exception occurs, you can call ``%debug`` to jump into the Python
121 debugger (pdb) and examine the problem. Alternatively, if you call ``%pdb``,
122 After an exception occurs, you can call :magic:`debug` to jump into the Python
123 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
122 124 IPython will automatically start the debugger on any uncaught exception. You can
123 125 print variables, see code, execute statements and even walk up and down the
124 126 call stack to track down the true source of the problem. This can be an efficient
@@ -171,7 +173,7 b" It's convenient to have aliases to the system commands you use most often."
171 173 This allows you to work seamlessly from inside IPython with the same commands
172 174 you are used to in your system shell. IPython comes with some pre-defined
173 175 aliases and a complete system for changing directories, both via a stack (see
174 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
176 :magic:`pushd`, :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a history of
175 177 visited directories and allows you to go to any previously visited one.
176 178
177 179
General Comments 0
You need to be logged in to leave comments. Login now