In Sphinx, can I register a bunch of keywords that should always be translated into links?

python, python-sphinx

Solution

You can use macros.

In my project, I have a header file that contains all "important" classes and global functions and their abbreviation. Two example lines:

.. |PostItem| replace:: :class:`PostItem <hklib.PostItem>`
.. |PostNotFoundError| replace:: :class:`PostNotFoundError <hklib.PostNotFoundError>`

In my `rst` files, I include this header file. Then I can use the macros in any `rst` file:

.. include:: defs.hrst

|PostItem| is a nice class. |PostNotFoundError|, on the other hand is not.

(You can include docstrings from Python source files as well, using the `autogen` extension. Macros in those will be replaced as well.)

About your example: I would add `Foo` to the header file and write the docstring this way:

'''This class contains a bunch of |Foo| objects'''

Problem

My doc strings have references to other python classes that I've defined. Every time Sphinx encounters one of these classes, I want it to insert a link to the documentation for that other class. Is this possible in Sphinx? Specifically, I have a doc string like: ``` '''This class contains a bunch of Foo objects''' ``` I could write: ``` '''This class contains a bunch of :class:`~foo.Foo` objects''' ``` but I would prefer that Sphinx finds all text matching `Foo` and makes it seem as though I had typed :class:`~foo.Foo`

Original source