=============================================== reStructuredText Guide =============================================== .. meta:: :description: A comprehensive guide to reStructuredText syntax for Sphinx documentation :keywords: reStructuredText, Sphinx, documentation, rST, tutorial .. .. contents:: Table of Contents .. :depth: 3 .. :local: 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: .. code-block:: rst 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 .. _my-section-list: Lists ----- .. tab-set:: .. tab-item:: Bulleted Lists .. code-block:: rst * 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 .. tab-item:: Numbered Lists .. code-block:: rst 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 #. Auto-numbered item #. Another auto-numbered item .. tab-item:: Definition Lists .. code-block:: rst Term 1 Definition of term 1 Term 2 Definition of term 2 Term 1 Definition of term 1 Term 2 Definition of term 2 Links and References ==================== .. tab-set:: .. tab-item:: External Links Here are all the ways to create external links in reStructuredText: .. code-block:: rst * Visit `Google `__ for search. * Visit `Google `_ for search. * Check the search google_, this is clean and reusable. .. _google: https://google.com/ Result: * Visit `Google `_ for search. .. tab-item:: Internal Cross-References Create internal references using labels: .. code-block:: rst .. _my-reference-label: Section Title ------------- after many contents See :ref:`my-reference-label`. Result: For an example, you can click :ref:`my-section-list` to quickly navigate .. tab-item:: Document Links Link to other documents in your Sphinx project: .. code-block:: rst :doc:`other-document` :doc:`subfolder/document` Result: For example, you can click :doc:`index` to go back, or :doc:`../CHANGELOG` to view the changelog. Code and Literal Blocks ======================== .. tab-set:: .. tab-item:: Inline Code .. code-block:: rst Use ``print("Hello, World!")`` to display inline code Use double backticks for inline code: ``print("Hello, World!")`` (double backtick) .. tab-item:: Code Blocks Code blocks with syntax highlighting: .. code-block:: rst .. code-block:: python def hello_world(): print("Hello, World!") return True Example result: .. code-block:: python def hello_world(): print("Hello, World!") return True .. tab-item:: Literal Includes Include external code files: .. code-block:: rst .. literalinclude:: example.py :language: python :lines: 1-10 :emphasize-lines: 2,3 Tables ====== .. tab-set:: .. tab-item:: CSV Table .. code-block:: rst .. 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: .. 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?" .. tab-item:: Simple Table .. code-block:: rst ===== ===== ======= 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 ===== ===== ======= .. tab-item:: Grid Table .. code-block:: rst +------------+------------+-----------+ | 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.| +------------+------------+-----------+ .. _my-image-section: Images and Figures ================== .. tab-set:: .. tab-item:: Images .. code-block:: rst .. image:: /_static/images/example.png :width: 200px :height: 100px :scale: 50% :alt: Alternative text :align: center .. image:: /_static/images/example.png :width: 200px :height: 100px :scale: 50% :alt: Alternative text :align: center .. tab-item:: Figures Figures are images with captions: .. code-block:: rst .. figure:: /_static/images/example.png :scale: 50% :alt: map to buried treasure Sphinx Neo-Hittite .. figure:: /_static/images/example.png :scale: 50% :alt: map to buried treasure Sphinx Neo-Hittite Sphinx-Specific Directives =========================== .. tab-set:: .. tab-item:: Cross-References :selected: Sphinx provides powerful cross-referencing: .. code-block:: rst :doc:`document-name` :ref:`reference-label` :class:`MyClass` :func:`my_function` :meth:`MyClass.my_method` :attr:`MyClass.my_attribute` * Check out :doc:`/api/index` for the API reference. * See the :ref:`my-image-section` for setup instructions. * Class/func/meth/attr reference * Import the main :class:`src.common.WSDataLoader` class * Create an instance and call :func:`src.common.set_seed` * Check if training completed with :attr:`src.common.Timer().total_elapsed` * Use :func:`src.common.save_json` for predictions .. tab-item:: Autodoc Automatically document Python code: .. code-block:: rst .. automodule:: src.common :members: :undoc-members: :show-inheritance: .. autoclass:: src.common.BaseTrainer :members: :inherited-members: .. autofunction:: src.common.set_seed Admonitions and Other Uncategories ================================== .. tab-set:: .. tab-item:: Admonitions .. code-block:: rst .. 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. .. admonition:: Custom Title :class: custom-class This is a custom admonition with a custom titl .. note:: This is a note admonition. .. seealso:: See also this related information. .. tab-item:: Substitutions Define reusable text substitutions: .. code-block:: rst .. |name| replace:: reStructuredText .. |version| replace:: 1.0 The |name| software version |version| is available. .. |name| replace:: reStructuredText .. |version| replace:: 1.0 Result: The |name| software version |version| is available. .. tab-item:: Comments .. code-block:: rst .. This is a comment. It can span multiple lines. .. This is also a comment. .. This is a comment that won't appear in the output. .. tab-item:: Include Files .. code-block:: rst .. include:: filename.txt Include content from other files: .. dropdown:: .. include:: /CHANGELOG.rst :literal: :start-line: 1 :end-line: 20 .. tab-item:: Math expressions using LaTeX syntax: .. code-block:: rst .. math:: \frac{1}{2\pi i} \oint_\gamma f(z) dz Inline math: :math:`a^2 + b^2 = c^2` Result: .. math:: \frac{1}{2\pi i} \oint_\gamma f(z) dz Inline math: :math:`a^2 + b^2 = c^2` This is inline math: $E = mc^2$ inside a sentence. .. tab-item:: PseudoCode We can write pseudocode like below: .. code-block:: rst .. 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: .. pcode:: :linenos: \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 .. tab-item:: Glossary Create a glossary of terms: .. code-block:: rst .. 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: .. 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. Cross-References and Indexing ============================== .. tab-set:: .. tab-item:: Index Entries Create index entries for better searchability: .. index:: single: Python pair: documentation; tools triple: reStructuredText; Sphinx; documentation .. code-block:: rst .. index:: single: Python pair: documentation; tools triple: reStructuredText; Sphinx; documentation This paragraph discusses Python. .. tab-item:: Sphinx Configuration Essential configuration for your Sphinx project: .. code-block:: python # 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), } .. tab-item:: Best Practices Document Structure: .. code-block:: rst 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 .. tab-item:: Docstring Format Use consistent docstring format (NumPy style example): .. code-block:: python 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 .. tab-item:: Cross-Reference Labels Use descriptive labels for cross-references: .. _installation-guide: .. code-block:: rst .. _installation-guide: Installation Guide ================== Content here... .. _quick-start: Quick Start ----------- See the :ref:`installation-guide` for setup instructions. .. tab-item:: Common Extensions **Napoleon Extension** for Google/NumPy style docstrings: .. code-block:: python # 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: .. code-block:: rst See :py:func:`python:open` for file operations. **ViewCode Extension** adds source code links: .. code-block:: python # In conf.py extensions = ['sphinx.ext.viewcode'] .. tab-item:: Getting Started To use this guide effectively: 1. **Set up a Sphinx project**: .. code-block:: bash sphinx-quickstart myproject cd myproject 2. **Create your first .rst file** using the syntax examples above 3. **Build your documentation**: .. code-block:: bash 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 ================================= .. tab-set:: .. tab-item:: Cards Create attractive content cards: .. code-block:: rst .. 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:: Card Title :margin: 3 Card content goes here. Cards are great for organizing information into digestible sections. +++ Card footer content .. tab-item:: Grids Create responsive layouts: .. code-block:: rst .. 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: .. grid:: 2 .. grid-item:: Left column content .. grid-item:: Right column content .. tab-item:: Dropdowns Create collapsible content sections: .. code-block:: rst .. 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: .. 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 .. tab-item:: Buttons & Badges Create interactive elements: .. code-block:: rst .. 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: :bdg:`plain badge` :bdg-primary:`primary` :bdg-secondary:`secondary` :bdg-success:`success` :bdg-info:`info` :bdg-warning:`warning` :bdg-danger:`danger` .. tab-item:: Sidebar Add content to sidebars .. code-block:: rst .. sidebar:: Sidebar Title :subtitle: Optional subtitle Sidebar content appears to the right of the main content. Main content continues here with sidebar .. tab-item:: Icons & Octicons Use icons throughout your documentation: .. code-block:: rst :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: :octicon:`mark-github` GitHub :octicon:`home` Home :octicon:`info` Information :octicon:`alert` Alert :octicon:`check` 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 `_. .. seealso:: - `Sphinx Tutorial `_ - `reStructuredText Primer `_ - `Sphinx Extensions `_ - `Sphinx | Sublime | Github `_