Tips and Tricks

Here is a small collection of tips and tricks on how to use Sphinx and Hawkmoth for documenting C and C++ code.

Function Parameter Direction

Sphinx does not have a dedicated way of expressing the parameter direction similar to Doxygen @param[dir] command. One approach to emulate this is to define reStructuredText replacement texts, and use them.

For example:

conf.py
rst_prolog = '''
.. |in| replace:: **[in]**
.. |out| replace:: **[out]**
.. |in,out| replace:: **[in,out]**
'''
source code
/**
 * :param foo: |in| Foo parameter.
 */
void bar(char *foo);

By using replacement text, the direction stands out in the source code, you get warnings for typos, and you can modify the appearance across documentation in one place. Instead of **[in]**, you might use , or whatever you prefer.

Including Source Code Blocks

Doxygen has the @include and @snippet commands to include a source file or a fragment of one into documentation as a block of code.

The Sphinx alternative is literalinclude. The :start-after: and :end-before: options can be used to mimic the block_id of @snippet, but there’s plenty more.

.. literalinclude:: path/to/source.c
   :start-after: Adding a resource
   :end-before: Adding a resource

Using sphinx-autobuild with Hawkmoth

sphinx-autobuild is a handy tool to automatically rebuild Sphinx documentation when you modify the .rst files, with live-reload in the browser.

It’s possible to have it auto rebuild and live-reload source documentation on source code changes by adding --watch <source root> option to sphinx-autobuild, where <source root> matches hawkmoth_root.

Ad-hoc Sphinx Extension

If you need access to Sphinx internals to modify the behavior of Hawkmoth, or to write your own Sphinx extensions, you can just add def setup() to your conf.py configuration, and it will be loaded as an Ad-Hoc Sphinx Extension.

For example:

conf.py
def _process_docstring(app, lines, transform, options):
    pass # do something clever here

def setup(app):
    app.connect('hawkmoth-process-docstring', _process_docstring)

The setup() function will grant access to a Sphinx application context (sphinx.application.Sphinx) and can thus be used to adjust Sphinx to your needs.