Is there any API for formatting Sphinx text?
Question: I want to use Sphinx text converting in my Python program. For example, I have
a `string` variable which contains this text:

    
    
    .. note::
    
       This is a note.
    
    .. code-block:: ruby
    
       Some Ruby code.
    

and I want to call `magic_convert_function(string)` that will produce a HTML
string like this one:

    
    
    <p class="note">This is a note.</p>
    <p><code class="ruby">Some ruby code.</code></p>
    

Is there any such function in Sphinx API?

Note that I am not satisfied with "pure" reStructuredText, I want to use some
Sphinx-specific language features.


Answer: I'm not sure about the Sphinx API, but since Sphinx is just built on top on
[Docutils](http://docutils.sourceforge.net/), which has a very well documented
API you can try and use and extend this. As a quick example, to get an XML
representation of some string of reStructuredText you could do something like:

    
    
    from docutils.core import publish_doctree
    
    source = """Test
    ====
    
    .. note::
        This is a note.
    
    This is just a paragraph.
    """
    
    # Parse reStructuredText input, returning the Docutils doctree as
    # an `xml.dom.minidom.Document` instance.
    doctree = publish_doctree(source).asdom()
    
    print doctree.toprettyxml()
    

The result of this is:

    
    
    <?xml version="1.0" ?>
    <document ids="test" names="test" source="&lt;string&gt;" title="Test">
    <title>
        Test
    </title>
    <note>
        <paragraph>
            This is a note.
        </paragraph>
    </note>
        <paragraph>
            This is just a paragraph.
        </paragraph>
    </document>
    

Now in my version of Docutils, 0.8, there is no `code-block` directive.
However, this is meant to be included in later versions and Sphinx in fact
extends Docutils to include this. So you can:

  * see how Sphinx does this;
  * get a later version of Docutils;
  * use the experimental code-block implementation in the [Docuitls sandbox](http://docutils.sourceforge.net/sandbox/code-block-directive/) (this has examples of how to use this code);
  * [write you own directive](http://docutils.sourceforge.net/docs/howto/rst-directives.html).

Note, here I have used `docutils.core.publish_doctree` to get an XML
representation of the reStructuredText source. If you just want the HTML you
can use the HTML writer with
[`docutils.core.publish_parts`](http://docutils.sourceforge.net/docs/api/publisher.html#publish-
parts-details) like so:

    
    
    from docutils.core import publish_parts
    
    source = ...as above...
    
    document = publish_parts(source, writer_name='html')
    
    print document['body']
    

which results in

    
    
    <div class="note">
        <p class="first admonition-title">Note</p>
        <p class="last">This is a note.</p>
    </div>
    <p>This is just a paragraph.</p>
    

