Create Documentation with RST, Sphinx, Sublime, and GitHub

This project captures guidelines and tips for efficiently creating documentation using RST, Sphinx, Sublime Text, and GitHub.

This project is also created using the guidelines it describes.

This document is geared towards content creators, not programmers.

Contributions are welcome in the GitHub Repository.

Get Started

Set Up Your System

To get started, you need to:

Install Sublime

Get Sublime from Sublime website.

See the following video for installation help.

Learn Sublime

See the following video to get started learning Sublime.

Install Sphinx

To build your document in HTML (or other formats) on your computer, you must install Sphinx.

See Sphinx Overview for background reading. Then follow the steps below.

  1. If you are using Windows, you might need to Install Python.

    Depending on your Windows setup, after installation you might need to manually add the Python directory to your path. Try the Python Windows Install for help.

    If you are using a Mac, it’s probably installed.

  2. Install PIP.

    Depending on your Windows setup, after installation you might need to manually add the PIP directory to your path.

  3. Use PIP to install Sphinx. On the command line, enter:

    $ pip install Sphinx
    

Note

If you are using Windows, this might be a frustrating task. If you get stuck, share the error messages and ask for help.

You should now be able to create a Sphinx project. See First Steps with Sphinx.

Verify Sphinx Setup

You can use the Get Started with Sphinx Repository to verify that Sphinx is set up. You can also use it as the start of a new project.

  1. Make a fork of the repository and check it out on your computer.

  2. Open a command prompt and change directories to the get_started_sphinx directory.

  3. Run the command make html. Check if there are warnings or errors in the command window.

  4. Check for the HTML output in the get_started_sphinx/build/html directory.

  5. Open the file index.html.

    The page should look like the following image.

    _images/get_started_sphinx.png

If you the HTML is generated and there are no warnings or errors in the command prompt, Sphinx is set up correctly.

Sphinx Videos

These videos are very long and detailed. But they are great resources if you need to complete real projects in Sphinx.

Learn RST

To learn RST syntax, see the RST Primer. Then see the following video.

You can experiment with RST with the Online reStructuredText Editor

Note

Indentation is important in RST. Lots of problems are caused by inconsistent indentation. The only way to learn is to practice and see the results.

Create a Sphinx Project

You can use your fork of the Get Started with Sphinx Repository as the start of a new project, or you can create the project by entering the command:

$ sphinx-quickstart

Work through the prompts. See First Steps with Sphinx for more information.

Sphinx Project Configuration File

When you create a new project with sphinx-quickstart, the project’s main configuration file, conf.py is generated. This file contains the settings that control how your project is generated.

See Sphinx Configuration for information.

The following example shows the commented conf.py file for this project.

"""
Imports the system and the 
theme the project is using to the project.
"""

import sys, os
import sphinx_bootstrap_theme

"""
Adds path to the folder ext, where extensions are stored.
"""

sys.path.append(os.path.abspath('ext'))
sys.path.append('.')

"""
Tells Sphinx which extensions to use.
"""

extensions = ['xref', 
              'youtube', 
              'sphinx.ext.autosectionlabel',
              'sphinxcontrib.osexample']

"""
Imports all link files into project.
"""

from links.link import *
from links import *

"""
Tells the project where to look for theme templates and css overrides.
"""
templates_path = ['_templates']
html_static_path = ["_static"]

"""
Tells the project the name of the home page.
"""

master_doc = 'index'

"""
The project name, copyright, and author.
"""

project = u'RST | Sphinx | Sublime | GitHub'
copyright = u'2017, Mark Hoeber'
author = u'Mark Hoeber'

"""
The Google Analytics ID.
"""
googleanalytics_id = 'UA-88078032-1'

"""
Tells the project to use sphinx pygments for color coding code examples.
"""

pygments_style = 'sphinx'

"""
Tells the project to include content in todo directives.  Often set through 
parameter to make commands.
"""
todo_include_todos = True

"""
Tells the project which theme to use, and the theme options.
"""
html_theme = 'default'
html_theme_path = sphinx_bootstrap_theme.get_html_theme_path()

html_theme_options = {

  'navbar_site_name': "Contents",
  'source_link_position': "footer",
}

def setup(app):
    app.add_stylesheet("my-styles.css") 
    
"""
Tells the project to ignore certain files in the build process.
"""
exclude_patterns = ['substitutions.rst']

"""
Tells the project to append content at the end of every file during the build 
process.
"""
rst_epilog = """
.. include:: substitutions.rst
"""




