Debian Codegraph @

doc/usage/restructuredtext/basics.rst

raw
1 .. highlight:: rst
2
3 .. _rst-primer:
4
5 =======================
6 reStructuredText Primer
7 =======================
8
9 reStructuredText is the default plaintext markup language used by Sphinx. This
10 section is a brief introduction to reStructuredText (reST) concepts and syntax,
11 intended to provide authors with enough information to author documents
12 productively. Since reStructuredText was designed to be a simple, unobtrusive markup
13 language, this will not take too long.
14
15 .. seealso::
16
17 The authoritative `reStructuredText User Documentation
18 <https://docutils.sourceforge.io/rst.html>`_.
19 The "ref" links in this document link to the description of
20 the individual constructs in the reStructuredText reference.
21
22
23 Paragraphs
24 ----------
25
26 The paragraph (:duref:`ref <paragraphs>`) is the most basic block
27 in a reStructuredText document.
28 Paragraphs are simply chunks of text separated by one or more blank lines.
29 As in Python, indentation is significant in reStructuredText,
30 so all lines of the same paragraph must be left-aligned
31 to the same level of indentation.
32
33
34 .. _rst-inline-markup:
35
36 Inline markup
37 -------------
38
39 The standard reStructuredText inline markup is quite simple: use
40
41 * one asterisk: ``*text*`` for emphasis (italics),
42 * two asterisks: ``**text**`` for strong emphasis (boldface), and
43 * backquotes: ````text```` for code samples.
44
45 If asterisks or backquotes appear in running text and could be confused with
46 inline markup delimiters, they have to be escaped with a backslash.
47
48 Be aware of some restrictions of this markup:
49
50 * it may not be nested,
51 * content may not start or end with whitespace: ``* text*`` is wrong,
52 * it must be separated from surrounding text by non-word characters. Use a
53 backslash escaped space to work around that: ``thisis\ *one*\ word``.
54
55 These restrictions may be lifted in future versions of the docutils.
56
57 It is also possible to replace or expand upon some of this inline markup with
58 roles. Refer to :ref:`rst-roles` for more information.
59
60
61 Lists and Quote-like blocks
62 ---------------------------
63
64 List markup (:duref:`ref <bullet-lists>`) is natural: just place an asterisk at
65 the start of a paragraph and indent properly. The same goes for numbered
66 lists; they can also be autonumbered using a ``#`` sign::
67
68 * This is a bulleted list.
69 * It has two items, the second
70 item uses two lines.
71
72 1. This is a numbered list.
73 2. It has two items too.
74
75 #. This is a numbered list.
76 #. It has two items too.
77
78 Nested lists are possible, but be aware that they must be separated from the
79 parent list items by blank lines::
80
81 * this is
82 * a list
83
84 * with a nested list
85 * and some subitems
86
87 * and here the parent list continues
88
89 Definition lists (:duref:`ref <definition-lists>`) are created as follows::
90
91 term (up to a line of text)
92 Definition of the term, which must be indented
93
94 and can even consist of multiple paragraphs
95
96 next term
97 Description.
98
99 Note that the term cannot have more than one line of text.
100
101 Quoted paragraphs (:duref:`ref <block-quotes>`) are created by just indenting
102 them more than the surrounding paragraphs.
103
104 Line blocks (:duref:`ref <line-blocks>`) are a way of preserving line breaks::
105
106 | These lines are
107 | broken exactly like in
108 | the source file.
109
110 There are also several more special blocks available:
111
112 * field lists (:duref:`ref <field-lists>`, with caveats noted in
113 :ref:`rst-field-lists`)
114 * option lists (:duref:`ref <option-lists>`)
115 * quoted literal blocks (:duref:`ref <quoted-literal-blocks>`)
116 * doctest blocks (:duref:`ref <doctest-blocks>`)
117
118
119 .. _rst-literal-blocks:
120
121 Literal blocks
122 --------------
123
124 Literal code blocks (:duref:`ref <literal-blocks>`) are introduced by ending a
125 paragraph with the special marker ``::``. The literal block must be indented
126 (and, like all paragraphs, separated from the surrounding ones by blank
127 lines)::
128
129 This is a normal text paragraph. The next paragraph is a code sample::
130
131 It is not processed in any way, except
132 that the indentation is removed.
133
134 It can span multiple lines.
135
136 This is a normal text paragraph again.
137
138 The handling of the ``::`` marker is smart:
139
140 * If it occurs as a paragraph of its own, that paragraph is completely left out
141 of the document.
142 * If it is preceded by whitespace, the marker is removed.
143 * If it is preceded by non-whitespace, the marker is replaced by a single
144 colon.
145
146 That way, the second sentence in the above example's first paragraph would be
147 rendered as "The next paragraph is a code sample:".
148
149 Code highlighting can be enabled for these literal blocks on a document-wide
150 basis using the :rst:dir:`highlight` directive and on a project-wide basis
151 using the :confval:`highlight_language` configuration option. The
152 :rst:dir:`code-block` directive can be used to set highlighting on a
153 block-by-block basis. These directives are discussed later.
154
155
156 .. _rst-doctest-blocks:
157
158 Doctest blocks
159 --------------
160
161 Doctest blocks (:duref:`ref <doctest-blocks>`) are interactive Python sessions
162 cut-and-pasted into docstrings. They do not require the
163 :ref:`literal blocks <rst-literal-blocks>` syntax. The doctest block must end
164 with a blank line and should *not* end with an unused prompt::
165
166 >>> 1 + 1
167 2
168
169 .. _rst-tables:
170
171 Tables
172 ------
173
174 For *grid tables* (:duref:`ref <grid-tables>`), you have to "paint" the cell
175 grid yourself. They look like this::
176
177 +------------------------+------------+----------+----------+
178 | Header row, column 1 | Header 2 | Header 3 | Header 4 |
179 | (header rows optional) | | | |
180 +========================+============+==========+==========+
181 | body row 1, column 1 | column 2 | column 3 | column 4 |
182 +------------------------+------------+----------+----------+
183 | body row 2 | ... | ... | |
184 +------------------------+------------+----------+----------+
185
186 *Simple tables* (:duref:`ref <simple-tables>`) are easier to write, but
187 limited: they must contain more than one row, and the first column cells cannot
188 contain multiple lines. They look like this::
189
190 ===== ===== =======
191 A B A and B
192 ===== ===== =======
193 False False False
194 True False False
195 False True False
196 True True True
197 ===== ===== =======
198
199 Two more syntaxes are supported: *CSV tables* and *List tables*. They use an
200 *explicit markup block*. Refer to :ref:`table-directives` for more information.
201
202
203 Hyperlinks
204 ----------
205
206 .. _rst-external-links:
207
208 External links
209 ~~~~~~~~~~~~~~
210
211 URLs and email addresses in text are automatically linked and do not need
212 explicit markup at all.
213 For example, https://domain.invalid/ is written with no special markup
214 in the source of this document, and is recognised as an external hyperlink.
215
216 To create text with a link, the best approach is generally to put the URL
217 below the paragraph as follows (:duref:`ref <hyperlink-targets>`)::
218
219 This is a paragraph that contains `a link`_.
220
221 .. _a link: https://domain.invalid/
222
223 This keeps the paragraph more readable in source code.
224
225 Alternatively, you can embed the URL within the prose for an 'inline link'.
226 This can lead to longer lines, but has the benefit of keeping the link text
227 and the URL pointed to in the same place.
228 This uses the following syntax: ```Link text <https://domain.invalid/>`__``
229 (:duref:`ref <embedded-uris-and-aliases>`).
230
231 .. important::
232
233 There must be a space between the link text
234 and the opening angle bracket ('``<``') for the URL.
235
236 .. tip::
237
238 Use two trailing underscores when embedding the URL.
239 Technically, a single underscore works as well,
240 but that would create a named reference instead of an anonymous one.
241 Named references typically do not have a benefit when the URL is embedded.
242 Moreover, they have the disadvantage that you must make sure that you
243 do not use the same "Link text" for another link in your document.
244
245 You can also separate the link and the target definition (:duref:`ref
246 <hyperlink-targets>`), like this::
247
248 This is a paragraph that contains `a link`_.
249
250 .. _a link: https://domain.invalid/
251
252 Internal links
253 ~~~~~~~~~~~~~~
254
255 Internal linking is done via a special reStructuredText role provided by Sphinx,
256 see the section on specific markup, :ref:`ref-role`.
257
258
259 .. _rst-sections:
260
261 Sections
262 --------
263
264 Section headers (:duref:`ref <sections>`) are created by underlining (and
265 optionally overlining) the section title with a punctuation character, at least
266 as long as the text::
267
268 =================
269 This is a heading
270 =================
271
272 Normally, there are no heading levels assigned to certain characters as the
273 structure is determined from the succession of headings. However, this
274 convention is used in `Python Developer's Guide for documenting
275 <https://devguide.python.org/documentation/markup/#sections>`_ which you may
276 follow:
277
278 * ``#`` with overline, for parts
279 * ``*`` with overline, for chapters
280 * ``=`` for sections
281 * ``-`` for subsections
282 * ``^`` for subsubsections
283 * ``"`` for paragraphs
284
285 Of course, you are free to use your own marker characters (see the reStructuredText
286 documentation), and use a deeper nesting level, but keep in mind that most
287 target formats (HTML, LaTeX) have a limited supported nesting depth.
288
289
290 .. _rst-field-lists:
291
292 Field Lists
293 -----------
294
295 Field lists (:duref:`ref <field-lists>`) are sequences of fields marked up like
296 this::
297
298 :fieldname: Field content
299
300 They are commonly used in Python documentation::
301
302 def my_function(my_arg, my_other_arg):
303 """A function just for me.
304
305 :param my_arg: The first of my arguments.
306 :param my_other_arg: The second of my arguments.
307
308 :returns: A message (just for me, of course).
309 """
310
311 Sphinx extends standard docutils behavior and intercepts field lists specified
312 at the beginning of documents. Refer to :doc:`field-lists` for more
313 information.
314
315
316 .. _rst-roles:
317
318 Roles
319 -----
320
321 A role or "custom interpreted text role" (:dupage:`ref <roles>`) is an inline
322 piece of explicit markup. It signifies that the enclosed text should be
323 interpreted in a specific way. Sphinx uses this to provide semantic markup and
324 cross-referencing of identifiers, as described in the appropriate section. The
325 general syntax is ``:rolename:`content```.
326
327 Docutils supports the following roles:
328
329 * :durole:`emphasis` -- equivalent of ``*emphasis*``
330 * :durole:`strong` -- equivalent of ``**strong**``
331 * :durole:`literal` -- equivalent of ````literal````
332 * :durole:`subscript` -- subscript text
333 * :durole:`superscript` -- superscript text
334 * :durole:`title-reference` -- for titles of books, periodicals, and other
335 materials
336
337 Refer to :doc:`roles` for roles added by Sphinx.
338
339
340 Explicit Markup
341 ---------------
342
343 "Explicit markup" (:duref:`ref <explicit-markup-blocks>`) is used in
344 reStructuredText for most constructs that need special handling, such as footnotes,
345 specially-highlighted paragraphs, comments, and generic directives.
346
347 An explicit markup block begins with a line starting with ``..`` followed by
348 whitespace and is terminated by the next paragraph at the same level of
349 indentation. (There needs to be a blank line between explicit markup and
350 normal paragraphs. This may all sound a bit complicated, but it is intuitive
351 enough when you write it.)
352
353
354 .. _rst-directives:
355
356 Directives
357 ----------
358
359 A directive (:duref:`ref <directives>`) is a generic block of explicit markup.
360 Along with roles, it is one of the extension mechanisms of reStructuredText,
361 and Sphinx makes heavy use of it.
362
363 Docutils supports the following directives:
364
365 * Admonitions: :dudir:`attention`, :dudir:`caution`, :dudir:`danger`,
366 :dudir:`error`, :dudir:`hint`, :dudir:`important`, :dudir:`note`,
367 :dudir:`tip`, :dudir:`warning` and the generic
368 :dudir:`admonition <admonitions>`. (Most themes style only "note" and
369 "warning" specially.)
370
371 * Images:
372
373 - :dudir:`image` (see also Images_ below)
374 - :dudir:`figure` (an image with caption and optional legend)
375
376 * Additional body elements:
377
378 - :dudir:`contents <table-of-contents>` (a local, i.e. for the current file
379 only, table of contents)
380 - :dudir:`container` (a container with a custom class, useful to generate an
381 outer ``<div>`` in HTML)
382 - :dudir:`rubric` (a heading without relation to the document sectioning)
383 - :dudir:`topic`, :dudir:`sidebar` (special highlighted body elements)
384 - :dudir:`parsed-literal` (literal block that supports inline markup)
385 - :dudir:`epigraph` (a block quote with optional attribution line)
386 - :dudir:`highlights`, :dudir:`pull-quote` (block quotes with their own
387 class attribute)
388 - :dudir:`compound <compound-paragraph>` (a compound paragraph)
389
390 * Special tables:
391
392 - :dudir:`table` (a table with title)
393 - :dudir:`csv-table` (a table generated from comma-separated values)
394 - :dudir:`list-table` (a table generated from a list of lists)
395
396 * Special directives:
397
398 - :dudir:`raw <raw-data-pass-through>` (include raw target-format markup)
399 - :dudir:`include` (include reStructuredText from another file) -- in Sphinx,
400 when given an absolute include file path, this directive takes it as
401 relative to the source directory
402
403 .. _rstclass:
404
405 - :dudir:`class <setting-class-attributes>`
406 (assign a class attribute to the next element)
407
408 .. note::
409
410 When the default domain contains a ``class`` directive, this directive
411 will be shadowed. Therefore, Sphinx re-exports it as ``rst-class``.
412
413 .. tip::
414
415 If you want to add a class to a directive,
416 you may consider the ``:class:`` :dudir:`option <common-options>` instead,
417 which is supported by most directives and allows for a more compact notation.
418
419 * HTML specifics:
420
421 - :dudir:`meta`
422 (generation of HTML ``<meta>`` tags, see also :ref:`html-meta` below)
423 - :dudir:`title <metadata-document-title>` (override document title)
424
425 * Influencing markup:
426
427 - :dudir:`default-role` (set a new default role)
428 - :dudir:`role` (create a new role)
429
430 Since these are only per-file, better use Sphinx's facilities for setting the
431 :confval:`default_role`.
432
433 .. warning::
434
435 Do *not* use the directives :dudir:`sectnum`, :dudir:`header` and
436 :dudir:`footer`.
437
438 Directives added by Sphinx are described in :doc:`directives`.
439
440 Basically, a directive consists of a name, arguments, options and content.
441 (Keep this terminology in mind, it is used in the next chapter describing
442 custom directives.) Looking at this example, ::
443
444 .. function:: foo(x)
445 foo(y, z)
446 :module: some.module.name
447
448 Return a line of text input from the user.
449
450 ``function`` is the directive name. It is given two arguments here, the
451 remainder of the first line and the second line, as well as one option
452 ``module`` (as you can see, options are given in the lines immediately
453 following the arguments and indicated by the colons). Options must be indented
454 to the same level as the directive content.
455
456 The directive content follows after a blank line and is indented relative to
457 the directive start or if options are present, by the same amount as the
458 options.
459
460 Be careful as the indent is not a fixed number of whitespace, e.g. three, but
461 any number whitespace. This can be surprising when a fixed indent is used
462 throughout the document and can make a difference for directives which are
463 sensitive to whitespace. Compare::
464
465 .. code-block::
466 :caption: A cool example
467
468 The output of this line starts with four spaces.
469
470 .. code-block::
471
472 The output of this line has no spaces at the beginning.
473
474 In the first code block, the indent for the content was fixated by the option
475 line to three spaces, consequently the content starts with four spaces.
476 In the latter the indent was fixed by the content itself to seven spaces, thus
477 it does not start with a space.
478
479
480 Images
481 ------
482
483 reStructuredText supports an image directive (:dudir:`ref <image>`), used like so::
484
485 .. image:: gnu.png
486 (options)
487
488 When used within Sphinx, the file name given (here ``gnu.png``) must either be
489 relative to the source file, or absolute which means that they are relative to
490 the top source directory. For example, the file ``sketch/spam.rst`` could
491 refer to the image ``images/spam.png`` as ``../images/spam.png`` or
492 ``/images/spam.png``.
493
494 Sphinx will automatically copy image files over to a subdirectory of the output
495 directory on building (e.g. the ``_static`` directory for HTML output.)
496
497 Interpretation of image size options (``width`` and ``height``) is as follows:
498 if the size has no unit or the unit is pixels, the given size will only be
499 respected for output channels that support pixels. Other units (like ``pt`` for
500 points) will be used for HTML and LaTeX output (the latter replaces ``pt`` by
501 ``bp`` as this is the TeX unit such that ``72bp=1in``).
502
503 Sphinx extends the standard docutils behavior by allowing an asterisk for the
504 extension::
505
506 .. image:: gnu.*
507
508 Sphinx then searches for all images matching the provided pattern and
509 determines their type. Each builder then chooses the best image out of these
510 candidates. For instance, if the file name ``gnu.*`` was given and two files
511 :file:`gnu.pdf` and :file:`gnu.png` existed in the source tree, the LaTeX
512 builder would choose the former, while the HTML builder would prefer the
513 latter. Supported image types and choosing priority are defined at
514 :doc:`/usage/builders/index`.
515
516 Note that image file names should not contain spaces.
517
518 .. versionchanged:: 0.4
519 Added the support for file names ending in an asterisk.
520
521 .. versionchanged:: 0.6
522 Image paths can now be absolute.
523
524 .. versionchanged:: 1.5
525 latex target supports pixels (default is ``96px=1in``).
526
527
528 Footnotes
529 ---------
530
531 For footnotes (:duref:`ref <footnotes>`), use ``[#name]_`` to mark the footnote
532 location, and add the footnote body at the bottom of the document after a
533 "Footnotes" rubric heading, like so::
534
535 Lorem ipsum [#f1]_ dolor sit amet ... [#f2]_
536
537 .. rubric:: Footnotes
538
539 .. [#f1] Text of the first footnote.
540 .. [#f2] Text of the second footnote.
541
542 You can also explicitly number the footnotes (``[1]_``) or use auto-numbered
543 footnotes without names (``[#]_``).
544
545
546 Citations
547 ---------
548
549 Standard reStructuredText citations (:duref:`ref <citations>`) are supported,
550 with the additional feature that they are "global",
551 i.e. all citations can be referenced from all files. Use them like so::
552
553 Lorem ipsum [Ref]_ dolor sit amet.
554
555 .. [Ref] Book or article reference, URL or whatever.
556
557 Citation usage is similar to footnote usage, but with a label that is not
558 numeric or begins with ``#``.
559
560
561 Substitutions
562 -------------
563
564 reStructuredText supports "substitutions" (:duref:`ref <substitution-definitions>`),
565 which are pieces of text and/or markup referred to in the text by ``|name|``.
566 They are defined like footnotes with explicit markup blocks, like this::
567
568 .. |name| replace:: replacement *text*
569
570 or this::
571
572 .. |caution| image:: warning.png
573 :alt: Warning!
574
575 See the :duref:`reStructuredText reference for substitutions
576 <substitution-definitions>` for details.
577
578 .. index:: ! pair: global; substitutions
579
580 If you want to use some substitutions for all documents, put them into
581 :confval:`rst_prolog` or :confval:`rst_epilog` or put them into a separate file
582 and include it into all documents you want to use them in, using the
583 :dudir:`include` directive. (Be sure to give the include file a file name
584 extension differing from that of other source files, to avoid Sphinx finding it
585 as a standalone document.)
586
587 Sphinx defines some default substitutions, see :ref:`default-substitutions`.
588
589
590 Comments
591 --------
592
593 Every explicit markup block which isn't a valid markup construct (like the
594 footnotes above) is regarded as a comment (:duref:`ref <comments>`). For
595 example::
596
597 .. This is a comment.
598
599 You can indent text after a comment start to form multiline comments::
600
601 ..
602 This whole indented block
603 is a comment.
604
605 Still in the comment.
606
607
608 .. _html-meta:
609
610 HTML Metadata
611 -------------
612
613 The :dudir:`meta` directive allows specifying the HTML
614 `metadata element`_ of a Sphinx documentation page. For example, the
615 directive::
616
617 .. meta::
618 :description: The Sphinx documentation builder
619 :keywords: Sphinx, documentation, builder
620
621 will generate the following HTML output:
622
623 .. code-block:: html
624
625 <meta name="description" content="The Sphinx documentation builder">
626 <meta name="keywords" content="Sphinx, documentation, builder">
627
628 Also, Sphinx will add the keywords as specified in the meta directive to the
629 search index. Thereby, the ``lang`` attribute of the meta element is
630 considered. For example, the directive::
631
632 .. meta::
633 :keywords: backup
634 :keywords lang=en: pleasefindthiskey pleasefindthiskeytoo
635 :keywords lang=de: bittediesenkeyfinden
636
637 adds the following words to the search indices of builds with different language
638 configurations:
639
640 * ``pleasefindthiskey``, ``pleasefindthiskeytoo`` to *English* builds;
641 * ``bittediesenkeyfinden`` to *German* builds;
642 * ``backup`` to builds in all languages.
643
644 .. _metadata element: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta
645
646
647 Source encoding
648 ---------------
649
650 Sphinx supports source files that are encoded in UTF-8.
651 This means that the full range of Unicode__ characters may be used
652 directly in reStructuredText.
653
654 __ https://www.unicode.org/
655
656
657 Gotchas
658 -------
659
660 There are some problems one commonly runs into
661 while authoring reStructuredText documents:
662
663 * **Separation of inline markup:** As said above, inline markup spans must be
664 separated from the surrounding text by non-word characters, you have to use a
665 backslash-escaped space to get around that. See :duref:`the reference
666 <substitution-definitions>` for the details.
667
668 * **No nested inline markup:** Something like ``*see :func:`foo`*`` is not
669 possible.