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>