Skip to content

Instantly share code, notes, and snippets.

@ionelmc
Last active July 28, 2024 23:38
Show Gist options
  • Save ionelmc/e876b73e2001acd2140f to your computer and use it in GitHub Desktop.
Save ionelmc/e876b73e2001acd2140f to your computer and use it in GitHub Desktop.

The reStructuredText Cheat Sheet: Syntax Reminders

Info:See <http://docutils.sf.net/rst.html> for introductory docs.
Author: David Goodger <[email protected]>
Date: 2013-02-20
Revision: 7612
Description:This is a "docinfo block", or bibliographic field list

Note

If you are reading this as HTML, please read cheatsheet.txt instead to see the input syntax examples!

Section Structure

Section titles are underlined or overlined & underlined.

Body Elements

Grid table:

Paragraphs are flush-left, separated by blank lines.

Block quotes are indented.

Literal block, preceded by "::":

Indented

or:

> Quoted
>>> print 'Doctest block'
Doctest block
Line blocks preserve line breaks & indents. [new in 0.3.6]
Useful for addresses, verse, and adornment-free lists; long lines can be wrapped with continuation lines.

Simple tables:

List Type Examples (syntax in the text source)
Bullet list
  • items begin with "-", "+", or "*"
Enumerated list
  1. items use any variation of "1.", "A)", and "(i)"
  2. also auto-enumerated
Definition list
Term is flush-left : optional classifier
Definition is indented, no blank line between
Field list
field name:field body
Option list
-o at least 2 spaces between option & description
Explicit Markup Examples (visible in the text source)
Footnote
[1]Manually numbered or [#] auto-numbered (even [#labelled]) or [*] auto-symbol
Citation
[CIT2002]A citation.
Hyperlink Target
Anonymous Target
Directive ("::") images/biohazard.png
Substitution Def
Comment  
Empty Comment (".." on a line by itself, with blank lines before & after, used to separate indentation contexts)

Inline Markup

emphasis; strong emphasis; interpreted text; interpreted text with role; inline literal text; standalone hyperlink, http://docutils.sourceforge.net; named reference, reStructuredText; anonymous reference; footnote reference, [1]; citation reference, [CIT2002]; like an inline directive; inline internal target.

Directive Quick Reference

See <http://docutils.sf.net/docs/ref/rst/directives.html> for full info.

Directive Name Description (Docutils version added to, in [brackets])
attention Specific admonition; also "caution", "danger", "error", "hint", "important", "note", "tip", "warning"
admonition Generic titled admonition: .. admonition:: By The Way
image .. image:: picture.png; many options possible
figure Like "image", but with optional caption and legend
topic .. topic:: Title; like a mini section
sidebar .. sidebar:: Title; like a mini parallel document
parsed-literal A literal block with parsed inline markup
rubric .. rubric:: Informal Heading
epigraph Block quote with class="epigraph"
highlights Block quote with class="highlights"
pull-quote Block quote with class="pull-quote"
compound Compound paragraphs [0.3.6]
container Generic block-level container element [0.3.10]
table Create a titled table [0.3.1]
list-table Create a table from a uniform two-level bullet list [0.3.8]
csv-table Create a table from CSV data [0.3.4]
contents Generate a table of contents
sectnum Automatically number sections, subsections, etc.
header, footer Create document decorations [0.3.8]
target-notes Create an explicit footnote for each external target
math Mathematical notation (input in LaTeX format)
meta HTML-specific metadata
include Read an external reST file as if it were inline
raw Non-reST data passed untouched to the Writer
replace Replacement text for substitution definitions
unicode Unicode character code conversion for substitution defs
date Generates today's date; for substitution defs
class Set a "class" attribute on the next element
role Create a custom interpreted text role [0.3.2]
default-role Set the default interpreted text role [0.3.10]
title Set the metadata document title [0.3.10]

Interpreted Text Role Quick Reference

See <http://docutils.sf.net/docs/ref/rst/roles.html> for full info.

Role Name Description
emphasis Equivalent to emphasis
literal Equivalent to literal but processes backslash escapes
math Mathematical notation (input in LaTeX format)
PEP Reference to a numbered Python Enhancement Proposal
RFC Reference to a numbered Internet Request For Comments
raw For non-reST data; cannot be used directly (see docs) [0.3.6]
strong Equivalent to strong
sub Subscript
sup Superscript
title Title reference (book, etc.); standard default role

reStructuredText Demonstration

Examples of Syntax Constructs

Author: David Goodger
Address:
123 Example Street
Example, EX  Canada
A1B 2C3
Contact: [email protected]
Authors: Me
Myself
I
Organization: humankind
Date: 2012-01-03
Status: This is a "work in progress"
Revision: 7302
Version: 1
Copyright: This document has been placed in the public domain. You may do with it as you wish. You may copy, modify, redistribute, reattribute, sell, buy, rent, lease, destroy, or improve it, quote it at length, excerpt, incorporate, collate, fold, staple, or mutilate it, or do anything else to it that your or anyone else's heart desires.
field name:This is a generic bibliographic field.
field name 2:

Generic bibliographic fields may contain multiple body elements.

Like this.

Dedication

For Docutils users & co-developers.

Abstract

This document is a demonstration of the reStructuredText markup language, containing examples of all basic reStructuredText constructs and many advanced constructs.

That's it, the text just above this line.

Here's a transition:


It divides the section.

A paragraph.

Paragraphs contain text and may contain inline markup: emphasis, strong emphasis, inline literals, standalone hyperlinks (http://www.python.org), external hyperlinks (Python [5]), internal cross-references (example), external hyperlinks with embedded URIs (Python web site), footnote references (manually numbered [1], anonymous auto-numbered [3], labeled auto-numbered [2], or symbolic [*]), citation references ([CIT2002]), substitution references (EXAMPLE), and inline hyperlink targets (see Targets below for a reference back to here). Character-level inline markup is also possible (although exceedingly ugly!) in reStructuredText. Problems are indicated by |problematic| text (generated by processing errors; this one is intentional).

The default role for interpreted text is Title Reference. Here are some explicit interpreted text roles: a PEP reference (PEP 287); an RFC reference (RFC 2822); a subscript; a superscript; and explicit roles for standard inline markup.

Let's test wrapping and whitespace significance in inline literals: This is an example of --inline-literal --text, --including some-- strangely--hyphenated-words. Adjust-the-width-of-your-browser-window to see how the text is wrapped. -- ---- -------- Now note the spacing between the words of this sentence (words should be grouped in pairs).

If the --pep-references option was supplied, there should be a live link to PEP 258 here.

  • A bullet list

    • Nested bullet list.
    • Nested item 2.
  • Item 2.

    Paragraph 2 of item 2.

    • Nested bullet list.
    • Nested item 2.
      • Third level.
      • Item 2.
    • Nested item 3.
  1. Arabic numerals.

    1. lower alpha)
      1. (lower roman)
        1. upper alpha.
          1. upper roman)
  2. Lists that don't start at 1:

    1. Three
    2. Four
    1. C
    2. D
    1. iii
    2. iv
  3. List items may also be auto-enumerated.

