reStructuredText Guide

Introduction

This guide covers reStructuredText (rST) syntax from basic to advanced concepts for creating professional Sphinx documentation. reStructuredText is a powerful markup language that serves as the foundation for Sphinx documentation systems.

Note

This tutorial assumes you have Sphinx installed. If not, install it with: pip install sphinx

Basic Syntax

Headings

Headings in reStructuredText use underlines (and optionally overlines) to denote hierarchy:

Document Title (H1)     Chapter/Section (H2)        Subsection (H3)
===================     --------------------        ~~~~~~~~~~~~~~~

Sub-subsection (H4)     Paragraph (H5)              Sub-paragraph (H6)
^^^^^^^^^^^^^^^^^^^     """""""""""""""             '''''''''''''''''''

Important

The underline must be at least as long as the title text. Consistency in heading styles throughout your document is crucial.

Text Formatting

Basic text formatting options:

  • italic text - use single asterisks

  • bold text - use double asterisks

  • code text - use double backticks

Lists

* Item 1
* Item 2
   * Nested item 2.1
   * Nested item 2.2
* Item 3

Result:

  • Item 1

  • Item 2
    • Nested item 2.1

    • Nested item 2.2

  • Item 3

1. First item
2. Second item
3. Third item
#. Auto-numbered item
#. Another auto-numbered item
  1. First item

  2. Second item

  3. Third item

  4. Auto-numbered item

  5. Another auto-numbered item

Term 1
    Definition of term 1

Term 2
    Definition of term 2
Term 1

Definition of term 1

Term 2

Definition of term 2

Code and Literal Blocks

Use ``print("Hello, World!")`` to display inline code

Use double backticks for inline code: print("Hello, World!") (double backtick)

Code blocks with syntax highlighting:

.. code-block:: python

    def hello_world():
        print("Hello, World!")
        return True

Example result:

def hello_world():
    print("Hello, World!")
    return True

Include external code files:

.. literalinclude:: example.py
   :language: python
   :lines: 1-10
   :emphasize-lines: 2,3

Tables

.. csv-table:: Frozen Delights!
   :header: "Treat", "Quantity", "Description"
   :widths: 15, 10, 30

   "Albatross", 2.99, "On a stick!"
   "Crunchy Frog", 1.49, "If we took the bones out, it wouldn't be crunchy, now would it?"

Result:

Table 3 Frozen Delights!

Treat

Quantity

Description

Albatross

2.99

On a stick!

Crunchy Frog

1.49

If we took the bones out, it wouldn’t be crunchy, now would it?

=====  =====  =======
A      B      A and B
=====  =====  =======
False  False  False
True   False  False
False  True   False
True   True   True
=====  =====  =======

Result:

A

B

A and B

False

False

False

True

False

False

False

True

False

True

True

True

+------------+------------+-----------+
| Header 1   | Header 2   | Header 3  |
+============+============+===========+
| body row 1 | column 2   | column 3  |
+------------+------------+-----------+
| body row 2 | Cells may span columns.|
+------------+------------+-----------+

Result:

Header 1

Header 2

Header 3

body row 1

column 2

column 3

body row 2

Cells may span columns.

Images and Figures

.. image:: /_static/images/example.png
   :width: 200px
   :height: 100px
   :scale: 50%
   :alt: Alternative text
   :align: center
Alternative text

Figures are images with captions:

.. figure:: /_static/images/example.png
   :scale: 50%
   :alt: map to buried treasure

Sphinx Neo-Hittite
map to buried treasure

Sphinx Neo-Hittite

Sphinx-Specific Directives

Sphinx provides powerful cross-referencing:

:doc:`document-name`
:ref:`reference-label`
:class:`MyClass`
:func:`my_function`
:meth:`MyClass.my_method`
:attr:`MyClass.my_attribute`

Automatically document Python code:

.. automodule:: src.common
   :members:
   :undoc-members:
   :show-inheritance:

.. autoclass:: src.common.BaseTrainer
   :members:
   :inherited-members:

.. autofunction:: src.common.set_seed

Admonitions and Other Uncategories

.. note::
   This is a note.
.. seealso::
   See also this related information.
.. admonition:: Custom Title
   :class: custom-class
   This is a custom admonition with a custom title.

Custom Title

This is a custom admonition with a custom titl

Note

This is a note admonition.

See also

See also this related information.

Define reusable text substitutions:

.. |name| replace:: reStructuredText
.. |version| replace:: 1.0

The |name| software version |version| is available.

Result: The reStructuredText software version 1.0 is available.

.. This is a comment.
   It can span multiple lines.

..
   This is also a comment.
.. include:: filename.txt

Include content from other files:

2025-08-29

Changes: - Add comprehensive paper review template and baseline documentation structure - Implement pseudocode extension for enhanced documentation rendering - Update documentation layout with improved navigation and styling - Remove installation.md in favor of integrated setup documentation

Technical Notes: - Add pseudocode.py extension (287 lines) for rendering algorithmic content in documentation - Restructure baselines documentation with new index and example content - Update Sphinx configuration to support new documentation features - Enhance HTML templates with improved layout and navigation structure

2025-08-28

Changes: - Add paper review template system with new baselines documentation structure - Implement pseudocode extension for enhanced documentation rendering - Update documentation layout with improved navigation and styling - Remove installation.md in favor of restructured documentation format

Technical Notes: - Add new pseudocode.py extension (287 lines) for rendering algorithmic pseudocode in documentation - Implement baselines/lol.rst template (243 lines) for standardized paper review format - Update Sphinx configuration with new extensions and template paths - Restructure documentation hierarchy with dedicated baselines section

2025-08-27

Changes: - Add comprehensive sequence labeling support with Hidden Markov Model (HMM) and Conditional Hidden Markov Model (CHMM) implementations - Introduce synthetic dataset generation capabilities with configurable labeling function generators

Technical Notes: - Implement modular sequence labeling architecture in wrench/seq_labelmodel/ with wrapper classes for model integration - Add synthetic data generation pipeline in wrench/synthetic/ supporting various noise models and labeling function patterns

2025-08-26

Changes: - Updated all documentation to reflect universal baseline comparison framework - API documentation restructured for src.common modules - Getting started guide now uses import src.common as lib examples - Fixed Sphinx configuration for proper module imports

Technical Notes: - conf.py configured with correct project paths - Autosummary directives updated to reference framework modules

2025-08-24

Changes: - Initial framework structure with src.common utilities - BaseTrainer abstract class for baseline integration - Configuration management with TOML and hyperparameter tuning - LoL and LPWS baseline examples integrated

Technical Notes: - Framework designed for minimal changes to existing baselines - Shared utilities provide consistent interface across methods

Daily Template

Copy and paste this template for daily updates:

**YYYY-MM-DD**

Changes:
- Brief description of what was changed
- Another change made today

Technical Notes:
- Implementation details
- Architecture notes

Usage: 1. Copy the template above 2. Replace YYYY-MM-DD with today’s date 3. Add changes and technical notes 4. Insert at top of changelog (after “Unreleased” section)

literal:

start-line:

1

end-line:

20

expressions using LaTeX syntax:

.. math::

   \frac{1}{2\pi i} \oint_\gamma f(z) dz

Inline math: :math:`a^2 + b^2 = c^2`

Result:

\[\frac{1}{2\pi i} \oint_\gamma f(z) dz\]

Inline math: \(a^2 + b^2 = c^2\)

This is inline math: \(E = mc^2\) inside a sentence.

We can write pseudocode like below:

.. pcode::
   :line-number:

   \STATE left \gets 0
   \STATE right \gets length(A) - 1
   \WHILE{left \leq right}
      \STATE mid \gets \lfloor (left + right) / 2 \rfloor
      \IF{A[mid] = target}
         \STATE return \ mid
      \ENDIF
   \ENDWHILE
   \STATE return -1

Result:

            \STATE left \gets 0
\STATE right \gets length(A) - 1
\WHILE{left \leq right}
   \STATE mid \gets \lfloor (left + right) / 2 \rfloor
   \IF{A[mid] = target}
      \STATE return \ mid
   \ENDIF
\ENDWHILE
\STATE return -1
        

Create a glossary of terms:

.. glossary::

   environment
      A structure where information about all documents under the root is
      saved, and used for cross-referencing.

   source directory
      The directory which, including its subdirectories, contains all
      source files for one Sphinx project.

Result:

environment

A structure where information about all documents under the root is saved, and used for cross-referencing.

source directory

The directory which, including its subdirectories, contains all source files for one Sphinx project.

Cross-References and Indexing

Create index entries for better searchability:

.. index::
   single: Python
   pair: documentation; tools
   triple: reStructuredText; Sphinx; documentation

This paragraph discusses Python.

Essential configuration for your Sphinx project:

# Configuration file for the Sphinx documentation builder.

project = 'My Project'
copyright = '2024, Author Name'
author = 'Author Name'

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.viewcode',
    'sphinx.ext.napoleon',
    'sphinx.ext.intersphinx',
]

html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']

# Intersphinx mapping
intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
}

Document Structure:

Project Documentation
=====================

.. toctree::
   :maxdepth: 2
   :caption: User Guide:

   installation
   quickstart
   tutorial

.. toctree::
   :maxdepth: 2
   :caption: API Reference:

   api/modules
   api/classes

.. toctree::
   :maxdepth: 1
   :caption: Development:

   contributing
   changelog

Use consistent docstring format (NumPy style example):

def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    Parameters
    ----------
    param1 : int
        The first parameter.
    param2 : str
        The second parameter.

    Returns
    -------
    bool
        True if successful, False otherwise.

    Examples
    --------
    >>> function_with_types_in_docstring(1, "hello")
    True
    """
    return True

