Source code

To show example code, use the |RST|code-block directive:

RestructuredText  
.. 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:

RestructuredText  
.. 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:

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

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

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

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

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.

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

   code . . .

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:

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

Python  
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:

RestructuredText  
.. example-code::

  .. code-block:: JSON

    {
      "key": "value"
    }

  .. code-block:: python

    pygments_style = 'sphinx'


  .. code-block:: ruby

    print "Hello, World!\n"

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

JSON  
{
  "key": "value"
}

Source:

RestructuredText  
.. code-block:: JSON

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

Source:

RestructuredText  
.. code-block:: RST

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

Source:

RestructuredText  
.. code-block:: python

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

Source:

RestructuredText  
.. code-block:: ruby

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

Source:

RestructuredText  
.. code-block:: javascript

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

Source:

RestructuredText  
.. code-block:: HTML

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

Source:

RestructuredText  
.. code-block:: XML

    <name>Mark</name>
Last updated: Feb 3, 2025
Need help?Contact Support
Questions?Contact us