Term
Definition
Term : classifier

Definition paragraph 1.

Definition paragraph 2.

Term
Definition
what:

Field lists map field names to field bodies, like database records. They are often part of an extension syntax. They are an unambiguous variant of RFC 2822 fields.

how arg1 arg2:

The field marker is a colon, the field name, and a colon.

The field body may contain one or more body elements, indented relative to the field marker.

For listing command-line options:

-a command-line option "a"
-b file options can have arguments and long descriptions
--long options can be long also
--input=file long options can also have arguments
--very-long-option
 

The description can also start on the next line.

The description may contain multiple body elements, regardless of where it starts.

-x, -y, -z Multiple options are an "option group".
-v, --verbose Commonly-seen: short & long options.
-1 file, --one=file, --two file
 Multiple options with arguments.
/V DOS/VMS-style options too

There must be at least two spaces between the option and the description.

Literal blocks are indicated with a double-colon ("::") at the end of the preceding paragraph (over there -->). They can be indented:

if literal_block:
    text = 'is left as-is'
    spaces_and_linebreaks = 'are preserved'
    markup_processing = None

Or they can be quoted without indentation:

>> Great idea!
>
> Why didn't I think of that?
This is a line block. It ends with a blank line.
Each new line begins with a vertical bar ("|").
Line breaks and initial indents are preserved.
Continuation lines are wrapped portions of long lines; they begin with a space in place of the vertical bar.
The left edge of a continuation line need not be aligned with the left edge of the text above it.
This is a second line block.

