Installation¶
Getting Started¶
Install sphinxcontrib-viewsource using pip.
pip install sphinxcontrib-viewsource
Add the extension to your Sphinx project
conf.py
file.
extensions = ['sphinxcontrib.viewsource']
Define a caption text and link resolution function at the end of your
conf.py
file:
viewsource_title = 'Edit on GitHub'
def viewsource_resolve_link(file_path, language=None):
base_url = 'https://github.com/dgarcia360/sphinxcontrib-viewsource/blob/master/docs/snippets/'
# get the name of the file
path_split = file_path.split('/')
file = path_split[len(path_split)-1]
return base_url + file
Find here other link resolution examples.
Use
viewsource
directive instead ofliteralinclude
when rendering code:
.. viewsource:: snippets/hello.py
:language: python
:lines: 2
The viewsource
extends from literalinclude
, so you can still use all the directive options.
Note
The directive overwrites the caption
option with the specified link. If you set the caption option, the extension will not render the link.
You can apply custom CSS to style the caption:
.code-block-caption .caption-text > a {
float: right;
}
Build the docs.