###########################################################################
#          auto-created readthedocs.org specific configuration            #
###########################################################################


#
# The following code was added during an automated build on readthedocs.org
# It is auto created and injected for every build. The result is based on the
# conf.py.tmpl file found in the readthedocs.org codebase:
# https://github.com/rtfd/readthedocs.org/blob/master/readthedocs/doc_builder/templates/doc_builder/conf.py.tmpl
#


import importlib
import sys
import os.path
from six import string_types

from sphinx import version_info

# Get suffix for proper linking to GitHub
# This is deprecated in Sphinx 1.3+,
# as each page can have its own suffix
if globals().get('source_suffix', False):
    if isinstance(source_suffix, string_types):
        SUFFIX = source_suffix
    elif isinstance(source_suffix, (list, tuple)):
        # Sphinx >= 1.3 supports list/tuple to define multiple suffixes
        SUFFIX = source_suffix[0]
    elif isinstance(source_suffix, dict):
        # Sphinx >= 1.8 supports a mapping dictionary for multiple suffixes
        SUFFIX = list(source_suffix.keys())[0]  # make a ``list()`` for py2/py3 compatibility
    else:
        # default to .rst
        SUFFIX = '.rst'
else:
    SUFFIX = '.rst'

# Add RTD Static Path. Add to the end because it overwrites previous files.
if not 'html_static_path' in globals():
    html_static_path = []
if os.path.exists('_static'):
    html_static_path.append('_static')

# Add RTD Theme only if they aren't overriding it already
using_rtd_theme = (
    (
        'html_theme' in globals() and
        html_theme in ['default'] and
        # Allow people to bail with a hack of having an html_style
        'html_style' not in globals()
    ) or 'html_theme' not in globals()
)
if using_rtd_theme:
    theme = importlib.import_module('sphinx_rtd_theme')
    html_theme = 'sphinx_rtd_theme'
    html_style = None
    html_theme_options = {}
    if 'html_theme_path' in globals():
        html_theme_path.append(theme.get_html_theme_path())
    else:
        html_theme_path = [theme.get_html_theme_path()]

if globals().get('websupport2_base_url', False):
    websupport2_base_url = 'https://readthedocs.org/websupport'
    websupport2_static_url = 'https://assets.readthedocs.org/static/'


#Add project information to the template context.
context = {
    'using_theme': using_rtd_theme,
    'html_theme': html_theme,
    'current_version': "latest",
    'version_slug': "latest",
    'MEDIA_URL': "https://media.readthedocs.org/",
    'STATIC_URL': "https://assets.readthedocs.org/static/",
    'PRODUCTION_DOMAIN': "readthedocs.org",
    'versions': [
    ("latest", "/en/latest/"),
    ],
    'downloads': [ 
    ("html", "//sublime-and-sphinx-guide.readthedocs.io/_/downloads/en/latest/htmlzip/"),
    ],
    'subprojects': [ 
    ],
    'slug': 'sublime-and-sphinx-guide',
    'name': u'Sublime and Sphinx Guide',
    'rtd_language': u'en',
    'programming_language': u'words',
    'canonical_url': 'https://sublime-and-sphinx-guide.readthedocs.io/en/latest/',
    'analytics_code': '',
    'single_version': False,
    'conf_py_path': '/source/',
    'api_host': 'https://readthedocs.org',
    'github_user': 'MarkHoeber',
    'proxied_api_host': '/_',
    'github_repo': 'sublime_sphinx_guide',
    'github_version': 'master',
    'display_github': True,
    'bitbucket_user': 'None',
    'bitbucket_repo': 'None',
    'bitbucket_version': 'master',
    'display_bitbucket': False,
    'gitlab_user': 'None',
    'gitlab_repo': 'None',
    'gitlab_version': 'master',
    'display_gitlab': False,
    'READTHEDOCS': True,
    'using_theme': (html_theme == "default"),
    'new_theme': (html_theme == "sphinx_rtd_theme"),
    'source_suffix': SUFFIX,
    'ad_free': False,
    'docsearch_disabled': False,
    'user_analytics_code': '',
    'global_analytics_code': 'UA-17997319-1',
    'commit': 'd3579a96',
}

# For sphinx >=1.8 we can use html_baseurl to set the canonical URL.
# https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-html_baseurl
if version_info >= (1, 8):
    if not globals().get('html_baseurl'):
        html_baseurl = context['canonical_url']
    context['canonical_url'] = None





if 'html_context' in globals():
    
    html_context.update(context)
    
else:
    html_context = context