Blank lines are permitted internally, but they must begin with a "|".

Take it away, Eric the Orchestra Leader!

A one, two, a one two three four

Half a bee, philosophically,
must, ipso facto, half not be.
But half the bee has got to be,
vis a vis its entity. D'you see?

But can a bee be said to be
or not to be an entire bee,
when half the bee is not a bee,
due to some ancient injury?

Singing...

Block quotes consist of indented body elements:

My theory by A. Elk. Brackets Miss, brackets. This theory goes as follows and begins now. All brontosauruses are thin at one end, much much thicker in the middle and then thin again at the far end. That is my theory, it is mine, and belongs to me and I own it, and what it is too.

—Anne Elk (Miss)

>>> print 'Python-specific usage examples; begun with ">>>"'
Python-specific usage examples; begun with ">>>"
>>> print '(cut and pasted from interactive Python sessions)'
(cut and pasted from interactive Python sessions)

Here's a grid table followed by a simple table:

Header row, column 1 (header rows optional) Header 2 Header 3 Header 4
body row 1, column 1 column 2 column 3 column 4
body row 2 Cells may span columns.
body row 3 Cells may span rows.
  • Table cells
  • contain
  • body elements.
body row 4
body row 5 Cells may also be empty: -->  
Inputs Output
A B A or B
False False False
True False True
False True True
True True True
[1](1, 2)

A footnote contains body elements, consistently indented by at least 3 spaces.

This is the footnote's second paragraph.

[2](1, 2) Footnotes may be numbered, either manually (as in [1]) or automatically using a "#"-prefixed label. This footnote has a label so it can be referred to from multiple places, both as a footnote reference ([2]) and as a hyperlink reference (label).
[3]This footnote is numbered automatically and anonymously using a label of "#" only.
[*]Footnotes may also use symbols, specified with a "*" label. Here's a reference to the next footnote: [†].
[†]This footnote shows the next symbol in the sequence.
[4]Here's an unreferenced footnote, with a reference to a nonexistent footnote: [5]_.
[CIT2002](1, 2) Citations are text-labeled footnotes. They may be rendered separately and differently from footnotes.

Here's a reference to the above, [CIT2002], and a [nonexistent]_ citation.

This paragraph is pointed to by the explicit "example" target. A reference can be found under Inline Markup, above. Inline hyperlink targets are also possible.

Section headers are implicit targets, referred to by name. See Targets, which is a subsection of Body Elements.

Explicit external targets are interpolated into references such as "Python [5]".

Targets may be indirect and anonymous. Thus this phrase may also refer to the Targets section.

Here's a `hyperlink reference without a target`_, which generates an error.

Duplicate names in section headers or other implicit targets will generate "info" (level-1) system messages. Duplicate names in explicit targets will generate "warning" (level-2) system messages.

Since there are two "Duplicate Target Names" section headers, we cannot uniquely refer to either of them by name. If we try to (like this: `Duplicate Target Names`_), an error is generated.

These are just a sample of the many reStructuredText Directives. For others, please see http://docutils.sourceforge.net/docs/ref/rst/directives.html.

An example of the "contents" directive can be seen above this section (a local, untitled table of contents) and at the beginning of the document (a document-wide table of contents).

An image directive (also clickable -- a hyperlink reference):

images/title.png

A figure directive:

reStructuredText, the markup syntax

A figure is an image with a caption and/or a legend:

re Revised, revisited, based on 're' module.
Structured Structure-enhanced text, structuredtext.
Text Well it is, isn't it?

This paragraph is also part of the legend.

Attention!

Directives at large.

Caution!

Don't take any wooden nickels.

!DANGER!

Mad scientist at work!

Error

Does not compute.

Hint

It's bigger than a bread box.

Important

  • Wash behind your ears.
  • Clean up your room.
  • Call your mother.
  • Back up your data.

Note

This is a note.

Tip

15% if the service is good.

Warning

Strong prose may provoke extreme mental exertion. Reader discretion is strongly advised.

And, by the way...

You can make up your own admonition too.

Sidebar Title

Optional Subtitle

This is a sidebar. It is for text outside the flow of the main text.

This is a rubric inside a sidebar

Sidebars often appears beside the main text with a border and background color.

