spaceman_spiff
spaceman_spiff

Reputation: 105

How do I set a caption for my generated code block in sphinx

Currently I am using the following code to generate a code block and show some information in it. I'd like to set a caption like with the following rst directive.

.. code-block:: python
   :caption: my_file.py

Currently I am using the following code but it

from docutils import nodes
from docutils.parsers.rst import Directive, directives


class ExecuteCode(Directive):

    def run(self):
        output = []
        input_code = nodes.literal_block(shown_code, shown_code)

        # This creates a normal text directly above the code block
        output.append(nodes.caption(text=self.options['header_code']))

        # This doesn't do anything at all
        input_code['caption'] = nodes.caption('asdf', 'asdf')
        
        return output

How can I set the caption on the literal_block?

Upvotes: 1

Views: 998

Answers (1)

Bob
Bob

Reputation: 734

As of Sphinx 1.3, it's the :caption: directive

Docs

Example:

.. code-block:: python
   :caption: my_file.py

   print("Hello world!")

Example Output: Example Output

Note: that I've found my editor previewer (pycharm or vscode) doesn't seem to support this directive, but when I build, the output files show the caption and code snippet as expected.

Upvotes: 0

Related Questions