bheklilr
bheklilr

Reputation: 54058

How to convert one Sphinx role to another?

I am documenting a set of projects using Sphinx that benefits greatly from the intersphinx extension. Essentially, there are about 3 utility projects that feed into a larger one, and in the larger project I need to reference the documentation from the smaller ones. I have intersphinx set up as

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.intersphinx',
    ...
]

intersphinx_mapping = {
    'project1': ('http://internal.url/to/project1/latest', None),
    'project2': ('http://internal.url/to/project2/latest', None),
    'project3': ('http://internal.url/to/project3/latest', None),
}

This lets me use intersphinx normally:

:any:`project1.Class1`

Which gets rendered as a link with the text project1.Class1. I would rather it use the unqualified name, though, so I end up writing

:any:`Class1 <project1.Class1>`

a lot. This is annoying. I would really like to set up a handful of roles so that I could do

* :p1:`Class1` is from ``project1``
* :p2:`Class2` is from ``project2``
* :p3:`function1` is from ``project3``

where :p1:`{text}` is replaced by :any:`{text} <project1.{text}>`, etc.

Is there an easy way to do this? All of my searches have come up with pretty useless information and the source code for the intersphinx is pretty hard to read. Ideally there would be some way for me to just do

def p1_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    return sphinx.some_module.parse(':any:`{0} <project1.{0}>`'.format(text))

def setup(app):
    app.add_role('p1', p1_role)

would be the best, but I don't know if that is available anywhere.

Upvotes: 3

Views: 103

Answers (1)

Steve Piercy
Steve Piercy

Reputation: 15055

Under the third bullet point of Cross-referencing syntax:

If you prefix the content with ~, the link text will only be the last component of the target. For example:

:py:meth:`~Queue.Queue.get`

will refer to Queue.Queue.get but only display get as the link text.

It works with class, func, meth, and attr, and possibly any (I could not get it to work with any).

Following the pattern, try this:

:class:`~project1.Class1`

I just ran a test in Pyramid and WebOb, and this worked:

:class:`~webob.request.Request`

Only the text Request displayed and linked to the WebOb API.

Upvotes: 3

Related Questions