Topic Title

This is a topic.

This is a rubric

[5](1, 2, 3) http://www.python.org/

I recommend you try Python, the best language around [5].

This paragraph contains a literal block:

Connecting... OK
Transmitting data... OK
Disconnecting... OK

and thus consists of a simple paragraph, a literal block, and another simple paragraph. Nonetheless it is semantically one paragraph.

This construct is called a compound paragraph and can be produced with the "compound" directive.

An inline image (EXAMPLE) example:

(Substitution definitions are not visible in the HTML source.)

Here's one:

(View the HTML source to see the comment.)

Any errors caught during processing will generate system messages.

|*** Expect 6 errors (including this one). ***|

There should be six messages in the following, auto-generated section, "Docutils System Messages":

A ReStructuredText Primer

Author: Richard Jones
Version: 5801
Copyright: This document has been placed in the public domain.

The text below contains links that look like "(quickref)". These are relative links that point to the Quick reStructuredText user reference. If these links don't work, please refer to the master quick reference document.

Note

This document is an informal introduction to reStructuredText. The What Next? section below has links to further resources, including a formal reference.

From the outset, let me say that "Structured Text" is probably a bit of a misnomer. It's more like "Relaxed Text" that uses certain consistent patterns. These patterns are interpreted by a HTML converter to produce "Very Structured Text" that can be used by a web browser.

The most basic pattern recognised is a paragraph (quickref). That's a chunk of text that is separated by blank lines (one is enough). Paragraphs must have the same indentation -- that is, line up at their left edge. Paragraphs that start indented will result in indented quote paragraphs. For example:

This is a paragraph.  It's quite
short.

   This paragraph will result in an indented block of
   text, typically used for quoting other text.

This is another one.

Results in:

This is a paragraph. It's quite short.

This paragraph will result in an indented block of text, typically used for quoting other text.

This is another one.

(quickref)

Inside paragraphs and other bodies of text, you may additionally mark text for italics with "*italics*" or bold with "**bold**". This is called "inline markup".

If you want something to appear as a fixed-space literal, use "``double back-quotes``". Note that no further fiddling is done inside the double back-quotes -- so asterisks "*" etc. are left alone.

If you find that you want to use one of the "special" characters in text, it will generally be OK -- reStructuredText is pretty smart. For example, this lone asterisk * is handled just fine, as is the asterisk in this equation: 5*6=30. If you actually want text *surrounded by asterisks* to not be italicised, then you need to indicate that the asterisk is not special. You do this by placing a backslash just before it, like so "\*" (quickref), or by enclosing it in double back-quotes (inline literals), like this:

``*``

Tip

Think of inline markup as a form of (parentheses) and use it the same way: immediately before and after the text being marked up. Inline markup by itself (surrounded by whitespace) or in the middle of a word won't be recognized. See the markup spec for full details.

Lists of items come in three main flavours: enumerated, bulleted and definitions. In all list cases, you may have as many paragraphs, sublists, etc. as you want, as long as the left-hand side of the paragraph or whatever aligns with the first line of text in the list item.

Lists must always start a new paragraph -- that is, they must appear after a blank line.

enumerated lists (numbers, letters or roman numerals; quickref)

Start a line off with a number or letter followed by a period ".", right bracket ")" or surrounded by brackets "( )" -- whatever you're comfortable with. All of the following forms are recognised:

1. numbers

A. upper-case letters
   and it goes over many lines

   with two paragraphs and all!

a. lower-case letters

   3. with a sub-list starting at a different number
   4. make sure the numbers are in the correct sequence though!

I. upper-case roman numerals

i. lower-case roman numerals

(1) numbers again

1) and again

Results in (note: the different enumerated list styles are not always supported by every web browser, so you may not get the full effect here):

  1. numbers
  1. upper-case letters and it goes over many lines

    with two paragraphs and all!

  1. lower-case letters
    1. with a sub-list starting at a different number
    2. make sure the numbers are in the correct sequence though!
  1. upper-case roman numerals
  1. lower-case roman numerals
  1. numbers again
  1. and again
bulleted lists (quickref)

Just like enumerated lists, start the line off with a bullet point character - either "-", "+" or "*":

* a bullet point using "*"

  - a sub-list using "-"

    + yet another sub-list

  - another item

