Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top