Search code examples
python-sphinxrestructuredtext

Is it possible to reuse hyperlink defined in another file in restructuredtext (or sphinx)


Suppose I have two files a.rst and b.rst in the same folder, and a.rst looks like this

.. _foo: http://stackoverflow.com

`foo`_ is a website

It seems using foo in b.rst is not allowed. Is there a way to define hyperlinks and use them in multiple files?

Followup

I used the extlinks extension as Steve Piercy suggested. Its implementation and docstring can be seen here on github.

In my case, I define wikipedia link in my conf.py

extlinks = {'wiki': ('https://en.wikipedia.org/wiki/%s', '')}

and in the .rst files, use them like

:wiki:`Einstein <Albert_Einstein>`

where Einstein will be displayed as a link to https://en.wikipedia.org/wiki/Albert_Einstein


Solution

  • There are at least four possible solutions.

    1. repeat yourself

    Put your complete reST in each file. You probably don't want that.

    2. combined rst_epilog and substitution

    This one is clever. Configure the rst_epilog value, in your conf.py along with a substition with the replace directive:

    rst_epilog = """
    .. |foo| replace:: foo
    .. _foo: http://stackoverflow.com
    """
    

    and reST:

    |foo|_ is a website
    

    yields:

    <a class="reference external" href="http://stackoverflow.com">foo</a>
    

    3. extlinks

    For links to external websites where you want to have a base URL and append path segments or arguments, you can use extlinks in your conf.py:

    extensions = [
    ...
        'sphinx.ext.extlinks',
    ...
    ]
    ...
    extlinks = {'so': ('https://stackoverflow.com/%s', None)}
    

    Then in your reST:

    :so:`questions/49016433`
    

    Yields:

    <a class="reference external"
     href="https://stackoverflow.com/questions/49016433">
     https://stackoverflow.com/questions/49016433
    </a>
    

    4. intersphinx

    For external websites that are documentation generated by Sphinx, then you can use intersphinx, in your conf.py:

    extensions = [
    ...
        'sphinx.ext.intersphinx',
    ...
    ]
    ...
    intersphinx_mapping = {
        'python': ('https://docs.python.org/3', None),
    }
    

    Then in your reST:

    :py:mod:`doctest`
    

    Yields:

    <a class="reference external"
     href="https://docs.python.org/3/library/doctest.html#module-doctest"
     title="(in Python v3.6)">
        <code class="xref py py-mod docutils literal">
            <span class="pre">doctest</span>
        </code>
    </a>