177

I know reStructuredText has this directive:

.. code:: bash

    gedit pohl.m

which renders a code block. Is there some way to get syntax highlighting for inline snippets like this:

Do edit the file, type ``gedit pohl.m`` into a terminal.

The backticks mark it as code, but I'd like to highlight it with pygments like the block. Is this possible?

Chris
  • 44,602
  • 16
  • 137
  • 156
Martin Ueding
  • 8,245
  • 6
  • 46
  • 92
  • 7
    The backticks mark that part of the text as an [inline literal](http://docutils.sourceforge.net/docs/user/rst/quickref.html#inline-markup), not as a code block. Typically this will just be published in a monospace font. I'm not sure how to get inline code syntax highlighted snippets I'm afraid. – Chris Jun 03 '12 at 15:25
  • See [Inline code highlighting § Roles — Sphinx documentation](https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html#inline-code-highlighting). – li ki Jul 19 '22 at 14:17

2 Answers2

273

Having looked into this some more I stumbled upon the document reStructuredText Interpreted Text Roles. From this document:

Interpreted text uses backquotes (`) around the text. An explicit role marker may optionally appear before or after the text, delimited with colons. For example:

This is `interpreted text` using the default role.

This is :title:`interpreted text` using an explicit role.

It seems that there is a code role, so you can simply type

:code:`a = b + c`

to render an inline code block. To get syntax highlighting you can define a custom role. For example

.. role:: bash(code)
   :language: bash

which you can then use like so:

Here is some awesome bash code :bash:`a = b + c`.

Note that the role definition must be placed before references to the role.

Note, the document I link to makes no mention of the version of docutils to which it refers. The code role is not available in docutils 0.8.1 (which is the only version I have to test against).

Community
  • 1
  • 1
Chris
  • 44,602
  • 16
  • 137
  • 156
  • 7
    please note this issue when using sphinx: https://stackoverflow.com/questions/21591107/sphinx-inline-code-highlight – Donatello Mar 28 '18 at 11:04
3

For me I had to create a docutils.conf file in the Sphinx's configuration directory (where conf.py resides). It had the following contents:

[restructuredtext parser]
syntax_highlight = short

See this answer for more information on the above

To set the role globally, in the conf.py file, I created a rst_prolog variable. The string inside it will be included at the beginning of every source file that is read.

rst_prolog = """
.. role:: python(code)
    :language: python
    :class: highlight
"""

In this highlight class was necessary for proper Python highlighting.

See this answer for more information on the above