Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline Code Link in Sphinx + reStructuredText

In Markdown, one can create an inline code link like so

[`dict.update`](https://docs.python.org/3/library/stdtypes.html#dict.update)

Which renders like dict.update. How can get a similar behaviour in reStructuredText / Sphinx? I tried (1) using a converter but it never results in something similar (2) nesting external link `link <link>`_ and inline code block :code:`dict.update`, but that din't work either.

like image 797
Hyperplane Avatar asked Apr 28 '26 18:04

Hyperplane


2 Answers

The right way to do this is using the sphinx.ext.intersphinx extension.

In your conf.py add

extensions = [
    'sphinx.ext.intersphinx',  # the last entry does not use a comma.
    # 'sphinx.ext.autodoc',  # just for example so there is more than 1 line.
]


intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}

# If you having an `objects.inv` for local builds
# intersphinx_mapping = {"python": ("https://docs.python.org/3", 'objects.inv'),}

Then in your .rst file or in the docstrings in the .py files write a simple cross-reference. Notice that dict.update is a method thus the right role (:py:meth:) should be used when cross-referencing. The following example

A simple text to :meth:`dict.update`

Would give the below HTML output (the tooltip and link of the cross-reference also included in the screenshot)

enter image description here

like image 181
bad_coder Avatar answered May 01 '26 06:05

bad_coder


The answer of @bad_coder works perfect when referencing roles of codes from other documentation (like :meth:, :class:, etc.)

If anyone would like to create an inline code link to an arbitrary hyperlink, I solved my situation with the sphinx comborole extension.

In particular using it toghether with extlinks extension.

like image 23
Diogo Avatar answered May 01 '26 07:05

Diogo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!