reStructuredText Example and Sphinx Cheat Sheet
November 11, 2026 · 12 min read
reStructuredText Example Cheat Sheet for Sphinx
Here's a restructuredtext example you can build as is. It's a two-page Sphinx project with underlined titles, inline markup, links, :doc: and :ref: roles, a code-block, a note and a toctree. Below it sits a reStructuredText cheat sheet for each construct, plus comments and docstring fields. The last section maps the warnings Sphinx prints most often to their fixes.
A Complete reStructuredText Example Page
Most references show each construct on its own. Below is a real index.rst plus the install.rst page it links to, so you can see how the pieces fit together. If you're still deciding whether to use RST at all, our Markdown vs reStructuredText comparison covers that choice. This page assumes you've already picked it.
.. _home:
Weather Kit
===========
**Weather Kit** fetches forecasts for any city. It needs *Python 3.10*
or later and one API key, set as ``WEATHER_KEY``.
Read the `Sphinx docs <https://www.sphinx-doc.org/>`__ for build
options, or jump to :doc:`install`.
Quick start
-----------
Call ``forecast()`` with a city name:
.. code-block:: python
:caption: quickstart.py
:emphasize-lines: 3
from weatherkit import forecast
print(forecast("Lisbon", days=3))
.. note::
The free key allows 100 requests a day.
.. toctree::
:maxdepth: 2
:caption: Contents
install
And the second file, install.rst, sitting next to it:
Installation
============
Install it with pip::
pip install weatherkit
See :ref:`home` for the overview.
Add an empty conf.py beside them, because sphinx-build refuses to run without one. We built this reStructuredText example with sphinx-build -b html and got zero warnings. Here's what each part becomes in the HTML output:
.. _home:is a label. It renders nothing, but:ref:links can point at the title below it.- The
=underline makes "Weather Kit" the page title, and the-underline makes "Quick start" a section under it. - The asterisks and double backticks render as bold, italic and monospace text.
- The link with two trailing underscores becomes an external link, and the
:doc:role becomes a link whose text is the other page's title, "Installation". - The
code-blockrenders as a Python listing with a "quickstart.py" caption and line 3 highlighted. - The
notebecomes a boxed admonition titled "Note", and thetoctreeprints a "Contents" list linking to the install page. - In
install.rst, the double colon turns into a single colon and the indented line becomes a literal block.
Section Titles and Underline Rules
A section title is a line of text with a punctuation underline at least as long as the text. You can add a matching overline too. Docutils doesn't assign levels to characters. The first style it meets becomes level 1, the second becomes level 2, and so on.
##########
User Guide
##########
Configuration
=============
Environment variables
---------------------
Proxy settings
^^^^^^^^^^^^^^
Overline and underline must use the same character and length when you use both. An overlined = title also counts as a different style from an underline-only = title, so mixing them creates an extra level by accident.
There's no fixed scheme, but the Sphinx reStructuredText primer suggests the Python Developer's Guide convention:
| Character | Used for |
|---|---|
# with overline | Parts |
* with overline | Chapters |
= | Sections |
- | Subsections |
^ | Subsubsections |
" | Paragraphs |
Give every file exactly one top-level title. Sphinx uses it as the page title in the toctree and as the default link text for :doc: references.
Inline Markup, Links and Sphinx Roles
Inline markup covers emphasis, strong text and inline literals. External links come in two common forms, and Sphinx adds roles for cross-references. Here's the core syntax:
*emphasis*, **strong** and ``inline literal``
An inline link: `Sphinx primer <https://www.sphinx-doc.org/>`__
A link with the URL kept below: read `the docutils spec`_ first.
.. _the docutils spec: https://docutils.sourceforge.io/rst.html
The first line renders as italic, bold and monospace. The inline link and the named link both become ordinary external links. Sphinx roles use the pattern :rolename:`content`, and these five cover most cross-references:
| Role | Example | What it produces |
|---|---|---|
| doc | :doc:`install` | Link to another file, with its title as the text |
| ref | :ref:`home` | Link to a label, with the section title as the text |
| ref with text | :ref:`the overview <home>` | Link to a label, with your own text |
| code | :code:`len(items)` | Inline code |
| term | :term:`forecast window` | Link to an entry in a glossary directive |
Three rules trip people up. Inline markup can't be nested, so *see :func:`foo`* won't work. The content can't start or end with a space. The markup must also be separated from surrounding text by spaces or punctuation, so you write thisis\ *one*\ word with backslash-escaped spaces to glue it to a word.
For links, leave a space before the <. Use two trailing underscores for inline links. A single underscore also registers the link text as a target name, so Docutils 0.21 and earlier warn when the same text points to two URLs. For internal links, prefer :ref: labels over section-title links: they work across files and Sphinx warns when the target disappears. The :term: role needs a matching entry in a glossary directive.
How Do I Add a Code Block in reStructuredText?
A reStructuredText code block takes one of two forms. End a paragraph with :: for a plain literal block, or use the code-block directive when you want a language, line numbers or a caption. Either way, leave a blank line before the code and indent it.
The :: marker behaves in three ways. On a line of its own, it disappears from the output. After a space, it's removed. Directly after text, it becomes a single colon, so "Run this::" renders as "Run this:".
.. code-block:: python
:linenos:
:emphasize-lines: 2
:caption: retry.py
for attempt in range(3):
if fetch():
break
This renders a Python listing with line numbers, line 2 highlighted and "retry.py" as the caption. The language argument has been optional since Sphinx 2.0. Leave it out and Sphinx falls back to the highlight directive or the highlight_language setting. The sourcecode alias works the same way.
Other options worth knowing are :lineno-start: to begin numbering at a given line, :dedent: to strip leading spaces and :name: to make the block a :ref: target. For real source files, literalinclude pulls code straight from disk, so the docs can't drift from the code:
.. literalinclude:: ../src/weatherkit/client.py
:language: python
:pyobject: forecast
The :pyobject: option picks out a single function or class, and :lines: selects a line range instead. Markdown handles this with backtick fences, which our guide to Markdown code blocks covers separately.
Directives You Use in Every Sphinx Project
Every directive follows one pattern: two dots, a space, the name, two colons, then optional arguments. Options sit on the next lines, and the content follows after a blank line, indented to match. Here are the ones most Sphinx projects lean on, and the Sphinx directives reference lists every option:
.. warning::
Rotating the API key logs out every client.
.. image:: _static/radar.png
:alt: Rain radar over Lisbon at noon
:width: 600px
.. figure:: _static/chart.png
:alt: Temperature chart for one week
Daily highs for the first week of May.
.. toctree::
:maxdepth: 2
:caption: User guide
:hidden:
install
usage
.. include:: ../CHANGELOG.rst
Docutils ships attention, caution, danger, error, hint, important, note, tip and warning admonitions. Sphinx adds seealso, and your theme decides how each type looks. A figure is an image with a caption paragraph, and :alt: gives screen readers a description.
The toctree directive builds the page hierarchy and the sidebar. Entries are document names without the .rst extension, relative to the current file. :hidden: keeps the list out of the page body while still building the navigation.
Tables have four syntaxes (grid, simple, CSV and list tables), and the simple table is the quickest to type:
===== ======
City Temp
===== ======
Oslo 4
Lima 19
===== ======
How Do You Comment in reStructuredText?
Start a line with two dots and a space, then write anything that isn't valid explicit markup. Docutils treats that block as a comment and drops it from the output. For a multi-line comment, put .. alone on a line and indent the text under it. Here are the three common forms:
.. This is a single-line comment.
..
This whole indented block is a comment.
It can run as long as you like.
.. TODO: rewrite this section after the 2.0 release.
None of these lines appear in the built HTML. The TODO line is safe because it has one colon, not two. Write .. TODO:: fix and Sphinx reads a directive instead. Likewise, .. note:: renders a visible box, not a comment, and a line like .. _draft: defines a link target.
reStructuredText has no inline comment syntax. The Docutils spec says so directly, so a comment always takes up at least one full line.
Field Lists for Documenting Python Functions
Sphinx's autodoc extension reads docstrings as reStructuredText and turns info field lists into Parameters, Returns and Raises sections. A minimal function looks like this:
def forecast(city, days=1):
"""Return a short forecast for a city.
:param city: Name of the city, for example ``"Lisbon"``.
:type city: str
:param days: How many days to include, from 1 to 7.
:type days: int
:returns: One line of text per day.
:rtype: list[str]
:raises ValueError: If ``days`` is outside 1 to 7.
"""
Add "sphinx.ext.autodoc" to the extensions list in conf.py, then document the function from any page with .. autofunction:: weatherkit.forecast. Teams that prefer Google or NumPy style docstrings can switch on the bundled sphinx.ext.napoleon extension instead. Our code documentation examples show a Google style docstring next to JSDoc, Javadoc and Go.
How Do I View or Preview an .rst File?
The most accurate preview is a real build. Run this from your project root and open the generated index.html:
sphinx-build -b html docs docs/_build/html
For a single file without a Sphinx project, Docutils installs a generic docutils command (since 0.19) plus front-end tools such as rst2html. Running docutils page.rst --output=page.html writes a standalone HTML page. Plain Docutils doesn't know Sphinx, though. It reports toctree as an unknown directive and :doc: as an unknown role.
GitHub renders .rst files, including READMEs, through Docutils too, with error messages switched off. Sphinx-only directives such as toctree show up as raw preformatted text, and roles such as :doc: don't become links. In VS Code, the built-in preview handles Markdown only. The Esbonio extension adds a Sphinx language server with completion, error highlighting and a near real-time preview.
Our markup converter runs in the browser and converts basic reStructuredText to Markdown and back. It isn't a full RST renderer, though. Directives such as code-block, toctree and note aren't fully supported, and our editor's preview renders Markdown, not RST.
Fixing the Warnings Sphinx Prints Most Often
Sphinx prefixes most messages with the file and line number, so you can jump straight to the problem. We reproduced each message below by breaking the reStructuredText example project on purpose:
| Message | Usual cause | Fix |
|---|---|---|
| Title underline too short. | Underline shorter than the title text | Extend the underline to at least the title length |
| Unexpected indentation. | An indented line inside a paragraph | Add a blank line before it or remove the indent |
| Inline literal start-string without end-string. | Unclosed double backticks | Close the literal or escape the backticks |
| Bullet list ends without a blank line; unexpected unindent. | Text right after a list item | Add a blank line after the list |
| Duplicate explicit target name: "x". | Two labels with the same name, or one link text used for two URLs (Docutils 0.21 and earlier) | Use two trailing underscores or rename the label |
| Error in "code-block" directive: maximum 1 argument(s) allowed | No blank line between the directive and the code | Add the blank line |
| document isn't included in any toctree | A file no toctree lists | Add it to a toctree, or put :orphan: at the top |
| unknown document: 'x' | A bad :doc: path | Use a path relative to the current file, without .rst |
Docutils labels some of these "ERROR" rather than "WARNING", but Sphinx still reports the build as succeeded. That's why we prefer running sphinx-build with -W (long form --fail-on-warning) in CI. Since Sphinx 8.1 it finishes the whole build, lists every problem and then exits with status 1.
Keep this restructuredtext example project as a starting template: copy the two files, add an empty conf.py, run sphinx-build -W, and fix whatever the table above flags. When you need to move content between formats, the markup converter mentioned above handles basic RST to Markdown. If your team decides Markdown suits its documentation better, MkDocs is the usual alternative to Sphinx, and you can draft pages in our free Markdown editor with a live preview.