Substitutions inside Sphinx code blocks aren't replaced
Asked Answered
C

2

31

In this reST example meant to be rendered by Sphinx, |yaco_url| doesn't get replaced because it's in a code-block:

.. |yaco_url| replace:: http://yaco.es/

You can use wget to download it:

.. code-block:: console

    $ wget |yaco_url|package.tar.gz

I wonder if there is some way to force the replacement of |yaco_url| before rendering the code block.

Cataclinal answered 11/1, 2012 at 15:5 Comment(4)
This question is almost the same but doesn't work inside code blocks: #1227537Cataclinal
Hey - did you find an answer to this?Goulet
No, I didn't. In the end I had to replace all |yaco_url| with a sed command.Cataclinal
If you haven't found it already, you might find the programoutput extension handy: packages.python.org/sphinxcontrib-programoutputHilly
S
24

Use the "parsed-literal" directive.

.. parsed-literal::

    ./home/user/somecommand-|version|

Source: https://groups.google.com/forum/?fromgroups=#!topic/sphinx-dev/ABzaUiCfO_8:

Subrogation answered 28/9, 2012 at 17:17 Comment(3)
This is close to my needs, though I'm still struggling with then treating the result as a code block, for proper formatting.Bierce
@HowardM.LewisShip I'm struggling with the same issue. did you find a solution?Afebrile
No, I never did.Bierce
C
8

Found a better solution (in my opinion), that can be used in others directives like :samp: and might be useful for future readers.

config.py:

def ultimateReplace(app, docname, source):
    result = source[0]
    for key in app.config.ultimate_replacements:
        result = result.replace(key, app.config.ultimate_replacements[key])
    source[0] = result

ultimate_replacements = {
    "{TEST}" : "replaced"
}

def setup(app):
   app.add_config_value('ultimate_replacements', {}, True)
   app.connect('source-read', ultimateReplace)

And this kind of markup:

.. http:get:: testing/replacement/{TEST}

Properly generates like:

testing/replacement/replaced

Note, that if using this to replace an argument in the :samp: directive, a double bracket { is require.

:samp:`func({{TEST}})`.

source: https://github.com/sphinx-doc/sphinx/issues/4054

Cort answered 27/5, 2019 at 15:0 Comment(2)
Nice! This worked well rather than the accepted answer as I still wasn't able to do a replace in a code block where I needed formatting.Onaonager
This works great in code-block, but I discovered that it will not work where the code-block is within an include. However it appears that Sphinx 7.2.5 added a new event include-read that might handle this situation. Alas, we're stuck on an older version for now.Aspire

© 2022 - 2024 — McMap. All rights reserved.