# Add custom RTD extension
if 'extensions' in globals():
    # Insert at the beginning because it can interfere
    # with other extensions.
    # See https://github.com/rtfd/readthedocs.org/pull/4054
    extensions.insert(0, "readthedocs_ext.readthedocs")
else:
    extensions = ["readthedocs_ext.readthedocs"]

# Add External version warning banner to the external version documentation
if 'branch' == 'external':
    extensions.insert(1, "readthedocs_ext.external_version_warning")
    readthedocs_vcs_url = 'None'
    readthedocs_build_url = 'https://readthedocs.org/projects/sublime-and-sphinx-guide/builds/13104311/'

project_language = 'en'

# User's Sphinx configurations
language_user = globals().get('language', None)
latex_engine_user = globals().get('latex_engine', None)
latex_elements_user = globals().get('latex_elements', None)

# Remove this once xindy gets installed in Docker image and XINDYOPS
# env variable is supported
# https://github.com/rtfd/readthedocs-docker-images/pull/98
latex_use_xindy = False

chinese = any([
    language_user in ('zh_CN', 'zh_TW'),
    project_language in ('zh_CN', 'zh_TW'),
])

japanese = any([
    language_user == 'ja',
    project_language == 'ja',
])

if chinese:
    latex_engine = latex_engine_user or 'xelatex'

    latex_elements_rtd = {
        'preamble': '\\usepackage[UTF8]{ctex}\n',
    }
    latex_elements = latex_elements_user or latex_elements_rtd
elif japanese:
    latex_engine = latex_engine_user or 'platex'

# Make sure our build directory is always excluded
exclude_patterns = globals().get('exclude_patterns', [])
exclude_patterns.extend(['_build'])

Glossary Terms

GitHub
GitHub is a web-based Git repository hosting service. It offers all of the distributed version control and source code management (SCM) functionality of Git as well as adding its own features. It provides access control and several collaboration features such as bug tracking, feature requests, task management, and wikis for every project.
RST
reStructured Text is an easy-to-read, what-you-see-is-what-you-get plaintext markup syntax and parser system. It is useful for in-line program documentation (such as Python docstrings), for quickly creating simple web pages, and for standalone documents. reStructured Text is designed for extensibility for specific application domains. The reStructured Text parser is a component of Docutils.
Sphinx
Sphinx is a tool that makes it easy to create intelligent and beautiful documentation. It was originally created for the Python documentation, and it has excellent facilities for the documentation of software projects in a range of languages.
Sublime Text
Sublime Text is a sophisticated text editor for code, markup and prose. You’ll love the slick user interface, extraordinary features and amazing performance.
Substitution
Substitutions are variables that you can add to text. If the value changes, you change it in one place, and it is updated throughout documentation. See Use a Substitution.

Set up Sublime

Install Sublime Packages

To improve the experience of using Sublime to edit RST files, install the Sublime packages below.

Syntax Highlighting

Use RestructuredText Improved to set highlighting of RST syntax in Sublime.

This package also lets you navigate to headers in the current file using CTRL-R or Command+R.

Preview RST in Browser

Install OmniMarkupPreviewer to preview RST in a web browser.

After installing the package, you can use the following shortcut to open the current file in your default browser:

  • Ctr+Alt+O on Windows
  • Command+option+O on a Mac

RST Completion

Sublime RST Completion is a group of snippets and commands to facilitate writing restructuredText with SublimeText. See the demo below.

Create Macros

Customize Sublime

You can customize Sublime in many ways, as described below.

Set Preferences

You can set a wide variety of editor preferences.

From the Sublime Text menu, select Preferences >> Settings.

A new window opens with two files displayed: the default sublime settings, and the user settings.

Do not edit the default settings. Instead, you specify custom preferences in the user settings file. User settings override default settings.

For example, the default editor font size is 10pt. If you want 14pt text, copy the font-size attribute into the user prefernces file and change 10 to 14.

The changes are visible when you save the user preferences file.

Explore the default preferences list for settings you want to override, and add those to the user preferences list and change the values.

For example, here is my user preferences file:

{
        "color_scheme": "Packages/Color Scheme - Default/Solarized (Dark).tmTheme",
        "tab_size": 2,
        "font_size": 14,
        "font_face": "arial",
        "line_padding_top": 2,
}

Set Shortcut Keys

You can set a shortcut keys as needed..

From the Sublime Text menu, select Preferences >> Key Bindings.

A new window opens with two files displayed: the default sublime key bindings, and the user key bindings.

The key binding format is:

{ "keys": ["key+key+key"],  "command": "command_name" }

