Is there a reST Writer?
Asked Answered
H

1

6

Is there a reST Writer for docutil.nodes trees? I couldn't find one but maybe I'm missing something obvious. Or is it trivial to write one yourself? I want to implement reST-to-reST transformations.

Hematite answered 10/12, 2012 at 15:50 Comment(0)
A
5

There is none, and it is hard, if not impossible to implement one beyond trivial ReST markup.

ReST roles and directives may execute arbitrary code at parse time. Particularly a role or directive can create and insert nodes of arbitrary types with arbitrary content into the document tree. Thus there is no direct mapping between a document tree and ReST source code and consequently it is impossible to obtain the original ReST source code – or at least something that comes close – for an arbitrary document tree.

A real world example are various directives from Sphinx, e.g. py:class. These directives insert pending_xref nodes into the document tree which are resolved into real cross-references at a later point of time. However, there is no single directive that corresponds to a pending_xref node thus there is no ReST source that directly corresponds to a document tree containing such nodes.

One can implement a writer for simple standard ReST markup, i.e. headlines, paragraphs, emphasis, and the like. I do not know of any implementation but that is trivial to do on yourself. That may or may not be enough for your purposes.

If your documents contain roles, directives or substitutions complete ReST-to-ReST transformations are impossible. However, you can sort-of cheat by unregistering all roles and directives first, and then registering a function that catches all roles and directives and preserves them literally in the document tree. Based on such a tree, you can restore the source (or at least get close to this). Substitutions however are lost, because these are applied at an early stage of parsing and do not appear in the resulting tree.

Accentor answered 10/12, 2012 at 16:38 Comment(1)
While it is impossible to restore the original rST source due to information loss during the rST -> doctree conversion, it is possible to create rST output from a doctree that would result in the same doctree when parsed with an rST parser again. Such an "rST writer" for is a longstanding Docutils TODO item. There is a contributed rST writer in the sandbox but it is unfortunately outdated and unmaintained.Shirline

© 2022 - 2024 — McMap. All rights reserved.