Inline Code Link in Sphinx + reStructuredText
Asked Answered
Q

2

10

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.

Quathlamba answered 11/5, 2021 at 9:57 Comment(0)
D
7

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

Ditch answered 11/5, 2021 at 11:25 Comment(1)
Thanks, this is perfect!Quathlamba
H
2

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.

Hispanicism answered 15/2, 2024 at 20:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.