For example:

{ "keys": ["super+shift+["], "command": "prev_view" }

Do not edit the default key bindings. Instead, you specify custom key bindings in the user settings file. User settings override default settings.

The changes are active when you save the user preferences file.

Explore the default key bindings list for settings you want to override, and add those to the user preferences list and change the values.

Set Colors

You can set the color scheme in the editor.

  1. From the Sublime Text menu, select Preferences >> Color Scheme.
  2. Select from the color schemes listed.

Use Snippets as Shortcuts

Snippets are short fragments of text that you use frequently. Use snippets to save yourself tedious typing. Snippets are smart templates that will insert text for you and adapt it to their context.

You can associate snippets with triggers, that is, specific keystrokes. For example, if you configured a snippet for an RST ordered list with the trigger ol, when you enter ul, the following snippet is added at the cursor:

#. Step one.

#. Step two.

#. Step three.

After it’s added at the cursor, you can edit the snippet as needed. You can configure the snippet so you can tab through subsequent parts of the text.

The following video demonstrates using some custom snippets for common RST structures.

Snippets are stored on your computer. To share snippets within a team, you must manually share the snippet files.

For a good overview of snippets, see Snippets Saved My Life.

Add a Snippet

You add a snippet in Sublime.

  1. From the Tools menu, select Developer >> New Snippet.

    A new file opens with the snippet template:

    <snippet>
      <content><![CDATA[
    Hello, ${1:name} is a ${2:snippet}.
    ]]></content>
      <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
      <!-- <tabTrigger>keystrokes</tabTrigger> -->
      <!-- Optional: Set a scope to limit where the snippet will trigger -->
      <!-- <scope>source.rst</scope> -->
    </snippet>
    
  2. Modify the content within [CDATA[.

    • To be able to tab through text fields in the snippet, use ${n:text}, where n is the number for the tab order, and text is the default text in the snippet.

    • To add a key shortcut, uncomment the <tabTrigger> element and enter the keystrokes that will add the snippet:

      <tabTrigger>code</tabTrigger>
      
  3. Save the file.

You can then add the snippet to RST files by typing the tab trigger text.

Example Snippets

You can create snippets to suit your needs. Anything you find yourself repeating is a good candidate for a snippet. Following are snippets for common RST uses. You can copy the files for these snippets from the repository for this document into your Sublime user package.

H1
<snippet>
  <content><![CDATA[
.. _${1:this}:

${1:this} 
###################

${2:Content starts here}
]]></content>
  <tabTrigger>h1</tabTrigger> 
</snippet>
H2
<snippet>
  <content><![CDATA[
${1:this} 
***********************

${2:Content starts here}
]]></content>
  <tabTrigger>h2</tabTrigger> 
</snippet>
H3
<snippet>
  <content><![CDATA[
${1:this} 
=========================

${2:Content starts here}
]]></content>
  <tabTrigger>h3</tabTrigger> 
</snippet>
Anchor
<snippet>
  <content><![CDATA[
.. _${1:this}:

]]></content>
  <tabTrigger>anchor</tabTrigger> 
</snippet>
Code
<snippet>
  <content><![CDATA[
.. code-block:: ${1:type}
  :linenos:

  code


]]></content>
  <tabTrigger>code</tabTrigger> 
</snippet>
File Include
<snippet>
  <content><![CDATA[
.. include:: ${1:filename}

]]></content>
  <tabTrigger>inc</tabTrigger> 
</snippet>
List
<snippet>
  <content><![CDATA[
* ${1:this} 

* ${2:this}

* ${3:this}

]]></content>
  <tabTrigger>ul</tabTrigger> 
</snippet>
Internal Reference
<snippet>
  <content><![CDATA[
:ref:`${1:this}`

]]></content>
  <tabTrigger>ref</tabTrigger> 
</snippet>
Steps
<snippet>
  <content><![CDATA[
#. ${1:this} 

#. ${2:this}

#. ${3:this}

]]></content>
  <tabTrigger>ol</tabTrigger> 
</snippet>
Substitution
<snippet>
  <content><![CDATA[
|${1:this}|

]]></content>
  <tabTrigger>sub</tabTrigger> 
</snippet>
Index Page TOC
<snippet>
  <content><![CDATA[
.. toctree::
    :maxdepth: 1

      file
      file
      file
      file
]]></content>
  <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
  <tabTrigger>toc</tabTrigger>
</snippet>
YouTube Video
<snippet>
  <content><![CDATA[
.. youtube:: ${1:Youtube ID}

]]></content>
  <tabTrigger>ytube</tabTrigger> 
</snippet>

Work with reStructured Text Content

Write Topics

A topic, or page, explains to users “what, why, and how”. Typically a topic should be short and focused on a single subject.

A reStructured Text file in a project becomes one HTML page in the document.

Typically a topic starts by explaining abstract ideas and introducing terminology. Then the topic covers how users accomplish specific tasks.

Topic Outline

You can use the outline below to start a new topic:

Topic Title
###########

High-level overview of topic.

What is ?
**********

High level conceptual information (Heading 2).

At a minimum, a concept includes the following components.

* A title, phrased as a gerund or question.
* One or more body paragraphs.

Complex concepts may contain 2 or more subsections.

What is <part of subject> ?
============================

When you need to break down a subject, you can break it down into subsections (H3s). Typically you would have 0 H3s, or 2+ H3s.


What is <part of subject> ?
============================

When you need to break down a subject, you can break it down into subsections (H3s)

Do this
**********

A task typically follows conceptual information. Task titles should be imperative. Tasks should have a short introduction sentence that captures the user's goal and introduces the steps, for example, "Verify your products are in the catalog:"

A task should have 3 - 7 steps.  Tasks with more should be broken down into digestible chunks.

Intro sentence.

#. Step 1.

#. Step 2.

#. Step 3.

Following the steps, you should add the result and any follow-up tasks needed.

Use Headings

In reStructured Text, the level of a heading is indicated by a series of symbols below the heading text. You can use any symbols, as long as you use them consistently for each level.

This document uses the following symbols:

  • H1: pound symbols (#)
  • H2: asterisk (*)
  • H3: equals symbol (=)

For example:

Heading 1
###########

The top level heading on any file, underscored by #. use for the topic title.

Heading 2
**********

The second level heading in a topic. Use for high-level concepts, tasks, or
reference information.

Heading 3
===========

The 3rd level heading in a topic. Use for breaking down conceptual
information into understandable chunks.

Note

Heading text cannot extend beyond the markers. If translated heading text is longer than the original English text, make sure to extend the markers so that they are at least the same length as translated text.

Create Tables of Contents

When you create new topics, you must add them to a TOC in the project.

You can add topics to the main TOC in the main index file. Or you can add them to TOCs in other files to create a second level in your document.

You add files in the .. toctree:: directive, using the file name (RST extension is not necessary.) See Sphinx TOC Tree Documentation for more information.

For example, the main index file for this project contains 5 separate TOCs. They are broken up in order to use headings for each part.

If you add a file to the project and do not include it in a TOC, it will not be built, and you will get a warning when building the project, unless you add it to the excluded files in the conf.py file.

Depth

In this project, only the top-level headings are listed in to TOC. You can include other levels in an indented list by setting the :maxdepth: parameter to 2 or higher:

.. toctree::
 :maxdepth: 2

In this example, second-level headings will be indented under the topic title in the TOC.

Numbered Sections

You can automatically generate numbered topics and sections by adding the :numbered: parameter to the .. toctree directive:

.. toctree::
 :numbered:

Each topic and section is then numbered consecutively in the output.

Use Lists

This topic shows how to use ordered and unordered lists in reStructured Text.

Ordered Lists

Use hash symbols for ordered lists:

#. Step 1.
#. Step 2.
#. Step 3.

Note

Ordered lists usually use numerals. Nested ordered lists (ordered lists inside other ordered lists) use letters.

An ordered lists should have 3-7 items.

Unordered Lists

Use asterisks for unordered (bulleted) lists.

* Item 1.
* Item 2.
* Item 3.

An unordered lists should have 3-7 items.

Unordered List Inside Ordered List

To include an unordered list inside an ordered list, indent the unordered list three spaces. The first bullet in the unordered list must be flush with the text in the ordered list.

#. Step 1.

    * Item 1.

    * Item 2.

#. Step 2.

Ordered List Inside Unordered List

To include an ordered list inside an unordered list, indent the ordered list two spaces. The first number or letter of the ordered list must be flush with the text in the unordered list.

* Item 1.

  #. Step 1.

  #. Step 2.

* Item 2.

Unordered List Inside Unordered List

To include an unordered list inside another unordered list, indent the second unordered list two spaces. The first bullet of the second unordered list must be flush with the text in the unordered list.

* Item 1.

  * Item a.

  * Item b.

* Item 2.

Ordered List inside Ordered List

To include another ordered list inside an ordered list, indent the second ordered list three spaces. The second ordered list must be flush with the text in the numbered list. The first ordered list uses numerals, and the second uses letters.

#. Step 1.

    #. Step a.

    #. Step b.

#. Step 2.

Code, Images, and Other Content Inside Lists

To include content such as code or an image inside a list, position the code or image directive flush with the text in the list. That is, indent three spaces for ordered lists and two spaces for unordered lists.

#. Step 1. Example:

    .. code-block:: bash

      Example code

#. Step 2.

Use Notes and Warnings

Use notes and warnings to make a sentence stand out visually.

In reStructured Text, you specify notes are warnings through directives (the .. syntax).

Notes

Note

This is note text. Use a note for information you want the user to pay particular attention to.

If note text runs over a line, make sure the lines wrap and are indented to the same level as the note tag. If formatting is incorrect, part of the note might not render in the HTML output.

Notes can have more than one paragraph. Successive paragraphs must indent to the same level as the rest of the note.

This is how the note appears in RST:

.. note::
   This is note text. Use a note for information you want the user to
   pay particular attention to.

   If note text runs over a line, make sure the lines wrap and are indented to
   the same level as the note tag. If formatting is incorrect, part of the note
   might not render in the HTML output.

   Notes can have more than one paragraph. Successive paragraphs must
   indent to the same level as the rest of the note.

Warnings

Warning

This is warning text. Use a warning for information the user must understand to avoid negative consequences.

Warnings are formatted in the same way as notes. In the same way, lines must be broken and indented under the warning tag.

This is how the warning appears in RST:

.. warning::
    This is warning text. Use a warning for information the user must
    understand to avoid negative consequences.

    Warnings are formatted in the same way as notes. In the same way,
    lines must be broken and indented under the warning tag.

Show Example Code

To show example code, use the reStructured Text code-block directive:

.. code-block:: language

   code

By specifying the language, you enable pygments, which show syntax color coding for that code sample. (Ensure that your project conf.py file contains pygments_style = 'sphinx').

If you might use the same example code in multiple parts of the document or multiple documents, you can save it as a separate file and include it directly:

.. include:: my_code_example.txt

The included file must start with the code-block directive.

Alternatively, you can use the literalinclude directive to include an actual code file:

.. literalinclude:: configuration.json
  :language: JSON

You could add code-block directives for different languages as snippets.

Show Line Numbers

You can add line numbers to code examples with the :linenos: parameter.

1
2
3
4
.. code-block:: javascript
  :linenos:

  code . . .

Highlight Lines

You can have certain lines in an example highlighted line numbers to code examples with the :emphasize-lines: parameter. In the following example, line 2 (with the :emphasize-lines: directive) is highlighted.

 .. code-block:: javascript
   :emphasize-lines: 8,10,16

   code . . .

Code Examples in Multiple Languages

You might want to show code examples in multiple languages. You can use the sphinxcontrib-osexample extension to create code examples to be displayed in a tabbed list. For example:

{
  "key": "value"
}
pygments_style = 'sphinx'
print "Hello, World!\n"

To enable tabs for multiple code examples, add sphinxcontrib.osexample to the list of extensions in the conf.py file:

extensions = ['sphinx.ext.autosectionlabel',
              'sphinxcontrib.osexample']

Then, to show multiple code examples with tabs, embed the code blocks under the .. example-code:: directive. The RST text for the code block example above is:

.. example-code::

  .. code-block:: JSON

    {
      "key": "value"
    }

  .. code-block:: python

    pygments_style = 'sphinx'


  .. code-block:: ruby

    print "Hello, World!\n"

Examples

The following examples show code blocks in different languages, with automatic syntax color coding.

JSON
{
  "key": "value"
}

Source:

.. code-block:: JSON

  {
    "key": "value"
  }
RST
.. code-block:: RST

Source:

.. code-block:: RST

  .. code-block:: RST
Python
pygments_style = 'sphinx'

Source:

.. code-block:: python

    pygments_style = 'sphinx'
Ruby
print "Hello, World!\n"

Source:

.. code-block:: ruby

  print "Hello, World!\n"
Javascript
alert('Hello, World!')

Source:

.. code-block:: javascript

  alert('Hello, World!')
HTML
<h1 class="title">Title</h1>

Source:

.. code-block:: HTML

  <h1 class="title">Title</h1>
XML
<name>Mark</name>

Source:

.. code-block:: XML

    <name>Mark</name>

Use Tables

Tables are very useful for presenting complex information. With reStructured Text and Sphinx, you can create tables in several ways.

List Table Directive

You can add reStructured Text table syntax with .. list-table:: directive.

Each table has the number of columns and their associated relative widths indicated in a width tag.

For proper formatting, the asterisk indicating each row must align vertically, and the hyphens indicating each column must also align. Empty cells must be accounted for, so that each column in a row is always marked, even if there is no content in the table cell. An example of an empty cell is the second column in the first row of the following example.

.. list-table:: Title
   :widths: 25 25 50
   :header-rows: 1

   * - Heading row 1, column 1
     - Heading row 1, column 2
     - Heading row 1, column 3
   * - Row 1, column 1
     -
     - Row 1, column 3
   * - Row 2, column 1
     - Row 2, column 2
     - Row 2, column 3

The table is displayed in HTML as:

Title
Heading row 1, column 1 Heading row 1, column 2 Heading row 1, column 3
Row 1, column 1   Row 1, column 3
Row 2, column 1 Row 2, column 2 Row 2, column 3

CSV Files

It’s often easier to create tables in a program like Excel than with RST syntax. You can then save the table as a CSV file, and reference the CSV file in your reStructured Text file where you want the table to go.

When you have a CSV file, reference it with the .. csv-table:: directive. For widths, use the percentage width of each column (without the % sign). For header rows, typically use 1.

Make sure the parameters match the content of the CSV file.

.. csv-table:: Table Title
   :file: CSV file path and name
   :widths: 30, 70
   :header-rows: 1

Within the CSV file, you can use RST markup just as you would if writing in directly in the RST file.

Add Images

You add images to reStructured Text with the .. image:: directive:

.. image:: path/filename.png
  :width: 400
  :alt: Alternative text

For example this image:

_images/get_started_sphinx.png

Is added to the reStructured Text file in by the following lines:

.. image:: images/get_started_sphinx.png
   :width: 600

Use Image Substitutions

You can also define a substitutions to reference an image:

.. |Substitution Name| image:: path/filename.png
  :width: 400
  :alt: Alternative text

Then add the image in content by adding the substitution name:

The screen opens:

|Substitution Name|

This is useful if you are using the image multiple times in a project and want to manage it in one location.

Width

You set the image width in pixels using the :width: parameter.

Typically you want to use a width between 400 - 800 pixels.

Alt text

You should add alternative text for screen readers for each image using the :alt: parameter. Provide text that is useful to someone who might not be able to see the image.

Add Videos

Use Inline Formatting

You can specify inline formatting in RST through special symbols around the text you want to format.

Code Text

Use double backquotes to show text as code. For example:

Set the ``env`` variable.

The ``Production Accepted`` event.

Edit the ``conf.py`` file.

Enter: ``run``

Use code formatting to highlight code snippets, variable names, file paths and names, or text the user must type.

Italic Text

Use single asterisks to show text as italic, or emphasized, for example when introducing a new term.

A *title* is about . . .

Bold Text

Use double asterisks to show text as bold, or strong.

Select **Sign In**

Use for UI elements.

Use Conditional Text

Sphinx supports conditional text. That is, you can specify that some content is visible only to the intended audience. You can then build different versions of the project for different audiences

To limit visibility of certain content, indent that content under an .. only:: directive. For example, to specify that some content is available only to internal audiences, use:

.. only:: Internal

  Content to be included only in the internal version of the document.

Build Projects with Conditions

When you use conditions, you must use the -t audience flag in the build command to specify which version of the project to build.

For example, the default command to build HTML in a project Makefile is:

.PHONY: html
html:
 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)
 @echo
 @echo "Build finished. The HTML pages are in $(BUILDDIR)."

If you use this command (make html) to build the project, the resulting HTML will not include content indented under the .. only:: Internal directive.

To build a project that does include this conditional content, add a command to your Makefile with the parameter -t Internal:

.PHONY: internalhtml
 internalhtml:
  $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) -t Internal $(INTERNALBUILDDIR)
  @echo
  @echo "Build finished. The HTML pages are in $(INTERNALBUILDDIR)."

Then build the project with make internalhtml. The resulting HTML will include the internal-only content.

Note

This example assumes you have defined INTERNALBUILDDIR as a separate location for the built files. You do not want to place them in the same directory as those files built without the conditional text, and have them overwrite the other project.

Add a Glossary

Sphinx has a built-in Glossary structure that you can use to:

  • Produce a consolidated glossary of terms.
  • Link terms in other content to their glossary definitions.

Create a Glossary

To add glossary terms, you use the directive .. glossary::. Write each glossary entry as a definition list, with a term, followed by a single-line indented definition.

Each glossary entry is nested below the .. Glossary:: directive. For example:

.. glossary::

    Sphinx
      Sphinx is a tool that makes it easy to create intelligent and beautiful documentation. It was originally created for the Python documentation, and it has excellent facilities for the documentation of software projects in a range of languages.

    RST
      |RST| is an easy-to-read, what-you-see-is-what-you-get plain text markup syntax and parser system. It is useful for in-line program documentation (such as Python docstrings), for quickly creating simple web pages, and for standalone documents. |RST| is designed for extensibility for specific application domains. The |RST| parser is a component of Docutils.

    Sublime Text
      Sublime Text is a sophisticated text editor for code, markup and prose. You'll love the slick user interface, extraordinary features and amazing performance.

You can list all glossary terms under a single Glossary directive, or use multiple Glossary directives.

For more information, see the Sphinx Glossary Documentation.

Link a Term to its a Glossary Entry

When a glossary term is used in text, you can link it to its definition with the :term: role. For example, to link the term Sphinx to its definition, use the following syntax:

:term:`Sphinx`

The term specified must exactly match a term in Glossary directive.

You can link to a term in the glossary while showing different text in the topic by including the term in angle brackets. For example:

:term:`reStructuredText<RST>`

The term in angle brackets must exactly match a term in the glossary. The text before the angle brackets is what users see on the page.

Reuse Content

Sphinx supports several ways to reuse content within and across projects.

Use a Substitution to reuse short, inline content.

Include a Shared File to reuse longer, more complex content.

Use a Substitution

For common, short content, use RST substitutions.

For example, use a substitution for a product name. To print the product name in a topic, enter |Product|. For example:

Set |Product| configuration properties by . . .

The value of |Product| is defined in a substitution definition:

.. |Product| replace:: SoftTech Analyzer

The generated documentation from this example is:

Set SoftTech Analyzer configuration properties by . . .

If you then change the replace value of the substitution, the new value is used in all instances when you rebuild the project.

You can define a substitution in any RST file in the project. To keep the project organized and have substitutions easily discoverable by other team members, you can include all substitutions in a file that is included in every other project file.

For more information, see the Sphinx Substitutions Documentation.

Include a Shared File

You can store complex content, such as tasks, or code samples, in a file that is then included in multiple.

If you are working on multiple projects, you can save entire topics in shared files, and include those files in multiple projects.

You add a shared file to content in your project with the .. include:: directive. For example:

.. include:: ../shared/folder/filename.rst

The contents of the shared file will then be built in the project.

Caution

Include paths are relative to the file in the document project, not the file in shared content.

Note

You must reference the shared file from a file within the project. You cannot use a direct TOC reference to files outside of the project directory.

Manage Content in GitHub

TBP

Deliver Documentation

Use Themes

Customize Styles

Build the Project

Make HTML

To build the HTML output for your project, open the command prompt in the top-level folder of your project (the location of the Makefile). Then enter:

make html

The HTML files are created in the build folder. Typically this is called build and at the same level as the source folder, although you can change this in the Makefile.

Automatically Generate HTML Updates

You can set up your project so that the HTML is automatically regenerated every time you save a change. This allows you to keep a the project open in your browser and view changes immediately.

You must install Sphinx Autobuild.

  1. From a command prompt, enter pip install sphinx-autobuild.

  2. In the Makefile, add the lines:

    SPHINXAUTOBUILD = sphinx-autobuild
    
    ALLSPHINXLIVEOPTS   = $(ALLSPHINXOPTS) -q \
       -p 0 \
       -H 0.0.0.0 \
       -B \
       --delay 1 \
       --ignore "*.swp" \
       --ignore "*.pdf" \
       --ignore "*.log" \
       --ignore "*.out" \
       --ignore "*.toc" \
       --ignore "*.aux" \
       --ignore "*.idx" \
       --ignore "*.ind" \
       --ignore "*.ilg" \
       --ignore "*.tex" \
       --watch source
    
    .PHONY: livehtml
    livehtml:
       $(SPHINXAUTOBUILD) -b html $(ALLSPHINXLIVEOPTS) $(BUILDDIR)
       @echo
       @echo "Build finished. The HTML pages are in $(BUILDDIR)."
    
  3. From the command prompt, enter:

    make livehtml
    

The project is built and opens automatically in your browser.

Each time you save a file in the project, it is automatically rebuilt. Just refresh your browser.

Note

If there are errors in the project, the automatic build will not complete and the HTML will not be updated. Check the command window for error details.

Use Read the Docs

Content starts here