Search code examples
pythonrestructuredtextdocutils

Parse and write RST using docutils


Are there any writers available that will output reStructuredText? I thought the "null" writer might be for this purpose but it produces no output.

My use case is to parse an existing RST file, modify the document tree in Python (e.g. to automatically update directives), and then output the tree back to RST.

HTML can be output as below. For RST output would I need to write a custom Writer to do this?

    import docutils.core
    import docutils.parsers.rst
    from docutils.writers import null
    import docutils.writers.html5_polyglot

    txt = """
    Title
    =====

    .. meta::
       :description: The reStructuredText plaintext markup language
       :keywords: plaintext, markup language

    """

    output = docutils.core.publish_string(
                source=txt,
                parser=docutils.parsers.rst.Parser(),
                #writer_name="null", # docutils_xml
                #writer= docutils.writers.null.Writer()
                writer=docutils.writers.html5_polyglot.Writer()
                )

    print(output)

Solution

  • Yes, a Sphinx extension called sphinxcontrib.restbuilder at https://github.com/sphinx-contrib/restbuilder

    Disclaimer: I started this code in 2014, but only recently it gained some traction that it starts getting reliable. Contributions are most appreciated.