Showing code

There are different directives to show code (we will focus on Python, but is possible to use different languages).

Check http://www.sphinx-doc.org/es/stable/markup/code.html for more information.

Code role

The code role marks its content as code in a formal language:

:code:`print('hello')`

print('hello')

Although that might not be very helpful, you can use the role directive to create your own custom roles

.. role:: python(code)
   :language: python

print('hello')

:python:`print('hello')`

print('hello')

Code directive

The reST code directive:

.. code:: ‹language›
   :linenos:

   ‹body›
.. code:: python

   print('hello')
print('hello')

Literal blocks

In Sphinx, Python source code or interactive session can be use directly as literal blocks:

::

   <code>

   >>> <code for interactive session>

non interactive

print('hello')
hello

interactive

>>> print('hello')
hello

By default Python is used as the language of literal blocks. However this behaviour can be modified usign the highlight directive:

.. highlight:: c

From that point on, any code in literal blocks will be treated as C code until the next highlight directive modifies it.

The highlight can include the linenothreshold option that produce line number for code blocks longer than the value specified:

.. highlight:: c
   :linenothreshold: 5

Also take a look at the highlight_language variable that can be used in the configuration.

Code-block directive

When different code snippets in different languages are display, the code-block directive can be used to avoid modifying the language with the highlight directive:

.. code-block:: bash

   echo TEST
   TEST
echo TEST
TEST

This is similar to the reST Code directive but with more options.

Some options that can be used with the code-block directive are:

  • linenos: to number the lines

  • emphasize-lines:

  • caption: appears before the code block

  • name:

.. code-block:: python
   :linenos:
   :emphasize-lines: 1,3-4
   :caption: function example

   def f(val):
       a=1
       b=2
       v=a+b+val
       return v
function example
1def f(val):
2    a=1
3    b=2
4    v=a+b+val
5    return v

Take a look at the lexers that are supported.

Literalinclude

This directive can also be used to show code. It supports the same options of the code block, as well as some others, like:

  • language: to indicate the language

  • lines: to show only parts of the file

.. literalinclude:: ../conf.py
   :language: python
   :lines: 30-34
   :caption: sphinx extensions
   :emphasize-lines: 4
sphinx extensions
extensions = [
    'sphinx.ext.todo',
    'IPython.sphinxext.ipython_directive',
    'IPython.sphinxext.ipython_console_highlighting',
    'myst_parser'