Use descriptive labels for cross-references:

.. _installation-guide:

Installation Guide
==================

Content here...

.. _quick-start:

Quick Start
-----------

See the :ref:`installation-guide` for setup instructions.

Napoleon Extension for Google/NumPy style docstrings:

# In conf.py
extensions = ['sphinx.ext.napoleon']

napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False

Intersphinx Extension for cross-project references:

See :py:func:`python:open` for file operations.

ViewCode Extension adds source code links:

# In conf.py
extensions = ['sphinx.ext.viewcode']

To use this guide effectively:

  1. Set up a Sphinx project:

    sphinx-quickstart myproject
    cd myproject
    
  2. Create your first .rst file using the syntax examples above

  3. Build your documentation:

    make html
    
  4. View the results in _build/html/index.html

Tip

Start with basic formatting and gradually incorporate advanced features as your documentation grows. The most essential elements are headings, paragraphs, links, code blocks, and the toctree directive.

Plugin: Sphinx-Design

Create attractive content cards:

.. card:: Card Title
   :margin: 3

   Card content goes here. Cards are great for organizing information
   into digestible sections.

   +++
   Card footer content

.. card:: Image Card
   :img-top: /_static/images/example.png
   :link: https://example.com

   This card has an image at the top and is clickable.

Result:

