Resolve Substitutions in RestructuredText
Question: I want to take the following restructured text snippet that contains a
[substitution
definition](http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#substitution-
definitions):

    
    
    text = """
    
    |python|
    
    .. |python| image:: python.jpg
    """
    

And resolve the definitions so the substitution text is displayed:

    
    
    resolved_text = """
    .. image:: python.jpg
    
    """
    

Is there a function or utility in docutils or another module that can do this?


Answer: `docutils` provides [publisher
functions](http://docutils.sourceforge.net/docs/api/publisher.html#publisher-
convenience-functions) to use docutils as a library.

So using `docutils.core.publish_string` could be an option for your usecase.

    
    
    In [90]: from docutils import core
    
    In [91]: text = '|python|\n\n.. |python| image:: python.jpg\n'
    
    In [92]: print core.publish_string(text)
    <document source="<string>">
        <paragraph>
            <image alt="python" uri="python.jpg">
        <substitution_definition names="python">
            <image alt="python" uri="python.jpg">
    

By default `puplish_string` uses a `pseudoxml` writer, which you can see in
the output. However if you really want to have the plain text output from your
question, you need a custom writer class derived from
`docutils.writers.Writer`. I'm not sure how to implement this, maybe the
`Sphinx`
[TextWriter](https://bitbucket.org/birkenfeld/sphinx/src/8ec0b3a74e791e59dfee2d484380c34881530a89/sphinx/writers/text.py?at=default#cl-133)
could be a starting point.

Seems that if you really only need the simple substitution, using `replace` on
your text would be a simpler solution, if you need more complicated things,
implement this using docutils is complicated, too.