Results in:

  • a bullet point using "*"
    • a sub-list using "-"
      • yet another sub-list
    • another item
definition lists (quickref)

Unlike the other two, the definition lists consist of a term, and the definition of that term. The format of a definition list is:

what
  Definition lists associate a term with a definition.

*how*
  The term is a one-line phrase, and the definition is one or more
  paragraphs or body elements, indented relative to the term.
  Blank lines are not allowed between term and definition.

Results in:

what
Definition lists associate a term with a definition.
how
The term is a one-line phrase, and the definition is one or more paragraphs or body elements, indented relative to the term. Blank lines are not allowed between term and definition.

(quickref)

To just include a chunk of preformatted, never-to-be-fiddled-with text, finish the prior paragraph with "::". The preformatted block is finished when the text falls back to the same indentation level as a paragraph prior to the preformatted block. For example:

An example::

    Whitespace, newlines, blank lines, and all kinds of markup
      (like *this* or \this) is preserved by literal blocks.
  Lookie here, I've dropped an indentation level
  (but not far enough)

no more example

Results in:

An example:

  Whitespace, newlines, blank lines, and all kinds of markup
    (like *this* or \this) is preserved by literal blocks.
Lookie here, I've dropped an indentation level
(but not far enough)

no more example

Note that if a paragraph consists only of "::", then it's removed from the output:

::

    This is preformatted text, and the
    last "::" paragraph is removed

Results in:

This is preformatted text, and the
last "::" paragraph is removed

(quickref)

To break longer text up into sections, you use section headers. These are a single line of text (one or more words) with adornment: an underline alone, or an underline and an overline together, in dashes "-----", equals "======", tildes "~~~~~~" or any of the non-alphanumeric characters = - ` : ' " ~ ^ _ * + # < > that you feel comfortable with. An underline-only adornment is distinct from an overline-and-underline adornment using the same character. The underline/overline must be at least as long as the title text. Be consistent, since all sections marked with the same adornment style are deemed to be at the same level:

Chapter 1 Title
===============

Section 1.1 Title
-----------------

Subsection 1.1.1 Title
~~~~~~~~~~~~~~~~~~~~~~

Section 1.2 Title
-----------------

Chapter 2 Title
===============

This results in the following structure, illustrated by simplified pseudo-XML:

<section>
    <title>
        Chapter 1 Title
    <section>
        <title>
            Section 1.1 Title
        <section>
            <title>
                Subsection 1.1.1 Title
    <section>
        <title>
            Section 1.2 Title
<section>
    <title>
        Chapter 2 Title

(Pseudo-XML uses indentation for nesting and has no end-tags. It's not possible to show actual processed output, as in the other examples, because sections cannot exist inside block quotes. For a concrete example, compare the section structure of this document's source text and processed output.)

Note that section headers are available as link targets, just using their name. To link to the Lists heading, I write "Lists_". If the heading has a space in it like text styles, we need to quote the heading "`text styles`_".

The title of the whole document is distinct from section titles and may be formatted somewhat differently (e.g. the HTML writer by default shows it as a centered heading).

To indicate the document title in reStructuredText, use a unique adornment style at the beginning of the document. To indicate the document subtitle, use another unique adornment style immediately after the document title. For example:

================
 Document Title
================
----------
 Subtitle
----------

Section Title
=============

...

Note that "Document Title" and "Section Title" above both use equals signs, but are distict and unrelated styles. The text of overline-and-underlined titles (but not underlined-only) may be inset for aesthetics.

(quickref)

To include an image in your document, you use the the image directive. For example:

.. image:: images/biohazard.png

results in:

images/biohazard.png

The images/biohazard.png part indicates the filename of the image you wish to appear in the document. There's no restriction placed on the image (format, size etc). If the image is to appear in HTML and you wish to supply additional information, you may:

.. image:: images/biohazard.png
   :height: 100
   :width: 200
   :scale: 50
   :alt: alternate text

See the full image directive documentation for more info.

This primer introduces the most common features of reStructuredText, but there are a lot more to explore. The Quick reStructuredText user reference is a good place to go next. For complete details, the reStructuredText Markup Specification is the place to go [1].

Users who have questions or need assistance with Docutils or reStructuredText should post a message to the Docutils-users mailing list.

[1]If that relative link doesn't work, try the master document: http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment