Search code examples
python-sphinxrestructuredtext

How do I specify whitespace or an empty string in a reStructuredText directive option?


I want an empty string or a single space for a caption -- how can I do it?

.. code-block:: c
   :name: forever
   :caption: ""

   for (;;)
   {
     ;
   }

This doesn't work, I get an error message instead; if I use " " the quotes show up in my output.


Solution

  • It depends on the option in question, see below for the "code-block" :caption:.

    The rST Markup Specification states: "Directive options are indicated using field lists; the field names and contents are directive-specific." Field lists may have an empty field_body, so the simplest input for an empty string is an empty string. A working example is

    .. image:: foo.png
       :alt:
    

    The empty string overwrites the value (the image URI), HTML browsers will silently ignore a missing image when rendering the the HMTL output.

    Other options (e.g. :class: or the "sidebar" directive's :subtitle:) throw an exception when used without value. This holds also for :caption: in the "code-block" directive added by Sphinx.

    The :caption: value, however, is parsed as inline reStructuredText (details are unfortunately undocumented), so any construct that does not generate visible output may be used to get an empty caption.

    My recommendation is to use an empty¹ comment:

    .. code-block:: c
       :name: forever
       :caption: ..
    
       for (;;) { ; }
    

    An alternative is defining and using a substitution for the space character, e.g.

    .. |space| unicode:: 32 
    
    .. code-block:: c
       :name: forever
       :caption: |space|
    
       for (;;) { ; }
    

    ¹In contrast to a comment in a standard rST field-body, content following the .. is not suppressed.