sphinxcontrib-viewsource

Add an “Edit on GitHub” button to your code examples.

sphinxcontrib-viewsource is a Sphinx extension that enhances the literalinclude directive, adding a caption automatically with a link pointing to the source file.

Use it to add an Edit on GitHub button to your code source files, or to show the complete code when the literalinclude directive renders a subset of the file.

Example

    print('Hello World!')

Add the extension to your project following the installation instructions.

Installation

Getting Started

  1. Install sphinxcontrib-viewsource using pip.
pip install sphinxcontrib-viewsource
  1. Add the extension to your Sphinx project conf.py file.
extensions = ['sphinxcontrib.viewsource']
  1. 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.

  1. Use viewsource directive instead of literalinclude 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.

  1. You can apply custom CSS to style the caption:
.code-block-caption .caption-text > a {
  float: right;
}
  1. Build the docs.

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[0.1.3] - 18 April 2019

Added

  • Initial code release