### Initialize Sphinx Project with Quickstart Command Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This console command executes `sphinx-quickstart`, an interactive script that sets up a new Sphinx project. It creates the source directory and a default `conf.py` configuration file, streamlining the initial setup process for documentation. ```console $ sphinx-quickstart ``` -------------------------------- ### Set Up Python Virtual Environment and Install Sphinx Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Provides shell commands to set up a Python virtual environment (`.venv`), activate it, and install the Sphinx documentation generator using `pip`. This ensures a clean and isolated development environment for the project. ```console $ python -m venv .venv $ source .venv/bin/activate (.venv) $ python -m pip install sphinx ``` -------------------------------- ### Run Live Preview with sphinx-autobuild Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This command starts a live preview server for Sphinx documentation. It automatically detects changes in source files and reloads the page in the browser, requiring a source directory and an output directory. ```console $ sphinx-autobuild source-dir output-dir ``` -------------------------------- ### Build HTML Documentation using Makefile Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This command leverages the `Makefile` generated by `sphinx-quickstart` to build HTML documentation. It simplifies the build process by abstracting the `sphinx-build` command. ```console $ make html ``` -------------------------------- ### Verify Sphinx Installation Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Executes `sphinx-build --version` within the activated virtual environment to confirm that Sphinx has been successfully installed and is accessible from the command line, displaying its version number. ```console (.venv) $ sphinx-build --version ``` -------------------------------- ### Build HTML Documentation with sphinx-build Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This command initiates a Sphinx build process. It uses the `-M` option to select the HTML builder, taking a source directory and an output directory as arguments to generate the documentation. ```console $ sphinx-build -M html sourcedir outputdir ``` -------------------------------- ### Sphinx Project Directory Structure Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Illustrates the standard directory and file structure created by `sphinx-quickstart` for a Sphinx project. It includes `build/`, `make.bat`, `Makefile`, and the `source/` directory containing `conf.py`, `index.rst`, `_static/`, and `_templates/`. ```text docs ├── build ├── make.bat ├── Makefile └── source ├── conf.py ├── index.rst ├── _static └── _templates ``` -------------------------------- ### Generate Sphinx Documentation Layout with sphinx-quickstart Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Runs the `sphinx-quickstart` command to interactively generate the basic directory and configuration layout for a new Sphinx project. Users are prompted to provide project details like name, author, and language, creating a `docs` folder with essential files. ```console (.venv) $ sphinx-quickstart docs ``` -------------------------------- ### Generate PDF Documents with make latexpdf Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This command uses the `Makefile` to invoke the LaTeX builder, which then runs the pdfTeX toolchain to generate PDF documents from the Sphinx source. ```console make latexpdf ``` -------------------------------- ### Create README.rst for Project Description Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Defines the initial `README.rst` file for a Sphinx project, introducing 'Lumache' as a Python library for recipe creation. This file serves as the project's root documentation. ```rst Lumache ======= **Lumache** (/lu'make/) is a Python library for cooks and food lovers that creates recipes mixing random ingredients. ``` -------------------------------- ### Defining EPUB Guide Metadata in Sphinx Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/configuration.rst This example shows how to set the `epub_guide` configuration, which provides metadata for the EPUB's guide element in `content.opf`. It expects a sequence of tuples, each containing a type, URI, and title. This allows for explicit definition of guide entries, overriding default 'cover' and 'toc' types if necessary, as per OPF documentation. ```Python epub_guide = ( ('cover', 'cover.html', 'Cover Page'), ) ``` -------------------------------- ### Build Sphinx Documentation to HTML Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/getting-started.rst Executes the `sphinx-build` command to compile the reStructuredText source files into HTML documentation. The command specifies the source and build directories, generating the final web-ready documentation that can be viewed in a browser. ```console (.venv) $ sphinx-build -M html docs/source/ docs/build/ ``` -------------------------------- ### Handle Search Queries in Flask with WebSupport Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Illustrates a Flask route for processing search requests. It retrieves the user's query from GET parameters, uses the WebSupport.get_search_results method to fetch relevant documents, and renders them using a common document template. ```Python @app.route('/search') def search(): q = request.args.get('q') document = support.get_search_results(q) return render_template('doc.html', document=document) ``` -------------------------------- ### Install Sphinx from Git Repository Clone Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Steps to install Sphinx by cloning its Git repository and then installing it locally using pip. This method allows for direct installation from the source code. ```console $ git clone https://github.com/sphinx-doc/sphinx $ cd sphinx $ pip install . ``` -------------------------------- ### Jinja2 Template for Sphinx Document Integration Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Provides an example of a Jinja2 template (`html+jinja`) demonstrating how to integrate the dictionary returned by `get_document` into an HTML layout. It maps document components like title, body, CSS, and scripts to corresponding template blocks, allowing for flexible rendering within an existing templating system. ```HTML+Jinja {%- extends "layout.html" %} {%- block title %} {{ document.title }} {%- endblock %} {% block css %} {{ super() }} {{ document.css|safe }} {% endblock %} {%- block script %} {{ super() }} {{ document.script|safe }} {%- endblock %} {%- block relbar %} {{ document.relbar|safe }} {%- endblock %} {%- block body %} {{ document.body|safe }} {%- endblock %} {%- block sidebar %} {{ document.sidebar|safe }} {%- endblock %} ``` -------------------------------- ### Define Sphinx Usage Page Content with Installation Instructions Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/narrative-documentation.rst This reStructuredText snippet outlines the content for a `usage.rst` file, including a main 'Usage' section, an 'Installation' subsection, and an embedded console code block demonstrating how to install a package using pip. ```rst Usage ===== Installation ------------ To use Lumache, first install it using pip: .. code-block:: console (.venv) $ pip install lumache ``` -------------------------------- ### Install Sphinx Development Release via pip Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Instructions to install the latest pre-release (development) version of Sphinx from PyPI using pip. This is generally not recommended for production but useful for testing new features or bug fixes. ```console $ pip install -U --pre sphinx ``` -------------------------------- ### Document Python Function with py:function Directive Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This reStructuredText snippet demonstrates how to document a Python function using the `py:function` directive. It includes the function signature and its descriptive content, which Sphinx renders as API documentation. ```rst .. py:function:: enumerate(sequence[, start=0]) Return an iterator that yields tuples of an index and an item of the *sequence*. (And so on.) ``` -------------------------------- ### Flask View for Authenticated Sphinx Document Access Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Presents a Flask function example (`doc`) that retrieves a Sphinx document, demonstrating how to pass authenticated user details (username and moderator status) to `support.get_document()`. It includes error handling for `DocumentNotFoundError` and shows how to integrate with a Flask application's routing. ```Python from sphinxcontrib.websupport.errors import * @app.route('/') def doc(docname): username = g.user.name if g.user else '' moderator = g.user.moderator if g.user else False try: document = support.get_document(docname, username, moderator) except DocumentNotFoundError: abort(404) return render_template('doc.html', document=document) ``` -------------------------------- ### Install Sphinx Directly from Git URL via pip Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Alternative method to install Sphinx directly from its Git repository URL using pip. This command fetches and installs the project without requiring a manual clone. ```console $ pip install git+https://github.com/sphinx-doc/sphinx ``` -------------------------------- ### Activate Sphinx Extension from Another Extension (Python) Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/howtos/setup_extension.rst This Python code demonstrates how to activate another Sphinx extension, `sphinx.ext.autodoc`, from within your own extension's `setup` function. It uses the `app.setup_extension` method to ensure the dependency is available at runtime. Remember to include the dependent extension in your installation requirements. ```python def setup(app): app.setup_extension('sphinx.ext.autodoc') ``` -------------------------------- ### Install Sphinx using pip from PyPI Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst The preferred method for installing Sphinx from PyPI is using pip. The -U flag ensures that Sphinx is upgraded if already installed. ```Shell $ pip install -U sphinx ``` -------------------------------- ### Example theme.toml Configuration Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/html_themes/index.rst An example `theme.toml` file demonstrating the structure and common settings for a Sphinx HTML theme, including inheritance, stylesheets, sidebars, and Pygments style definitions, along with custom options. ```toml [theme] inherit = "basic" stylesheets = [ "main-CSS-stylesheet.css", ] sidebars = [ "localtoc.html", "relations.html", "sourcelink.html", "searchbox.html", ] # Style names from https://pygments.org/styles/ pygments_style = { default = "style_name", dark = "dark_style" } [options] variable = "default value" ``` -------------------------------- ### Configuring `conf.py` for Sphinx Doctests and Code Import Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/describing-code.rst This snippet provides the initial configuration for the `conf.py` file, which is essential for Sphinx to import the project's Python code. This setup is a prerequisite for features like doctests, allowing Sphinx to execute and verify code examples during documentation build. ```python ``` -------------------------------- ### Retrieve Comments for a Node via Flask API Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Presents a Flask GET route designed to fetch comments associated with a specific documentation node. It retrieves the node_id from query arguments and uses WebSupport.get_data to retrieve comment data, returning it as a JSON response. ```Python @app.route('/docs/get_comments') def get_comments(): username = g.user.name if g.user else None moderator = g.user.moderator if g.user else False node_id = request.args.get('node', '') data = support.get_data(node_id, username, moderator) return jsonify(**data) ``` -------------------------------- ### Verify Sphinx Installation Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst After installing Sphinx, run this command in your terminal to check if it's correctly installed and to display its version number. ```Shell $ sphinx-build --version ``` -------------------------------- ### Setting Up a Python Virtual Environment for Sphinx Development (Shell) Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/internals/contributing.rst This snippet shows how to create and activate a Python virtual environment, and then install Sphinx in editable mode using pip. This setup is crucial for running sphinx-build locally or executing unit tests without tox, ensuring project dependencies are isolated. ```shell virtualenv ~/.venv . ~/.venv/bin/activate pip install -e . ``` -------------------------------- ### Python Sphinx Extension Setup Function for Autodoc Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/tutorials/autodoc_ext.rst Defines the `setup` function, the entry point for a Sphinx extension. It registers the custom `IntEnumDocumenter` with Sphinx's autodoc system and declares a dependency on the `sphinx.ext.autodoc` extension, ensuring autodoc is loaded. ```python def setup(app): app.setup_extension('sphinx.ext.autodoc') app.add_autodocumenter(IntEnumDocumenter) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True, } ``` -------------------------------- ### Configure Intersphinx Mapping for Python Documentation Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This Python snippet demonstrates how to set up the `intersphinx_mapping` configuration variable in Sphinx's `conf.py` file. It maps the logical name 'python' to the official Python 3 documentation URL, enabling cross-references to Python library functions within your Sphinx project. ```Python intersphinx_mapping = {'python': ('https://docs.python.org/3', None)} ``` -------------------------------- ### Defining a Sphinx Extension Module Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/extdev/index.rst A Sphinx extension is a Python module that contains a `setup()` function. This function is the entry point for the extension, receiving the `app` object (an instance of `sphinx.application.Sphinx`) to register new builders, roles, directives, or hook into build events. The `setup()` function should return a dictionary with metadata like version and parallel safety flags. ```Python # your_extension_module.py from sphinx.application import Sphinx def setup(app: Sphinx): # Register builders, roles, directives, or event handlers here # app.add_builder(...) # app.add_role(...) # app.connect(...) return { 'version': '0.1', 'parallel_read_safe': True, 'parallel_write_safe': True } ``` -------------------------------- ### Sphinx Extension Folder Structure Example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/tutorials/adding_domain.rst An example of the recommended folder structure for a Sphinx project that includes a custom extension. The `recipe.py` extension file is placed within the `_ext` subdirectory under `source`, alongside `conf.py` and `index.rst`. ```text └── source    ├── _ext │   └── recipe.py    ├── conf.py    └── index.rst ``` -------------------------------- ### Example theme.conf Configuration (INI Format) Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/html_themes/index.rst An example `theme.conf` file in INI format, showing the configuration structure for older Sphinx HTML themes, including inheritance, stylesheet, Pygments style, and sidebars. ```ini [theme] inherit = base theme stylesheet = main CSS name pygments_style = stylename sidebars = localtoc.html, relations.html, sourcelink.html, searchbox.html [options] variable = default value ``` -------------------------------- ### Install Sphinx HTML Theme Python Package Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/theming.rst Provides a console command to install a Sphinx HTML theme distributed as a Python package using pip. ```console # installing theme package $ pip install sphinxjp.themes.dotted ``` -------------------------------- ### Example Info URI for External Texinfo Links Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/faq.rst This example demonstrates the `info` URI scheme used to create links to external Info files. It specifies the target Info file (`Texinfo`) and a specific node within that file (`makeinfo_options`), allowing for precise navigation to external documentation. ```Text info:Texinfo#makeinfo_options ``` -------------------------------- ### Sphinx Application Object: Extension Setup Methods Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/extdev/appapi.rst Details the `Sphinx` application object's public API, specifically methods intended for use within an extension's `setup()` function to register various components like builders, directives, roles, and more. These methods facilitate extending Sphinx's core functionality. ```APIDOC class Sphinx: setup_extension() require_sphinx() connect() disconnect() add_builder() add_config_value() add_event() set_translator() add_node() add_enumerable_node() add_directive() add_role() add_generic_role() add_domain() add_directive_to_domain() add_role_to_domain() add_index_to_domain() add_object_type() add_crossref_type() add_transform() add_post_transform() add_js_file() add_css_file() add_latex_package() add_lexer() add_autodocumenter() add_autodoc_attrgetter() add_search_language() add_source_suffix() add_source_parser() add_env_collector() add_html_theme() add_html_math_renderer() add_message_catalog() is_parallel_allowed() set_html_assets_policy() ``` -------------------------------- ### Install Sphinx on Windows using Chocolatey Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst On Windows, Sphinx can be installed using the Chocolatey package manager. Ensure Chocolatey is installed on your system before running this command. ```Windows Shell $ choco install sphinx ``` -------------------------------- ### sphinx-quickstart Command Line Options Reference Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/man/sphinx-quickstart.rst Detailed reference for all available command-line options of the sphinx-quickstart tool, including their purpose, required parameters, and versioning notes. ```APIDOC sphinx-quickstart Command Line Tool: Synopsis: sphinx-quickstart Description: An interactive tool that generates a complete documentation directory and sample Makefile. Options: General Options: -q, --quiet: Description: Quiet mode that skips the interactive wizard for specifying options. This option requires -p, -a and -v options. -h, --help, --version: Description: Display usage summary or Sphinx version. Structure Options: --sep: Description: If specified, separate source and build directories. --no-sep: Description: If specified, create build directory under source directory. --dot=DOT: Description: Inside the root directory, two more directories will be created; "_templates" for custom HTML templates and "_static" for custom stylesheets and other static files. You can enter another prefix (such as ".") to replace the underscore. Project Basic Options: -p PROJECT, --project=PROJECT: Description: Project name will be set. (see :confval:`project`). -a AUTHOR, --author=AUTHOR: Description: Author names. (see :confval:`copyright`). -v VERSION: Description: Version of project. (see :confval:`version`). -r RELEASE, --release=RELEASE: Description: Release of project. (see :confval:`release`). -l LANGUAGE, --language=LANGUAGE: Description: Document language. (see :confval:`language`). --suffix=SUFFIX: Description: Source file suffix. (see :confval:`source_suffix`). --master=MASTER: Description: Master document name. (see :confval:`root_doc`). Extension Options: --ext-autodoc: Description: Enable :py:mod:`sphinx.ext.autodoc` extension. --ext-doctest: Description: Enable `sphinx.ext.doctest` extension. --ext-intersphinx: Description: Enable `sphinx.ext.intersphinx` extension. --ext-todo: Description: Enable `sphinx.ext.todo` extension. --ext-coverage: Description: Enable `sphinx.ext.coverage` extension. --ext-imgmath: Description: Enable `sphinx.ext.imgmath` extension. --ext-mathjax: Description: Enable `sphinx.ext.mathjax` extension. --ext-ifconfig: Description: Enable `sphinx.ext.ifconfig` extension. --ext-viewcode: Description: Enable `sphinx.ext.viewcode` extension. --ext-githubpages: Description: Enable `sphinx.ext.githubpages` extension. --extensions=EXTENSIONS: Description: Enable arbitrary extensions. Makefile and Batchfile Creation Options: --use-make-mode (-m), --no-use-make-mode (-M): Description: Makefile/make.bat uses (or doesn't use) make-mode. Default is use, which generates a more concise Makefile/make.bat. Notes: Version changed: 1.5 - make-mode is default. Version changed: 7.3 - Support for disabling the make-mode will be removed in Sphinx 8. Version removed: 8.0 - The !--no-use-make-mode option. The !--use-make-mode now has no effect. --makefile, --no-makefile: Description: Create (or not create) makefile. --batchfile, --no-batchfile: Description: Create (or not create) batchfile. Project Templating Options: -t, --templatedir=TEMPLATEDIR: Description: Template directory for template files. You can modify the templates of sphinx project files generated by quickstart. Following Jinja2 template files are allowed: root_doc.rst.jinja, conf.py.jinja, Makefile.jinja, Makefile.new.jinja, make.bat.jinja, make.bat.new.jinja. In detail, please refer the system template files Sphinx provides. (sphinx/templates/quickstart) Notes: Version added: 1.5 - Project templating options for sphinx-quickstart. -d NAME=VALUE: Description: Define a template variable. ``` -------------------------------- ### reStructuredText URL and Anchor Examples Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-linkcheck-anchors-ignore-for-url/index.rst Demonstrates various URL and anchor configurations in reStructuredText, illustrating how Sphinx processes them for validity and link resolution. These examples cover valid, ignored, and invalid URLs, as well as different types of anchors. ```reStructuredText `Example valid url, no anchor `_ ``` ```reStructuredText `Example valid url, valid anchor `_ ``` ```reStructuredText `Example valid url, valid quotable anchor `_ ``` ```reStructuredText `Example valid url, invalid anchor `_ ``` ```reStructuredText `Example ignored url, no anchor `_ ``` ```reStructuredText `Example ignored url, invalid anchor `_ ``` ```reStructuredText `Example invalid url, no anchor `_ ``` ```reStructuredText `Example invalid url, invalid anchor `_ ``` -------------------------------- ### C Language Example with code-block Directive and Caption Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-intl/literalblock.txt An example of a C program explicitly defined using the `.. code-block:: c` directive, which allows specifying the language and adding a caption for the block. ```c #include int main(int argc, char** argv) { return 0; } ``` -------------------------------- ### Example reStructuredText Top-Level Heading with Role Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/changes/7.1.rst Demonstrates how a top-level heading starting with a reStructuredText role is structured, specifically showing a `:mod:` role followed by a title and an underline. This example highlights a fix where such headings now render properly when `rst_prolog` is set. ```reStructuredText :mod:`lobster` -- The lobster module ==================================== ... ``` -------------------------------- ### API Definition: Python enumerate() Function Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst Formal API documentation for the Python built-in `enumerate()` function, detailing its signature and return value. ```APIDOC Function: enumerate Signature: enumerate(sequence[, start=0]) Description: Return an iterator that yields tuples of an index and an item of the *sequence*. ``` -------------------------------- ### Python 'Hello World' Example (List 1.1) Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-numfig/foo.rst This snippet demonstrates a basic 'hello world' program in Python, as presented in List 1.1 of the documentation. It prints the string 'hello world' to the standard output. ```python print('hello world') ``` -------------------------------- ### Python 'Hello World' Example (List 1.2) Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-numfig/foo.rst This snippet demonstrates a basic 'hello world' program in Python, as presented in List 1.2 of the documentation. It prints the string 'hello world' to the standard output. ```python print('hello world') ``` -------------------------------- ### Python 'Hello World' Example (List 1.3) Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-numfig/foo.rst This snippet demonstrates a basic 'hello world' program in Python, as presented in List 1.3 of the documentation. It prints the string 'hello world' to the standard output. ```python print('hello world') ``` -------------------------------- ### Python 'Hello World' Example (List 1.4) Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-numfig/foo.rst This snippet demonstrates a basic 'hello world' program in Python, as presented in List 1.4 of the documentation. It prints the string 'hello world' to the standard output. ```python print('hello world') ``` -------------------------------- ### Install sphinx-intl Tool Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/intl.rst This command installs the `sphinx-intl` utility using pip. `sphinx-intl` is a helpful tool designed to streamline and manage the translation workflow for Sphinx projects. ```console pip install sphinx-intl ``` -------------------------------- ### WebSupport Class Constructor Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Documentation for the `WebSupport` class constructor, detailing its parameters for both building documentation data and integrating pre-built data into a web application. It clarifies which parameters are required for each use case. ```APIDOC WebSupport(srcdir: str = None, builddir: str = None, datadir: str = None, search: str, staticdir: str = "/static") Purpose: Initializes the WebSupport object. srcdir: (Required for building) Path to reStructuredText sources. builddir: (Required for building) Path where necessary data will be placed. datadir: (Required for integration) Path to the pre-built data directory. search: The search engine to use (e.g., 'xapian'). staticdir: Optional. Path to serve static files from (defaults to "/static"). Note: Either `srcdir` and `builddir` (for building) or `datadir` (for integration) must be provided. ``` -------------------------------- ### Document Python Function with Default Domain Directive Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This reStructuredText snippet shows how to document a Python function when the Python domain is set as the default. The `py:` prefix can be omitted, simplifying the directive to just `function`. ```rst .. function:: enumerate(sequence[, start=0]) ... ``` -------------------------------- ### Create Sphinx Project using Docker Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Demonstrates how to initialize a new Sphinx project within a Docker container. This command mounts a local directory to the container's /docs path and executes `sphinx-quickstart`. ```console $ docker run -it --rm -v /path/to/document:/docs sphinxdoc/sphinx sphinx-quickstart ``` -------------------------------- ### Install Transifex CLI Tool Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/intl.rst Command to download and install the Transifex command-line interface (CLI) tool. This tool is essential for interacting with the Transifex service to fetch and push translation resources. ```console $ curl -o- https://raw.githubusercontent.com/transifex/cli/master/install.sh | bash ``` -------------------------------- ### Cross-reference Python Function with Default Domain Role Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This reStructuredText snippet demonstrates cross-referencing a Python function when the Python domain is the default. The `py:` prefix can be omitted, using just the `func` role to create the link. ```rst A link to :func:`enumerate`. ``` -------------------------------- ### Install Python Package via Pip in Console Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/narrative-documentation.rst This console command demonstrates the standard procedure for installing a Python package, 'lumache', using the `pip` package manager within a virtual environment. ```console (.venv) $ pip install lumache ``` -------------------------------- ### Improve Error Message for Non-Callable setup in conf.py Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/changes/1.2.rst When `setup` in `conf.py` is non-callable, `sphinx-build` now emits a more user-friendly error message instead of an unexpected termination, improving debugging experience. ```APIDOC conf.py: Non-callable `setup` now results in a user-friendly error message. ``` -------------------------------- ### Sphinx Docker Images Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Official Docker images for Sphinx are published on Docker Hub, providing pre-configured environments for standard Sphinx usage and for PDF generation with LaTeX. ```APIDOC Docker Hub Images: - Name: sphinxdoc/sphinx Purpose: Standard Sphinx usage - Name: sphinxdoc/sphinx-latexpdf Purpose: For PDF builds using LaTeX (contains TeXLive packages, image size > 2GB) ``` -------------------------------- ### WebSupport.build Method Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Documentation for the `build` method of the `WebSupport` class. This method processes reStructuredText sources from the `srcdir` and generates all necessary data files and static assets into the `builddir` for web integration. ```APIDOC WebSupport.build() Purpose: Reads reStructuredText sources from `srcdir` and places necessary data in `builddir`. Returns: None ``` -------------------------------- ### Install Furo Third-Party Sphinx HTML Theme Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/more-sphinx-customization.rst This command demonstrates how to install the Furo third-party HTML theme for Sphinx using `pip` within a Python virtual environment. This is a prerequisite step before configuring Sphinx to use the theme. ```console (.venv) $ pip install furo ``` -------------------------------- ### Configure Example Section Rendering in Sphinx Napoleon Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/extensions/napoleon.rst Controls the reStructuredText directive used for 'Example' and 'Examples' sections in Sphinx Napoleon. When `True`, it uses `.. admonition::`, providing a distinct block. When `False`, it uses `.. rubric::`, which is a simple heading. This choice impacts the visual theme. ```text Example ------- This is just a quick example ``` ```rst .. admonition:: Example This is just a quick example ``` ```rst .. rubric:: Example This is just a quick example ``` -------------------------------- ### Define and Call a Basic Python Function Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-reST-code-block/index.rst This snippet illustrates the definition of a simple Python function named 'hello' that takes one argument and prints a greeting. It also shows how to call this function with a string argument. This is a common pattern for introductory code examples. ```Python def hello(name): print("hello", name) hello("Sphinx") ``` -------------------------------- ### Synopsis for sphinx-quickstart Command Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/man/sphinx-quickstart.rst Shows the basic command-line usage for the sphinx-quickstart tool. ```Shell sphinx-quickstart ``` -------------------------------- ### Python Hello World Example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-numfig/baz.rst Demonstrates a basic 'hello world' program in Python using a Sphinx code-block directive. This snippet illustrates how to embed executable code with a caption. ```python print('hello world') ``` -------------------------------- ### Configure WebSupport with a Custom Document Root Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Demonstrates how to initialize the WebSupport object with a custom document root path and define a Flask route to serve documentation from that specific directory. ```Python support = WebSupport(..., docroot='docs') @app.route('/docs/') ``` -------------------------------- ### Example reStructuredText for autosummary Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/man/sphinx-autogen.rst Illustrates an `index.rst` file containing `autosummary` directives with the `:toctree:` option. This configuration guides `sphinx-autogen` in generating documentation stubs for the listed Python modules, given a specific directory structure. ```rst Modules ======= .. autosummary:: :toctree: modules foobar.foo foobar.bar foobar.bar.baz ``` -------------------------------- ### Rendered output of the reStructuredText extension example Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/tutorials/extending_syntax.rst This plain text snippet displays the expected output when the reStructuredText example, utilizing the 'hello' directive and role, is processed by Sphinx. It illustrates how the custom extension transforms the input into rendered content. ```text Some intro text here... Hello world! Some text with a hello world! role. ``` -------------------------------- ### Initialize WebSupport for Document Integration Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Shows how to initialize a `WebSupport` object for integrating pre-built Sphinx documentation into a web application. This initialization uses the `datadir` parameter, pointing to the directory containing the generated data. Only one instance is typically needed per documentation set. ```Python from sphinxcontrib.websupport import WebSupport support = WebSupport(datadir='/path/to/the/data', search='xapian') ``` -------------------------------- ### Passing Options to LaTeX Packages in Sphinx (xcolor example) Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/latex.rst Provides an example of using the `passoptionstopackages` key in `latex_elements` to pass options to a LaTeX package, specifically `svgnames` to the `xcolor` package for extended color names. ```Python latex_elements = { 'passoptionstopackages': r'\PassOptionsToPackage{svgnames}{xcolor}' } ``` -------------------------------- ### Basic reStructuredText toctree Directive Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This reStructuredText snippet illustrates the fundamental structure of an empty `toctree` directive. The `maxdepth` option controls the depth of section titles included from referenced documents, defining the initial hierarchy for the documentation. ```rst .. toctree:: :maxdepth: 2 ``` -------------------------------- ### Build Sphinx Documentation to HTML Format Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/first-steps.rst This console command sequence demonstrates how to navigate to the `docs` directory and build the Sphinx documentation into HTML format using the `make html` command. This process updates the `index.html` file with the latest content, making it ready for web viewing. ```console (.venv) $ cd docs (.venv) $ make html ``` -------------------------------- ### Ruby Code Block Example Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-root/markup.txt An example of a Ruby code block, demonstrating a simple function definition. This block includes line numbers and a custom caption, showcasing Sphinx's `code-block` directive features. ```ruby def ruby? false end ``` -------------------------------- ### Applying TeX Extra Commands for Styling Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/latex.rst This snippet illustrates `\itshape`, an example of a LaTeX command that can be used with the `_TeXextras` option. These commands are inserted at the start of directive contents (after the heading for admonitions) to apply additional LaTeX styling. ```LaTeX \itshape ``` -------------------------------- ### Registering Message Catalogs in Sphinx Extension Setup Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/extdev/i18n.rst Illustrates how to configure a Sphinx extension's `setup` function to register its dedicated message catalog with the Sphinx application, specifying the catalog name and the path to the locale directory. ```Python def setup(app): package_dir = Path(__file__).resolve().parent locale_dir = package_dir / 'locales' app.add_message_catalog(MESSAGE_CATALOG_NAME, locale_dir) ``` -------------------------------- ### Build Sphinx Documentation Data with WebSupport Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Demonstrates how to create a `WebSupport` instance and call its `build()` method to generate necessary data (pickle files, search indices, node data) for web applications. It specifies the source directory for reStructuredText files (`srcdir`) and the output build directory (`builddir`). ```Python from sphinxcontrib.websupport import WebSupport support = WebSupport(srcdir='/path/to/rst/sources/', builddir='/path/to/build/outdir', search='xapian') support.build() ``` -------------------------------- ### Cross-reference Python Function with py:func Role Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This reStructuredText snippet illustrates how to create a cross-reference link to a documented Python function using the `py:func` role. Sphinx automatically finds the function's documentation and generates a link. ```rst The :py:func:`enumerate` function can be used for ... ``` -------------------------------- ### reStructuredText Code Block Indentation Rules Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/restructuredtext/basics.rst Demonstrates how indentation affects the content of `code-block` directives in reStructuredText. The first example shows content indented relative to an option line, while the second shows content indented relative to itself, affecting the starting whitespace of the output. ```reStructuredText .. code-block:: :caption: A cool example The output of this line starts with four spaces. .. code-block:: The output of this line has no spaces at the beginning. ``` -------------------------------- ### GitLab CI/CD Configuration for Sphinx HTML Documentation Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/deploying.rst This GitLab CI workflow defines a job with several steps to build Sphinx documentation: 1. Install the necessary dependencies (make, sphinx, furo). 2. Build the HTML documentation using Sphinx. 3. Move the output to a known artifacts location for deployment. ```YAML image: python:3.12-slim before_script: - apt-get update && apt-get install make --no-install-recommends -y - python -m pip install sphinx furo script: - cd docs && make html after_script: - mv docs/build/html/ ./public/ artifacts: paths: - public rules: - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH ``` -------------------------------- ### Applying Extra LaTeX Code to Admonition Contents Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/latex.rst These LaTeX macros are examples of extra code that can be inserted at the beginning of admonition contents via the `notetexextras` option. They are executed at the start of the content block, allowing for custom text styling such as bolding or changing font size. ```LaTeX \bfseries ``` ```LaTeX \footnotesize ``` -------------------------------- ### Example `someotherfile.rst` with Another `todo` Directive Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/tutorials/extending_build.rst Another reStructuredText example showing the usage of the `todo` directive in a separate content file, illustrating how multiple `todo` items can be distributed across a Sphinx project. ```rst bar === Some more text here... .. todo:: Fix that ``` -------------------------------- ### Populating reStructuredText toctree with Document Paths Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/quickstart.rst This reStructuredText snippet demonstrates how to add documents to a `toctree` directive by listing their names in its content. Document names are specified without file extensions and use forward slashes for directory separation, establishing the hierarchical order of the documentation. ```rst .. toctree:: :maxdepth: 2 usage/installation usage/quickstart ... ``` -------------------------------- ### Build HTML Documentation with Sphinx Docker Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Shows how to build HTML documentation for a Sphinx project using the official Sphinx Docker image. It mounts the document directory and runs `make html` inside the container. ```console $ docker run --rm -v /path/to/document:/docs sphinxdoc/sphinx make html ``` -------------------------------- ### Register Sphinx HTML Theme via Python setup function Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/html_themes/index.rst Shows a Python `setup` function that registers a Sphinx HTML theme using the `app.add_html_theme` API. This function is called by Sphinx when the theme package is loaded, making the theme available for use in documentation projects. ```python from pathlib import Path def setup(app): app.add_html_theme('name_of_theme', Path(__file__).resolve().parent) ``` -------------------------------- ### Example Configuration for Sphinx apidoc_modules Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/extensions/apidoc.rst This example demonstrates how to configure the 'apidoc_modules' setting in Sphinx, specifying multiple Python modules for documentation. It shows how to define module paths, output destinations, and various options like 'exclude_patterns', 'max_depth', and 'automodule_options' for fine-grained control over the generated API documentation. ```Python apidoc_modules = [ {'path': 'path/to/module', 'destination': 'source/'}, { 'path': 'path/to/another_module', 'destination': 'source/', 'exclude_patterns': ['**/test*'], 'max_depth': 4, 'follow_links': False, 'separate_modules': False, 'include_private': False, 'no_headings': False, 'module_first': False, 'implicit_namespaces': False, 'automodule_options': { 'members', 'show-inheritance', 'undoc-members' }, }, ] ``` -------------------------------- ### Build Sphinx Documentation to EPUB Format Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/first-steps.rst This console command shows how to build Sphinx documentation into EPUB format from the `docs` directory using the `make epub` command. After execution, the generated e-book files, including `Lumache.epub` and `index.xhtml`, will be found under `docs/build/epub/`. ```console (.venv) $ make epub ``` -------------------------------- ### Hardcoded and Standard reStructuredText Link Examples Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-ext-extlinks-hardcoded-urls-multiple-replacements/index.rst Presents a collection of hardcoded URLs and various standard reStructuredText link types, including direct URLs, inline hyperlinks, and reference-style links. These examples demonstrate common linking practices within Sphinx documentation. ```reStructuredText https://github.com/octocat `inline replaceable link `_ `replaceable link`_ `non replaceable link `_ .. _replaceable link: https://github.com/octocat ``` -------------------------------- ### WebSupport.get_document Method Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Documentation for the `get_document` method, which retrieves an individual Sphinx document. It details the parameters for specifying the document name and optional user authentication details, as well as the structure and content of the returned dictionary. ```APIDOC WebSupport.get_document(docname: str, username: str = '', moderator: bool = False) docname: The name of the document to retrieve (e.g., 'contents'). username: Optional unique string identifying the user for authentication. This username will be stored with comments and votes. moderator: Optional boolean indicating if the user has moderation privileges (defaults to False). Returns: dict body: The main body of the document as HTML. sidebar: The sidebar of the document as HTML. relbar: A div containing links to related documents. title: The title of the document. css: Links to CSS files used by Sphinx. script: JavaScript containing comment options. ``` -------------------------------- ### Deprecate Old-Style sphinx-quickstart Output Options Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/changes/7.3.rst The traditional `Makefile` and `make.bat` output generation in `sphinx-quickstart` is deprecated, along with its associated command-line options. Users are encouraged to adopt newer methods for project setup. ```APIDOC Deprecated sphinx-quickstart options: -M -m --no-use-make-mode --use-make-mode ``` -------------------------------- ### Configuring Apple Help Knowledgebase Product Tag in Sphinx Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/configuration.rst This option sets the product tag for use with 'applehelp_kb_url'. It defaults to a sample string combining the project and release names, allowing for dynamic product identification. ```Python '{project}-{release}' ``` -------------------------------- ### sphinx-build Command Synopsis Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/man/sphinx-build.rst Provides the basic command-line syntax for `sphinx-build`, showing the required source and output directories, and optional filenames for selective building. ```APIDOC sphinx-build [options] [filenames ...] ``` -------------------------------- ### Google Style Docstring Format Comparison Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/extensions/napoleon.rst This example shows the same docstring content rewritten in the Google Python Style Guide format. It highlights the improved legibility and conciseness achieved by using `Args` and `Returns` sections with type hints in parentheses, making the docstring easier to parse visually. ```text Args: path (str): The path of the file to wrap field_storage (FileStorage): The :class:`FileStorage` instance to wrap temporary (bool): Whether or not to delete the file when the File instance is destructed Returns: BufferedFileStorage: A buffered writable file descriptor ``` -------------------------------- ### Sphinx Extension Metadata Dictionary Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/extdev/index.rst Describes the dictionary structure that an extension's `setup()` function should return. This metadata informs Sphinx about the extension's version, its interaction with the build environment, and its compatibility with parallel processing during read and write phases. ```APIDOC Extension Metadata Dictionary: 'version': string Description: A string that identifies the extension version. Used for extension version requirement checking and informational purposes. If not returned, 'unknown version' is used by default. 'env_version': non-zero positive integer Description: Records the version of data stored in the environment by the extension. This key must be defined if the extension uses the 'env' object to store data. The version number must be incremented whenever the type, structure, or meaning of the stored data change. Constraint: If 'env_version' is not set, the extension must not store any data or state directly on the environment object ('env'). 'parallel_read_safe': boolean Description: Specifies if parallel reading of source files can be used when the extension is loaded. Defaults to False. Conditions (if True): - The core logic of the extension is parallelly executable during the reading phase. - It has event handlers for 'env-merge-info' and 'env-purge-doc' events if it stores data to the build environment object ('env') during the reading phase. 'parallel_write_safe': boolean Description: Specifies if parallel writing of output files can be used when the extension is loaded. Defaults to True. Conditions (if True): - The core logic of the extension is parallelly executable during the writing phase. ``` -------------------------------- ### Install Sphinx on macOS using Homebrew or MacPorts Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst On macOS, Sphinx can be installed using popular package managers like Homebrew or MacPorts. MacPorts may require additional commands to set up executable paths after installation. ```macOS Shell $ brew install sphinx-doc ``` ```macOS Shell $ sudo port install py313-sphinx ``` ```macOS Shell $ sudo port select --set python python313 $ sudo port select --set sphinx py313-sphinx ``` -------------------------------- ### Install Sphinx using Conda Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Sphinx can be installed using the Conda package manager from either the anaconda main channel or the conda-forge community channel. A conda-based Python distribution is required. ```Shell $ conda install sphinx ``` ```Shell $ conda install -c conda-forge sphinx ``` -------------------------------- ### Install or Upgrade Sphinx via pip Source: https://github.com/sphinx-doc/sphinx/blob/master/README.rst This command installs or upgrades the Sphinx documentation generator from the Python Package Index. Ensure you have a working installation of Python and pip before executing this command. ```shell pip install -U sphinx ``` -------------------------------- ### Example Sphinx Extension Folder Structure Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/development/tutorials/extending_syntax.rst Illustrates the recommended folder structure for a Sphinx project when adding a custom extension, showing the placement of the `_ext` directory and the `helloworld.py` file relative to `source`, `conf.py`, and `index.rst`. ```text └── source    ├── _ext │   └── helloworld.py    ├── conf.py    ├── index.rst ``` -------------------------------- ### Retrieve Individual Sphinx Documents Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/advanced/websupport/quickstart.rst Illustrates how to use the `support.get_document()` method to access individual Sphinx documents. This method returns a dictionary containing various HTML parts of the document (body, sidebar, relbar), its title, and links to CSS and JavaScript files, suitable for template rendering. ```Python contents = support.get_document('contents') ``` -------------------------------- ### Install Sphinx on Linux using OS Package Managers Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/usage/installation.rst Sphinx can be installed globally using distribution-specific package managers like apt-get for Debian/Ubuntu or yum for RHEL/CentOS. This method is less flexible than virtual environments. ```Linux Shell $ apt-get install python3-sphinx ``` ```Linux Shell $ yum install python-sphinx ``` -------------------------------- ### Define Project Welcome Page Content in reStructuredText Source: https://github.com/sphinx-doc/sphinx/blob/master/doc/tutorial/first-steps.rst This snippet shows how to modify the `index.rst` file to define the welcome page content for Sphinx documentation. It demonstrates reStructuredText syntax features like section headers, strong and emphasized text, inline external links, and a `note` admonition. ```rst Welcome to Lumache's documentation! =================================== **Lumache** (/lu'make/) is a Python library for cooks and food lovers that creates recipes mixing random ingredients. It pulls data from the `Open Food Facts database `_ and offers a *simple* and *intuitive* API. .. note:: This project is under active development. ``` -------------------------------- ### Basic 'Hello World' Output in Python Source: https://github.com/sphinx-doc/sphinx/blob/master/tests/roots/test-numfig/bar.rst This fundamental Python snippet demonstrates how to print a simple string to the console. It is commonly used as a first program to verify environment setup or for basic output operations. ```python print('hello world') ```