Last active
March 20, 2023 21:06
DOI role for Sphinx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
doilinks | |
~~~~~~~~~~~~~~~~~~~ | |
Extension to add links to DOIs. With this extension you can use e.g. | |
:doi:`10.1016/S0022-2836(05)80360-2` in your documents. This will | |
create a link to a DOI resolver | |
(``https://doi.org/10.1016/S0022-2836(05)80360-2``). | |
The link caption will be the raw DOI. | |
You can also give an explicit caption, e.g. | |
:doi:`Basic local alignment search tool <10.1016/S0022-2836(05)80360-2>`. | |
:copyright: Copyright 2015 Jon Lund Steffensen. Based on extlinks by | |
the Sphinx team. | |
:license: BSD. | |
""" | |
from docutils import nodes, utils | |
from sphinx.util.nodes import split_explicit_title | |
def doi_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): | |
text = utils.unescape(text) | |
has_explicit_title, title, part = split_explicit_title(text) | |
full_url = 'https://doi.org/' + part | |
if not has_explicit_title: | |
title = 'doi:' + part | |
pnode = nodes.reference(title, title, internal=False, refuri=full_url) | |
return [pnode], [] | |
def setup_link_role(app): | |
app.add_role('doi', doi_role) | |
def setup(app): | |
app.connect('builder-inited', setup_link_role) | |
return {'version': '0.1', 'parallel_read_safe': True} |
how does this differ from using the builtin extlink
extension and defining the following in conf.py
:
extlinks = {
'doi': ('https://dx.doi.org/%s', 'doi:'),
}
@mikofski That seems like a much better solution. Also requires adding
extensions = [
'sphinx.ext.extlinks',
…
It produces this though:
WARNING: extlinks: Sphinx-6.0 will require a caption string to contain exactly one '%s' and all other '%' need to be escaped as '%%'.
Oh I get it. You need to change it to
extlinks = {
'doi': ('https://dx.doi.org/%s', 'doi:%s'),
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @jonls, thanks for the gist!
I just wanted to draw your attention to scipy/scipy#6650 which proposes to add DOI roles to SciPy documentation. I took liberty to copy-paste your gist, interpreting your BSD license note literally --- is it OK with you? Also, I'm happy to change the author info on the copy-paste commit (scipy/scipy@1ee4203), so that you're fully credited in our git logs.