Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve Substitutions in RestructuredText

I want to take the following restructured text snippet that contains a substitution definition:

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?

like image 613
geographika Avatar asked Mar 09 '13 15:03

geographika


2 Answers

docutils provides publisher 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 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.

like image 93
bmu Avatar answered Sep 27 '22 21:09

bmu


Have a look at the Docutils Hacker's Guide. It explains how docutils works.

You might get away with applying an appropriate Transform to the node tree that is generated by parsing the input file. After applying the transform you should use a Writer object to output ReStructuredText again. This writer doesn't exist yet, so you'd have to create that first.

like image 25
Roland Smith Avatar answered Sep 27 '22 21:09

Roland Smith