Search code examples
python-sphinxrestructuredtext

If possible, how do we put hyperlink within the code section in rst files?


I have the following in an rst file:

.. code-block:: bash

   user@adi:~/workspace$ pytest
   test/test/functional/example/test_api_2.py
   --testbed test/test/topo_confs/pytest_tb.json
   --loglevel DEBUG --html /home/user/test.html --self-contained-html

Now how do I put a hyperlink on the pytest_tb.json word in that code?


Solution

  • .. code-block:: only applies syntax highlighting to literal code, which means it does not support hyperlinks by interpreting reStructuredText markup.

    Instead you could use a custom style in your Sphinx theme's CSS file, let's say named my-code-block, and use reST markup, something like the following.

    In your CSS file:

    p.my-code-block {
        font-family: monospace;
        white-space: pre;
    }
    

    And in your reST source file:

    .. rst-class:: my-code-block
    
        user@adi:~/workspace$ pytest
        test/test/functional/example/test_api_2.py
        --testbed test/test/topo_confs/`pytest_tb.json <relative/path/to/pytest_tb.json>`_
        --loglevel DEBUG --html /home/user/test.html --self-contained-html
    

    Note that will not apply bash syntax highlighting from Pygments. However you could get fancy and use a JavaScript syntax highlighter on the HTML output, but getting the HTML output to conform to what the JavaScript requires as well as updating the theme can be challenging and more trouble than it is worth.