Ryan
Ryan

Reputation: 10169

How to add link to source code in Sphinx

enter image description here

class torch.FloatStorage[source]
    byte()
        Casts this storage to byte type
    char()
        Casts this storage to char type

Im trying to get some documentation done, i have managed to to get the format like the one shown above, But im not sure how to give that link of source code which is at the end of that function! The link takes the person to the file which contains the code,But im not sure how to do it,

Upvotes: 8

Views: 4244

Answers (2)

dsz
dsz

Reputation: 5212

I'd recommend looking at the linkcode extension too. Allows you to build a full HTTP link to the code on GitHub or such like. This is sometimes a better option that including the code within the documentation itself. (E.g. may have stronger permission on it than the docs themselves.)

You write a little helper function in your conf.py file, and it does the rest.

What I really like about linkcode is that it creates links for enums, enum values, and data elements, which I could not get to be linked with viewcode.

I extended the link building code to use #:~:text= to cause the linked-to page to scroll to the text. Not perfect, as it will only scroll to the first instance, which may not always be correct, but likely 80~90% of the time it will be.

from urllib.parse import quote

def linkcode_resolve(domain, info):
    # print(f"domain={domain}, info={info}")
    if domain != 'py':
        return None
    if not info['module']:
        return None
    filename = quote(info['module'].replace('.', '/'))
    if not filename.startswith("tests"):
        filename = "src/" + filename
    if "fullname" in info:
        anchor = info["fullname"]
        anchor = "#:~:text=" + quote(anchor.split(".")[-1])
    else:
        anchor = ""

    # github
    result = "https://<github>/<user>/<repo>/blob/master/%s.py%s" % (filename, anchor)
    # print(result)
    return result

Upvotes: 1

Pierre de Buyl
Pierre de Buyl

Reputation: 7293

This is achieved thanks to one of the builtin sphinx extension.

The one you are looking for in spinx.ext.viewcode. To enable it, add the string 'sphinx.ext.viewcode' to the list extensions in your conf.py file.

In summary, you should see something like that in conf.py

extensions = [
    # other extensions that you might already use
    # ...
    'sphinx.ext.viewcode',
]

Upvotes: 13

Related Questions