Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Sphinx
https://github.com/sphinx-doc/sphinx
Admin
The Sphinx documentation generator
Tokens:
2,489,212
Snippets:
21,853
Trust Score:
9.2
License:
BSD-2-Clause
Update:
2 weeks ago
Context
Chat
Benchmark
69.28
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Run sphinx-quickstart to create docs layout Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Starts the interactive setup for the documentation directory. You will be prompted for several configuration options. ```console (.venv) $ sphinx-quickstart docs ``` -------------------------------- ### epub_guide configuration example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/configuration.rst Example of setting the epub_guide option with a tuple containing type, URI, and title for the guide element. ```python epub_guide = ( ('cover', 'cover.html', 'Cover Page'), ) ``` -------------------------------- ### Run sphinx-quickstart Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst Use this command in your terminal to start the interactive setup for a new Sphinx project. It creates a source directory and a default conf.py file. ```console $ sphinx-quickstart ``` -------------------------------- ### Set up environment with pip (alternative) Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/internals/contributing.md Alternative setup using pip: create a virtual environment, activate it, and install the package in editable mode. ```shell python -m venv .venv . .venv/bin/activate python -m pip install -e . ``` -------------------------------- ### Set up environment with pip Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/internals/contributing.rst Alternative environment setup using pip: creates a virtual environment, activates it, and installs Sphinx in editable mode. ```shell python -m venv .venv . .venv/bin/activate python -m pip install -e . ``` -------------------------------- ### Activate another extension with app.setup_extension() Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/howtos/setup_extension.rst Use this in your extension's setup() function to activate another Sphinx extension at run-time. The example activates sphinx.ext.autodoc. Ensure the dependency is included in your extension's installation requirements. ```python def setup(app): app.setup_extension('sphinx.ext.autodoc') ``` -------------------------------- ### Install Transifex CLI tool Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/intl.rst Installs the Transifex CLI tool (tx) by downloading and running the official installation script. The binary is placed in the current directory and that directory is added to $PATH. ```console $ curl -o- https://raw.githubusercontent.com/transifex/cli/master/install.sh | bash ``` -------------------------------- ### Install Transifex CLI tool Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/advanced/intl.md Installs the Transifex CLI tool (tx) by downloading and running the official installation script. The binary is placed in the current directory and that directory is added to $PATH. ```console $ curl -o- https://raw.githubusercontent.com/transifex/cli/master/install.sh | bash ``` -------------------------------- ### Install Sphinx from source Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/installation.md Install Sphinx from source by cloning the Git repository and installing locally, or directly via git with pip. Both methods install the latest development version. ```console $ git clone https://github.com/sphinx-doc/sphinx $ cd sphinx $ pip install . ``` ```console $ pip install git+https://github.com/sphinx-doc/sphinx ``` -------------------------------- ### epub_pre_files configuration example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/configuration.rst Example of adding a file before the generated text using the epub_pre_files option. ```python epub_pre_files = [ ('index.html', 'Welcome'), ] ``` -------------------------------- ### Set up virtual environment and install Sphinx Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-directive-only/tutorial/getting-started.md Commands to create a Python virtual environment, activate it, and install Sphinx. Run these in a terminal after creating the project directory. ```console $ python -m venv .venv $ source .venv/bin/activate (.venv) $ python -m pip install sphinx ``` -------------------------------- ### epub_post_files configuration example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/configuration.rst Example of adding a file after the generated text using the epub_post_files option. ```python epub_post_files = [ ('appendix.xhtml', 'Appendix'), ] ``` -------------------------------- ### Complete Sphinx extension in helloworld.py Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-autosectionlabel-prefix-document/development/tutorials/extending_syntax.md Full example of a Sphinx extension defining a role and a directive. It includes the setup function that registers them and returns extension metadata. ```python from __future__ import annotations from docutils import nodes from sphinx.application import Sphinx from sphinx.util.docutils import SphinxDirective, SphinxRole from sphinx.util.typing import ExtensionMetadata class HelloRole(SphinxRole): """A role to say hello!""" def run(self) -> tuple[list[nodes.Node], list[nodes.system_message]]: node = nodes.inline(text=f'Hello {self.text}!') return [node], [] class HelloDirective(SphinxDirective): """A directive to say hello!""" required_arguments = 1 def run(self) -> list[nodes.Node]: paragraph_node = nodes.paragraph(text=f'hello {self.arguments[0]}!') return [paragraph_node] def setup(app: Sphinx) -> ExtensionMetadata: app.add_role('hello', HelloRole()) app.add_directive('hello', HelloDirective) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Set up virtual environment and install Sphinx Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Commands to create a Python virtual environment, activate it, and install Sphinx. The output shows the prompt change after activation. ```console $ python -m venv .venv $ source .venv/bin/activate (.venv) $ python -m pip install sphinx ``` -------------------------------- ### Install Sphinx from source Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Install Sphinx from source. The first block clones the repository, changes into the directory, and installs from the local clone. The second block installs directly from the Git repository using pip. ```console $ git clone https://github.com/sphinx-doc/sphinx $ cd sphinx $ pip install . ``` ```console $ pip install git+https://github.com/sphinx-doc/sphinx ``` -------------------------------- ### Install uv Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/internals/contributing.md Install the uv dependency manager using pip. ```shell python -m pip install -U uv ``` -------------------------------- ### Extension setup methods Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-latex-numfig/extdev/appapi.md These methods are called in an extension's setup() function and raise ExtensionError on failure. ```APIDOC ## Extension setup ### Description Methods called in an extension's `setup()` function to register extension functionality with Sphinx. ### Methods - **setup(app)** - Called at initialization time with the application object. ### Exceptions - **ExtensionError** - Raised if something goes wrong with the extension API. ### Usage Call these methods within the `setup()` function of your extension module. ``` -------------------------------- ### Domain add_recipe method and setup function Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/tutorials/adding_domain.rst Defines the add_recipe method on the domain class and the setup function that registers the domain with Sphinx. The setup returns extension metadata with version and parallel safety flags. ```python def add_recipe(self, signature, ingredients): """Add a new recipe to the domain.""" name = f'recipe.{signature}' anchor = f'recipe-{signature}' self.data['recipe_ingredients'][name] = ingredients # name, dispname, type, docname, anchor, priority self.data['recipes'].append(( name, signature, 'Recipe', self.env.current_document.docname, anchor, 0, )) def setup(app: Sphinx) -> ExtensionMetadata: app.add_domain(RecipeDomain) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Install Sphinx on Debian/Ubuntu with apt-get Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-api-set-translator/usage/installation.md Install Sphinx on Debian/Ubuntu using apt-get. Installs Python if it is not already present. ```console $ apt-get install python3-sphinx ``` -------------------------------- ### setup function for the extension Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/tutorials/extending_syntax.rst Defines the setup function that registers the custom role and directive with Sphinx and returns extension metadata. ```python def setup(app: Sphinx) -> ExtensionMetadata: app.add_role('hello', HelloRole()) app.add_directive('hello', HelloDirective) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Decorator with parameter example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-html_signaturereturn_icon/usage/domains/python.md Example showing how to document a decorator that takes parameters. ```python .. py:decorator:: setnewname(name) Set name of the decorated function to *name*. ``` -------------------------------- ### Install Sphinx from local clone Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-add_enumerable_node/usage/installation.md Clones the Sphinx Git repository and installs it from the local clone. This is one of two ways to install from source. ```console $ git clone https://github.com/sphinx-doc/sphinx $ cd sphinx $ pip install . ``` -------------------------------- ### Install dependencies from requirements.txt Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Installs dependencies from a requirements.txt file, which is recommended to pin Sphinx and third-party extension versions. ```console $ pip install -r requirements.txt ``` -------------------------------- ### Info references and external link example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-viewcode-find/faq.md The first two examples are identical display references from the generated Info source, illustrating how a reference appears. The third example shows the URI scheme for linking to external Info files. ```default * note Displaying Links: target-id ``` ```default * note Displaying Links: target-id ``` ```default info:Texinfo#makeinfo_options ``` -------------------------------- ### Decorator signature example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-html_signaturereturn_icon/usage/domains/python.md Example showing how to document a decorator with a signature. ```python .. py:decorator:: removename Remove name of the decorated function. ``` -------------------------------- ### Install sphinx-intl Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/advanced/intl.md Install the sphinx-intl package using pip. ```console $ pip install sphinx-intl ``` -------------------------------- ### Conditionally skip doctest directives with skipif when pandas is missing Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/extensions/doctest.rst Configure Sphinx to use the doctest extension and define a global setup that imports pandas or sets it to None if unavailable. The RST example then uses the `skipif` option on testsetup, doctest, testcode, and testoutput directives to conditionally skip tests when pandas is not installed. ```py extensions = ['sphinx.ext.doctest'] doctest_global_setup = ''' try: import pandas as pd except ImportError: pd = None ''' ``` ```rst .. testsetup:: :skipif: pd is None data = pd.Series([42]) .. doctest:: :skipif: pd is None >>> data.iloc[0] 42 .. testcode:: :skipif: pd is None print(data.iloc[-1]) .. testoutput:: :skipif: pd is None 42 ``` -------------------------------- ### Run sphinx-quickstart to create documentation layout Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-directive-only/tutorial/getting-started.md Command to initialize a Sphinx project in the docs directory. It prompts for several configuration options. ```console (.venv) $ sphinx-quickstart docs ``` -------------------------------- ### Install sphinx-intl Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/intl.rst Install the sphinx-intl package using pip. ```console $ pip install sphinx-intl ``` -------------------------------- ### INI file for :start-at: and :end-before: example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/restructuredtext/directives.rst Example INI file used to illustrate the :start-at: and :end-before: options. To select only [second-section], use :start-at: [second-section] and :end-before: [third-section]. ```ini [first-section] var_in_first=true [second-section] var_in_second=true [third-section] var_in_third=true ``` -------------------------------- ### code-block directive examples with options Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-intersphinx-role/usage/restructuredtext/directives.md Examples of the code-block directive with various options, including language, line numbers, line number start, emphasized lines, caption and name, and dedent. ```rst .. code-block:: ruby Some Ruby code. ``` ```rst .. code-block:: ruby :linenos: Some more Ruby code. ``` ```rst .. code-block:: ruby :lineno-start: 10 Some more Ruby code, with line numbering starting at 10. ``` ```rst .. code-block:: python :emphasize-lines: 3,5 def some_function(): interesting = False print('This line is highlighted.') print('This one is not...') print('...but this one is.') ``` ```rst .. code-block:: python :caption: this.py :name: this-py print('Explicit is better than implicit.') ``` ```rst .. code-block:: ruby :linenos: :dedent: 4 some ruby code ``` -------------------------------- ### Set up environment with uv Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/internals/contributing.md Set up the development environment using uv sync. ```shell uv sync ``` -------------------------------- ### Install uv with pip Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/internals/contributing.rst Installs uv, the recommended dependency manager for Sphinx development. ```shell python -m pip install -U uv ``` -------------------------------- ### Install uv Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-autosectionlabel-prefix-document/internals/contributing.md Installs uv, the recommended dependency manager for Sphinx development. ```shell python -m pip install -U uv ``` -------------------------------- ### reStructuredText example of a top-level heading with a role Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/changes/7.1.rst Shows a reStructuredText file starting with a role-based heading. This example is used to illustrate a bug fix where such headings rendered improperly when rst_prolog was set. ```rst :mod:`lobster` -- The lobster module ==================================== ... ``` -------------------------------- ### Set up environment with uv sync Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/internals/contributing.rst Sets up the development environment using uv. ```shell uv sync ``` -------------------------------- ### Example Google-style class docstring Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-napoleon-paramtype/usage/extensions/example_google.md Example class with Google-style docstring, including an __init__ method and a public method. ```python class ExampleError(Exception): """Exceptions are documented in the same way as classes. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. """ pass class ExampleClass(object): """Summary of class here. Longer class information.... Longer class information.... Attributes: likes_spam (bool): Indicates if we like SPAM or not. eggs (int): The number of eggs we have. """ def __init__(self, likes_spam=False): """Inits ExampleClass with blah. Args: likes_spam (bool): Indicates if we like SPAM or not. """ self.likes_spam = likes_spam self.eggs = 0 def public_method(self): """Performs operation blah.""" ``` -------------------------------- ### Verify Sphinx installation with sphinx-build --version Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-directive-only/usage/installation.md Run this command after installation to check that Sphinx is available and print its version number. ```console $ sphinx-build --version ``` -------------------------------- ### productionlist directive example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-api-set-translator/usage/restructuredtext/directives.md Example of the `productionlist` directive from the Python Reference Manual. Each production is on a single line with a name, colon, and definition; continuation lines must start with a colon at the same column. Token names in backticks become cross-references to their definitions. ```rst .. productionlist:: try_stmt: try1_stmt | try2_stmt try1_stmt: "try" ":" `suite` : ("except" [`expression` ["," `target`]] ":" `suite`)+ : ["else" ":" `suite`] : ["finally" ":" `suite`] try2_stmt: "try" ":" `suite` : "finally" ":" `suite` ``` -------------------------------- ### Line block example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-autosectionlabel/usage/restructuredtext/basics.md Shows how to preserve line breaks using a line block in reStructuredText. Each line starts with a vertical bar. ```rst | These lines are | broken exactly like in | the source file. ``` -------------------------------- ### Build documentation data with WebSupport Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-autosectionlabel-prefix-document/usage/advanced/websupport/quickstart.md Creates a WebSupport instance with srcdir, builddir, and search='xapian', then calls build() to generate data and static directories. The builddir will contain 'data' and 'static' subdirectories. ```python from sphinxcontrib.websupport import WebSupport support = WebSupport(srcdir='/path/to/rst/sources/', builddir='/path/to/build/outdir', search='xapian') support.build() ``` -------------------------------- ### ExampleClass.__init__ Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-double-inheriting-theme/usage/extensions/example_google.md The __init__ method of ExampleClass, demonstrating how to document constructor parameters. ```APIDOC ## __init__ ### Description Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. ### Parameters - **param1** (str) - Description of `param1`. - **param2** (:obj:`int`, optional) - Description of `param2`. Multiple lines are supported. - **param3** (list(str)) - Description of `param3`. ### Note Do not include the `self` parameter in the ``Args`` section. ``` -------------------------------- ### Add support for a third-party domain with add_linkcode_domain Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/extensions/linkcode.rst Example of a Sphinx extension setup that registers a custom 'php' domain with linkcode using add_linkcode_domain(). ```python from sphinx.ext.linkcode import add_linkcode_domain def setup(app): add_linkcode_domain('php', ['namespace', 'class', 'fullname']) ``` -------------------------------- ### Build HTML documentation with make Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst Uses the Makefile generated by sphinx-quickstart to build HTML docs in the chosen build directory. Running make without an argument lists available targets. ```console $ make html ``` -------------------------------- ### Install dependencies and run tests with pip Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/internals/contributing.rst Installs test dependencies with pip and runs the test suite. ```shell python -m pip install . --group test pytest ``` -------------------------------- ### Run Sphinx commands with Docker Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Use these commands to create a Sphinx project and build HTML documentation inside a Docker container. The first command runs sphinx-quickstart interactively, and the second builds the HTML output. Both mount the host directory /path/to/document to /docs in the container. ```console $ docker run -it --rm -v /path/to/document:/docs sphinxdoc/sphinx sphinx-quickstart ``` ```console $ docker run --rm -v /path/to/document:/docs sphinxdoc/sphinx make html ``` -------------------------------- ### Inheritance diagram configuration examples Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-intersphinx-role/usage/extensions/inheritance.md Configuration examples for inheritance diagrams: graph attributes, node attributes, and alias mapping. ```rst inheritance_graph_attrs = dict(rankdir="LR", size='"6.0, 8.0"', fontsize=14, ratio='compress') ``` ```rst inheritance_node_attrs = dict(shape='ellipse', fontsize=14, height=0.75, color='dodgerblue1', style='filled') ``` ```rst inheritance_alias = {'_pytest.Magic': 'pytest.Magic'} ``` -------------------------------- ### sphinx-build -M html example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/man/sphinx-build.rst Use the -M option first, before other options, to select a builder in make-mode. This example builds HTML with the --fail-on-warning flag. ```default sphinx-build -M html ./source ./build --fail-on-warning ``` -------------------------------- ### Menu selection sequence with :menuselection: role Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-math-duplicate-label/usage/restructuredtext/roles.md Use the :menuselection: role to mark a sequence of menu selections, separating individual selections with -->. The example renders as 'Start ‣ Programs'. ```rst :menuselection:`Start --> Programs` ``` -------------------------------- ### Run Sphinx commands with Docker Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/installation.md Use the sphinxdoc/sphinx Docker image to create a Sphinx project and build HTML documentation. The first command runs sphinx-quickstart interactively, and the second builds the HTML output. ```console $ docker run -it --rm -v /path/to/document:/docs sphinxdoc/sphinx sphinx-quickstart ``` ```console $ docker run --rm -v /path/to/document:/docs sphinxdoc/sphinx make html ``` -------------------------------- ### toctree :numbered: option example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-directive-only/usage/restructuredtext/directives.md Adds section numbers to the toctree entries in HTML output. Section numbering starts at the heading of the first document listed. Sub-toctrees are automatically numbered. ```rst .. toctree:: :numbered: foo bar ``` -------------------------------- ### setup function for recipe extension Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/development/tutorials/adding_domain.md Sphinx extension setup function that registers the RecipeDomain with the application. Returns metadata declaring version 0.1 and parallel read/write safety. ```python def setup(app: Sphinx) -> ExtensionMetadata: app.add_domain(RecipeDomain) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Enable Napoleon and set all configuration options in conf.py Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/extensions/napoleon.rst Example conf.py configuration that enables the sphinx.ext.napoleon extension and sets all Napoleon settings to their default values. This is the starting point for customizing Napoleon behavior. ```python # conf.py # Add any Sphinx extension module names here, as strings extensions = ['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = True napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True napoleon_preprocess_types = False napoleon_type_aliases = None napoleon_attr_annotations = True ``` -------------------------------- ### Example of :any: role usage in function documentation Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-doctest-with-autodoc/usage/referencing.md This example demonstrates how the :any: role can be used to reference a glossary term, a Python module, and a section without explicit role prefixes. ```default .. function:: install() This function installs a `handler` for every signal known by the `signal` module. See the section `about-signals` for more information. ``` -------------------------------- ### RST example: documenting anonymous union with cpp:union Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-environment-record-dependencies/usage/domains/cpp.md Shows how to document an anonymous union inside a class using the cpp:union directive with a name starting with '@'. The '@data' name is rendered as '[anonymous]' and can be used in cross-references. ```rst .. cpp:class:: Data .. cpp:union:: @data .. cpp:var:: int a .. cpp:var:: double b Explicit ref: :cpp:var:`Data::@data::a`. Short-hand ref: :cpp:var:`Data::a`. ``` -------------------------------- ### Directive Implementation Examples Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-build-text/extdev/markupapi.md Code examples for implementing Sphinx directives, including parsing content and switching source input. ```APIDOC ## [Directive] docutils.parsers.rst.Directive ### Description Base class for Sphinx directives. New directives must implement the `run()` method to process arguments, options, and content, returning a list of Docutils/Sphinx nodes. ### Method run() ### Parameters #### Instance Attributes - **name** (string) - The directive name. - **arguments** (list) - The arguments given to the directive. - **options** (dict) - The options given to the directive, mapping option names to validated/converted values. - **content** (ViewList) - The directive content, if given. - **lineno** (int) - The absolute line number on which the directive appeared. - **content_offset** (int) - Internal offset of the directive content. - **block_text** (string) - The string containing the entire directive. - **state** - The state controlling the parsing. - **state_machine** - The state machine controlling the parsing. ### Return Value Returns a list of Docutils/Sphinx nodes to be inserted into the document tree. ``` ```APIDOC ## [Directive] SphinxDirective.parse_content_to_nodes() ### Description Parses all the directive's content as reStructuredText markup and returns the parsed Docutils nodes in a list. ### Method parse_content_to_nodes() ### Return Value Returns a list of parsed Docutils nodes. ``` ```APIDOC ## [Directive] SphinxDirective.parse_text_to_nodes() ### Description Parses the given text string as reStructuredText markup and returns the parsed Docutils nodes in a list. ### Method parse_text_to_nodes(text) ### Parameters - **text** (string) - The text to parse. ### Return Value Returns a list of parsed Docutils nodes. ``` ```APIDOC ## [Directive] sphinx.util.nodes.nested_parse_with_titles() ### Description Parses content allowing titles in the parsed content. Used prior to Sphinx 7.4. ### Method nested_parse_with_titles(state, result, container, content_offset) ### Parameters - **state** - The state controlling the parsing. - **result** - The content to parse. - **container** - The container element to hold parsed nodes. - **content_offset** (int) - The content offset. ### Return Value Populates the container with parsed nodes. ``` ```APIDOC ## [Directive] sphinx.util.docutils.switch_source_input() ### Description Context manager that changes the source (input) file during parsing content in a directive. Useful for parsing mixed content. ### Method switch_source_input(state, source) ### Parameters - **state** - The state controlling the parsing. - **source** - The new source input. ### Usage ```python from sphinx.util.docutils import switch_source_input from sphinx.util.parsing import nested_parse_to_nodes with switch_source_input(self.state, self.result): parsed = nested_parse_to_nodes(self.state, self.result) ``` ``` -------------------------------- ### Directory structure for custom extension example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-domain-c-intersphinx/usage/configuration.md Shows the directory structure for the custom extension example above: conf.py at the project root and the extension in a sphinxext subdirectory. ```none <project directory>/ ├── conf.py └── sphinxext/ └── extname.py ``` -------------------------------- ### code-block directive with caption and indented content Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-copyright-multiline/usage/restructuredtext/basics.md Demonstrates that the option line fixes the content indent to three spaces, so the content line starts with four spaces. This is the first of two contrasting examples showing whitespace sensitivity. ```rst .. code-block:: :caption: A cool example The output of this line starts with four spaces. ``` -------------------------------- ### Use :glob: option in toctree Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/restructuredtext/directives.md Enables glob wildcard matching in toctree entries. Entries are matched against available documents and inserted alphabetically. The example includes all documents starting with 'intro', all files in 'recipe/', and all remaining documents except the one containing the directive. ```rst .. toctree:: :glob: intro* recipe/* * ``` -------------------------------- ### my_package.example_function(a: str) → str Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-domain-cpp-intersphinx/generated/my_package.md An example function that takes a string and returns a string. ```APIDOC ## my_package.example_function(a: str) → str ### Description An example function. ### Signature `my_package.example_function(a: str) → str` ### Parameters - **a** (str) - Required - Input string. ### Returns - **str** - The result string. ``` -------------------------------- ### Build EPUB documentation with make epub Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/first-steps.rst Build your documentation in EPUB format. Run from the docs directory; output files appear under docs/build/epub/. ```console (.venv) $ make epub ``` -------------------------------- ### Example class with properties and methods Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-environment-record-dependencies/usage/extensions/example_numpy.md Shows a class with a docstring, an __init__ method with its own docstring, properties, and a regular method. Demonstrates documenting attributes inline and in the class docstring. ```python class ExampleClass: """The summary line for a class docstring should fit on one line. If the class has public attributes, they may be documented here in an ``Attributes`` section and follow the same formatting as a function's ``Args`` section. Alternatively, attributes may be documented inline with the attribute's declaration (see __init__ method below). Properties created with the ``@property`` decorator should be documented in the property's getter method. Attributes ---------- attr1 : str Description of `attr1`. attr2 : :obj:`int`, optional Description of `attr2`. """ def __init__(self, param1, param2, param3): """Example of docstring on the __init__ method. The __init__ method may be documented in either the class level docstring, or as a docstring on the __init__ method itself. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it. Note ---- Do not include the `self` parameter in the ``Parameters`` section. Parameters ---------- param1 : str Description of `param1`. param2 : list(str) Description of `param2`. Multiple lines are supported. param3 : :obj:`int`, optional Description of `param3`. """ self.attr1 = param1 self.attr2 = param2 self.attr3 = param3 #: Doc comment *inline* with attribute #: list(str): Doc comment *before* attribute, with type specified self.attr4 = ['attr4'] self.attr5 = None """str: Docstring *after* attribute, with type specified.""" @property def readonly_property(self): """str: Properties should be documented in their getter method.""" return 'readonly_property' @property def readwrite_property(self): """list(str): Properties with both a getter and setter should only be documented in their getter method. If the setter method contains notable behavior, it should be mentioned here. """ return ['readwrite_property'] @readwrite_property.setter def readwrite_property(self, value): _ = value def example_method(self, param1, param2): """Class methods are similar to regular functions. Note ---- Do not include the `self` parameter in the ``Parameters`` section. Parameters ---------- param1 The first parameter. param2 The second parameter. Returns ------- bool True if successful, False otherwise. """ return True ``` -------------------------------- ### Install Sphinx on Windows with Chocolatey Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-api-set-translator/usage/installation.md Install Sphinx on Windows using Chocolatey. Requires Chocolatey to be installed beforehand. ```console $ choco install sphinx ``` -------------------------------- ### Configure \sphinxboxsetup and define \sphinxkeyboard with \sphinxbox Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/latex.rst Shows how to set global defaults with \sphinxboxsetup and define a custom command that uses \sphinxbox with extra options. The preamble is assigned to the 'preamble' key in latex_elements. ```latex latex_elements = { 'preamble': r''' % modify globally the defaults \sphinxboxsetup{border-width=2pt,% border-radius=4pt,% background-TeXcolor=yellow!20} % configure some styling element with some extra specific options: \protected\def\sphinxkeyboard#1{\sphinxbox[border-TeXcolor=green]{\sphinxcode{#1}}} ''', } ``` -------------------------------- ### Install Sphinx on RHEL/CentOS with yum Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-api-set-translator/usage/installation.md Install Sphinx on RHEL/CentOS using yum. Installs Python if it is not already present. ```console $ yum install python-sphinx ``` -------------------------------- ### LaTeX color options example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-autosectionlabel/latex.md Shows the syntax for setting colors in LaTeX options, using either the \definecolor syntax or the \colorlet syntax. The example uses div.warning_border-TeXcolor and div.error_background-TeXcolor as placeholders. ```default ...<other options> div.warning_border-TeXcolor={rgb}{1,0,0},% \definecolor syntax div.error_background-TeXcolor=red!10,% \colorlet syntax ...<other options> ``` -------------------------------- ### Run live documentation server with sphinx-autobuild Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/internals/contributing.rst Starts a live documentation server that rebuilds and reloads the browser whenever changes are made. Requires sphinx-autobuild. ```shell sphinx-autobuild ./doc ./build/sphinx/ ``` -------------------------------- ### Register theme with add_html_theme() in setup() Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-api-set-translator/development/html_themes/index.md Python setup() function that registers the theme using app.add_html_theme(). The theme path is the directory containing the package. Call this function multiple times if the package contains multiple themes. ```python # your_theme_package.py from pathlib import Path def setup(app): app.add_html_theme('name_of_theme', Path(__file__).resolve().parent) ``` -------------------------------- ### Install Sphinx on Windows with Chocolatey Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Installs Sphinx on Windows using Chocolatey. Requires Chocolatey to be installed first. ```console $ choco install sphinx ``` -------------------------------- ### Info URI scheme example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/faq.rst Example of the `info` URI scheme used to create links to external Info files, as mentioned in the notes for creating Texinfo files. ```default info:Texinfo#makeinfo_options ``` -------------------------------- ### Build HTML with make html Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-add_enumerable_node/usage/quickstart.md Builds HTML documentation using the Makefile created by sphinx-quickstart. The build output goes to the chosen build directory. Running make without an argument lists available targets. ```console $ make html ``` -------------------------------- ### my_package.example_function(a: str) → str Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-add_enumerable_node/generated/my_package.md An example function that takes a string argument and returns a string. ```APIDOC ## my_package.example_function(a: str) → str ### Description An example function. ### Parameters - **a** (str) - Required - The input string. ### Returns - **str** - The result string. ``` -------------------------------- ### Install Sphinx on RHEL/CentOS with yum Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Installs Sphinx on RHEL/CentOS using yum. If Python is not already present, this will install it as well. ```console $ yum install python-sphinx ``` -------------------------------- ### Expected output for helloworld RST example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-domain-c-intersphinx/development/tutorials/extending_syntax.md Expected output generated from the preceding RST example, showing the rendered text for the hello directive and the :hello: role. ```text Some intro text here... Hello world! Some text with a hello world! role. ``` -------------------------------- ### Install Sphinx on Debian/Ubuntu with apt-get Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Installs Sphinx on Debian/Ubuntu using apt-get. If Python is not already present, this will install it as well. ```console $ apt-get install python3-sphinx ``` -------------------------------- ### ExampleClass.example_method(param1, param2) Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-autosummary-filename-map/usage/extensions/example_numpy.md Documentation for the example_method method of ExampleClass. ```APIDOC ## ExampleClass.example_method(param1, param2) ### Description Class method that returns a boolean indicating success. ### Parameters - **param1** - Required - The first parameter. - **param2** - Required - The second parameter. ### Returns - bool - True if successful, False otherwise. ``` -------------------------------- ### Install Sphinx with pip Source: https://github.com/sphinx-doc/sphinx/blob/master/README.rst Installs the latest version of Sphinx from the Python Package Index. Requires a working installation of Python and pip. ```shell pip install -U sphinx ``` -------------------------------- ### Build and preview Sphinx documentation Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-intersphinx-role/internals/contributing.md Use these commands to build the documentation as HTML. The first generates static HTML and fails on warnings, and the second provides a live preview that reloads on changes. Requires a working Sphinx environment. ```shell sphinx-build -M html ./doc ./build/sphinx --fail-on-warning ``` ```shell sphinx-autobuild ./doc ./build/sphinx/ ``` -------------------------------- ### Install Python package theme via pip Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-need-escaped/usage/theming.md Command to install a Python package distributed theme. After installation, the theme can be used like any other. ```console pip install sphinxjp.themes.dotted ``` -------------------------------- ### setup function implementation Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-build-html-theme-having-multiple-stylesheets/development/tutorials/extending_syntax.md Registers the custom role and directive with Sphinx and returns extension metadata. ```python def setup(app: Sphinx) -> ExtensionMetadata: app.add_role('hello', HelloRole()) app.add_directive('hello', HelloDirective) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Initialize Transifex config with tx init Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/advanced/intl.md Initializes the Transifex project configuration, creating .tx/config in the current directory. The output confirms successful creation of the file. ```console $ cd /your/document/root $ tx init Successful creation of '.tx/config' file ``` -------------------------------- ### Install directly from Git with pip Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-changes/usage/installation.md Installs Sphinx directly from the Git repository using pip's git+https URL. This is an alternative to cloning and installing locally. ```console $ pip install git+https://github.com/sphinx-doc/sphinx ``` -------------------------------- ### ExampleException.__init__ Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-autosummary-import_cycle/usage/extensions/example_google.md Initializes an ExampleException instance with a message and optional error code. ```APIDOC ## ExampleException.__init__ ### Description Initializes an ExampleException instance with a human-readable message and an optional error code. ### Method Constructor ### Parameters #### Args - **msg** (str) - Required - Human readable string describing the exception. - **code** (:obj:`int`, optional) - Optional - Error code. ### Attributes - **msg** (str) - Human readable string describing the exception. - **code** (int) - Exception error code. ``` -------------------------------- ### Create usage.rst with sections and a code-block directive Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/narrative-documentation.rst Shows the initial content for docs/source/usage.rst, including two section headers and a code-block directive for console output. The '---' heading style makes 'Installation' a subsection of 'Usage'. ```rst Usage ===== Installation ------------ To use Lumache, first install it using pip: .. code-block:: console (.venv) $ pip install lumache ``` -------------------------------- ### Build HTML documentation with make html Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/first-steps.rst Build your HTML documentation using the convenience script. Run from the docs directory after modifying index.rst. ```console (.venv) $ cd docs (.venv) $ make html ``` -------------------------------- ### Install from source via Git clone Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-changes/usage/installation.md Clones the Sphinx repository and installs it locally with pip. This method is for users who want to install from a local clone of the Git repository. ```console $ git clone https://github.com/sphinx-doc/sphinx $ cd sphinx $ pip install . ``` -------------------------------- ### RecipeDomain class and setup function for Sphinx extension Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-double-inheriting-theme/development/tutorials/adding_domain.md Defines the RecipeDomain class and the setup function for a Sphinx extension. The domain registers directives, roles, and indices via class attributes, and the setup function only calls app.add_domain(RecipeDomain) because the rest is already registered. The domain uses initial_data to store recipes and ingredients, and implements resolve_xref to resolve cross-references. ```python class RecipeDomain(Domain): name = 'recipe' label = 'Recipe Sample' roles = { 'ref': XRefRole(), } directives = { 'recipe': RecipeDirective, } indices = { RecipeIndex, IngredientIndex, } initial_data = { 'recipes': [], # object list 'recipe_ingredients': {}, # name -> object } data_version = 0 def get_full_qualified_name(self, node): return f'recipe.{node.arguments[0]}' def get_objects(self): yield from self.data['recipes'] def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode): match = [ (docname, anchor) for name, sig, typ, docname, anchor, prio in self.get_objects() if sig == target ] if len(match) > 0: todocname = match[0][0] targ = match[0][1] return make_refnode(builder, fromdocname, todocname, targ, contnode, targ) else: print('Awww, found nothing') return None def add_recipe(self, signature, ingredients): """Add a new recipe to the domain.""" name = f'recipe.{signature}' anchor = f'recipe-{signature}' self.data['recipe_ingredients'][name] = ingredients # name, dispname, type, docname, anchor, priority self.data['recipes'].append(( name, signature, 'Recipe', self.env.current_document.docname, anchor, 0, )) ``` ```python def setup(app: Sphinx) -> ExtensionMetadata: app.add_domain(RecipeDomain) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Install Sphinx directly from Git Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-add_enumerable_node/usage/installation.md Installs Sphinx directly from the Git repository using pip's git+ URL syntax. This is an alternative to cloning and installing locally. ```console $ pip install git+https://github.com/sphinx-doc/sphinx ``` -------------------------------- ### Run sphinx-autobuild for live preview Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-add_enumerable_node/usage/quickstart.md Builds a live version of the documentation that previews in the browser, detects changes, and reloads the page on edits. Requires sphinx-autobuild. ```console $ sphinx-autobuild source-dir output-dir ``` -------------------------------- ### pyversion option example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-directive-only/usage/extensions/doctest.md Shows how to specify a required Python version for a doctest example using the :pyversion: option. The example will only be tested for Python versions greater than 3.14. ```rst .. doctest:: :pyversion: > 3.14 ``` -------------------------------- ### add_recipe method and setup function Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-double-inheriting-theme/development/tutorials/adding_domain.md Defines the add_recipe method that stores recipe ingredients and adds a recipe entry to the domain data. Also defines the setup function that registers the RecipeDomain and returns extension metadata. ```python def add_recipe(self, signature, ingredients): """Add a new recipe to the domain.""" name = f'recipe.{signature}' anchor = f'recipe-{signature}' self.data['recipe_ingredients'][name] = ingredients # name, dispname, type, docname, anchor, priority self.data['recipes'].append(( name, signature, 'Recipe', self.env.current_document.docname, anchor, 0, )) def setup(app: Sphinx) -> ExtensionMetadata: app.add_domain(RecipeDomain) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Install Sphinx dependencies via pyproject.toml with pip install . --group docs Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-directive-only/usage/installation.md For Python packages, install documentation dependencies defined in pyproject.toml using the docs group. ```console $ pip install . --group docs ``` -------------------------------- ### Install documentation dependencies with pip install . --group docs Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Installs the documentation dependencies for a Python package using the 'docs' optional dependency group defined in pyproject.toml. ```console $ pip install . --group docs ``` -------------------------------- ### Instantiate WebSupport with custom storage backend Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/storagebackends.rst Create a WebSupport instance with a custom storage backend by passing the storage keyword argument. The MyStorage class must be a subclass of StorageBackend. ```default support = WebSupport(srcdir=srcdir, builddir=builddir, storage=MyStorage()) ``` -------------------------------- ### Initialize tx config file Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/intl.rst Initializes the tx project configuration file .tx/config in the current directory. The output confirms successful creation. ```console $ cd /your/document/root $ tx init Successful creation of '.tx/config' file ``` -------------------------------- ### Run sphinx-build with -M html Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-add_enumerable_node/usage/quickstart.md Starts a first build of the documentation. The -M option selects the builder; here it builds HTML files. sourcedir is the source directory and outputdir is where the built documentation is placed. ```console $ sphinx-build -M html sourcedir outputdir ``` -------------------------------- ### Show generated docs directory structure Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Displays the directory layout created by sphinx-quickstart, including build, make.bat, Makefile, and source subdirectories. ```text docs ├── build ├── make.bat ├── Makefile └── source ├── conf.py ├── index.rst ├── _static └── _templates ``` -------------------------------- ### my_package.example_function(a: str) -> str Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-copyright-multiline/generated/my_package.md Documentation for the example_function function in the my_package module. ```APIDOC ## my_package.example_function(a: str) -> str ### Description An example function. ### Signature `my_package.example_function(a: str) -> str` ### Parameters - **a** (str) - Required - Description not provided. ### Returns - **str** - Description not provided. ``` -------------------------------- ### inheritance_node_attrs example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/extensions/inheritance.md Example configuration for inheritance_node_attrs, a dictionary of graphviz node attributes. ```rst inheritance_node_attrs = dict(shape='ellipse', fontsize=14, height=0.75, color='dodgerblue1', style='filled') ``` -------------------------------- ### inheritance_graph_attrs example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/usage/extensions/inheritance.md Example configuration for inheritance_graph_attrs, a dictionary of graphviz graph attributes. ```rst inheritance_graph_attrs = dict(rankdir="LR", size='"6.0, 8.0"', fontsize=14, ratio='compress') ``` -------------------------------- ### Install Sphinx from PyPI with pip Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Installs or upgrades Sphinx from PyPI using pip. ```console $ pip install -U sphinx ``` -------------------------------- ### my_package.example_function(a: str) → str Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/js/roots/titles/generated/my_package.md Documentation for the example_function function in the my_package module. ```APIDOC ## my_package.example_function(a: str) → str ### Description An example function. ### Signature `my_package.example_function(a: str) → str` ### Parameters - **a** (str) - Required - The input string. ### Returns - **str** - The result string. ```