Card Title

Card content goes here. Cards are great for organizing information into digestible sections.

Create responsive layouts:

.. grid:: 2

   .. grid-item::

      Left column content

   .. grid-item::

      Right column content

.. grid:: 1 2 2 3
   :gutter: 2

   .. grid-item-card:: Card 1

      Content for card 1

   .. grid-item-card:: Card 2

      Content for card 2

   .. grid-item-card:: Card 3

      Content for card 3

Result:

Left column content

Right column content

Create collapsible content sections:

.. dropdown:: Click to expand
   :open:

   This dropdown is open by default.

.. dropdown:: Advanced Options
   :icon: tools

   This dropdown has a custom icon and is closed by default.

   * Option 1
   * Option 2
   * Option 3

Result:

Click to expand

This dropdown is open by default.

Advanced Options

This dropdown has a custom icon and is closed by default.

  • Option 1

  • Option 2

  • Option 3

Create interactive elements:

.. button-ref:: installation
   :color: primary
   :outline:

   Install Now

.. button-link:: https://example.com
   :color: secondary

   External Link

:bdg:`plain badge`
:bdg-primary:`primary`
:bdg-secondary:`secondary`
:bdg-success:`success`
:bdg-info:`info`
:bdg-warning:`warning`
:bdg-danger:`danger`
:bdg-light:`light`
:bdg-dark:`dark`

Result:

plain badge primary secondary success info warning danger

Add content to sidebars

.. sidebar:: Sidebar Title
   :subtitle: Optional subtitle

   Sidebar content appears to the right of the main content.

Main content continues here with sidebar

Use icons throughout your documentation:

:octicon:`mark-github` GitHub
:octicon:`home` Home
:octicon:`info` Information
:octicon:`alert` Alert
:octicon:`check` Success

:material-regular:`home` Material Home
:material-outlined:`info` Material Info
:fa:`home` FontAwesome Home

Result:

GitHub Home Information Alert Success

Conclusion

This guide provides a comprehensive overview of reStructuredText syntax for Sphinx documentation. Master the basics first, then progressively add more sophisticated features to create professional, navigable documentation.

For more information, consult the official Sphinx documentation and reStructuredText documentation.