Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Sphinx anchor on arbitrary line

How can I set an anchor reference at an arbitrary line in ReST using Sphinx?

To be more clear, here is an example:

A title with an anchor
----------------------

some stuff

this will create a heading A title with an anchor and add an extra on-hover character at the end of the line, which will be an anchor reference to that line/heading.

Now in the following case...

``some arbitrary line``
    this is actually a definition

...I want to have an anchor for some arbitrary line, the same way as for the heading.

like image 937
bagrat Avatar asked Jun 13 '15 19:06

bagrat


1 Answers

You can do this with a role called ref: https://www.sphinx-doc.org/en/master/usage/restructuredtext/roles.html#role-ref

Specifically read the 2nd bullet point which addresses what happens if the reference is not placed before a title.

For example, in a file called example.rst this is how you would use:

.. _arbitrary-anchor:

Some Arbitrary Line
    This is actually a definition

The label "arbitrary-anchor" has to be unique through out the document. To reference this anchor somewhere in the document, you would do something like this:

Lorem ipsum :ref:`here is the anchor link <arbitrary-anchor>` dolor sit amet

Unfortunately, this anchor will not show up when you hover over the referenced line, but you should be able to access it using an explicit link to http://example.com/example.html#arbitrary-anchor


Since you mention definitions - it is also worth noting that there is a role called term which lets you reference a definition in the glossary.

For an example of how to use this, see: http://sphinx-doc.org/glossary.html#term-role

and how this is referenced in the 3rd paragraph of: http://sphinx-doc.org/domains.html#domains


Lastly, if you need to insert an anchor in the middle of a paragraph, one way to do it is by creating an explicit <a id=#sample>inline anchor</a> by using a raw role: http://docutils.sourceforge.net/docs/ref/rst/roles.html#raw


EDIT:

There is one more option. This will create an anchor and the hover effect.

.. rst:role:: Sample rst role

    This is a sample definition which links back to its anchor :rst:role:`Sample rst role`

This is a funny looking directive that I've been using for a while now. I found it when I was looking at the source of this page:

http://sphinx-doc.org/markup/inline.html#inline-markup

http://sphinx-doc.org/_sources/markup/inline.txt

The text looks like this when you hover: enter image description here

The text looks like this after you click on the link: enter image description here

This option is less that ideal because it displays the : to the left and right of the definition. But it is nice because it creates an anchor and hover on something that's not a title (so it doesn't show up in the TOC as well, which is exactly what I wanted)

like image 102
Subbdue Avatar answered Sep 23 '22 02:09

Subbdue