Search code examples
pythonpython-sphinxrestructuredtextdocutils

How to escape single quotes in reStructuredText when converting to HTML using Sphinx


For a documentation project I am writing I need to include a table with date format strings. Now almost everything works fine, but at the end I have this slight problem where I want to print a literal ' quote and two literal quotes (separately and between other quotes). Sphinx changes these to up/down quotes, which usually looks really neat, but in this particular case makes the text unreadable. The best I could come up with was:

======   ===========   ======  =====================
``'``    Escape for            | " ``'`` hour ``'`` h" -> "hour 9"
         for text 
         Delimiter
``''``   Single                | "ss ``''`` SSS" -> "45 ``'`` 876"
         quote 
         Literal  
======   ===========   ======  =====================

This produces all the right quotes, but it inserts extra spaces before and after, which I would like to see removed, since the example is not syntactically correct that way. So one could also rephrase my question as: How to remove extra spaces before and after literal quotes when using backticks.

I have tried standard ways of escaping. Backslashes have no effect, since ' is not a reStructuredText special character. If I remove the spaces the backticks `` won't work anymore.

Sample output with extra spaces: enter image description here


Solution

  • As mentioned by other people in the comments, this process where Sphinx changes plain " into curled and so on is called SmartQuotes.

    I'm not sure if you specifically wanted the literals at all in the first place, or if they were only a compromise to avoid the SmartQuotes, but there are (at least) two ways to stop the SmartQuotes without needing to use literals:

    1. Disable SmartQuotes for the whole project:

    If you don't want SmartQuotes, either add:

    smartquotes = False
    

    to your conf.py file

    Or add a docutils.conf file at the same level as conf.py with this contents:

    [parsers]
    smart_quotes: no
    

    (solution from this GitHub issue; see the Sphinx documentation for how these two settings interact - TL;DR: switching off in docutils.conf will override even if they're turned on in conf.py)

    2. Escape the individual quotes you don't want to be 'smart':

    You can use double-backslashes \\ to escape the quote marks you want to be straight, eg \\' and \\". So in your example, this:

    "\\'hour\\'h" -> "hour 9"
    "ss\\'\\'SSS" -> "45\\'876"
    

    would give output of:

    “'hour'h” -> “hour 9”
    “ss''SSS” -> “45'876”
    

    with the outer double quotes left as 'smart', but I think that is the behaviour you wanted.

    (see the official docutils documentation for details on escaping)