additional_samples_with_very_long_name

Various examples of styling applied to Sphinx constructs. You can view the source of this page to see the specific reStructuredText used to create these examples.

Headings

This is a second level heading (h2).

Sub-Heading

This is a third level heading (h3).

Sub-Sub-Heading

This is a fourth level heading (h4).

Code

The theme uses pygments for inline code text and

multiline
code text

Here’s an included example with line numbers.

  1"""MDAnalysis Sphinx theme."""
  2
  3import hashlib
  4import inspect
  5import os
  6import sys
  7from multiprocessing import Manager
  8from pathlib import Path
  9from typing import List, Optional
 10from xml.etree import ElementTree
 11
 12import bs4
 13import sass
 14import slugify
 15from bs4 import BeautifulSoup
 16from css_html_js_minify.html_minifier import html_minify
 17from sass import SassColor
 18from sphinx.util import console, logging
 19import sphinx
 20
 21from ._version import get_versions
 22
 23__version__ = get_versions()["version"]
 24del get_versions
 25
 26ROOT_SUFFIX = "--page-root"
 27
 28
 29def setup(app):
 30    """Setup connects events to the sitemap builder"""
 31    app.connect("build-finished", compile_css)
 32
 33    app.site_pages = []
 34    app.add_html_theme(
 35        "mdanalysis_sphinx_theme", html_theme_path()[0]
 36    )
 37    return {
 38        "version": __version__,
 39        "parallel_read_safe": True,
 40        "parallel_write_safe": True,
 41    }
 42
 43
 44def compile_css(app, exception):
 45    """Compile Bulma SASS into CSS"""
 46    if exception is not None:
 47        return
 48
 49    theme_path = Path(html_theme_path()[0])
 50    src = theme_path / "sass/site.sass"
 51    dest = Path(app.outdir) / "_static/site.css"
 52
 53    if not dest.parent.exists():
 54        return
 55
 56    accent_color = app.config["html_theme_options"].get(
 57        "color_accent", "mdanalysis-orange"
 58    )
 59    accent_color = {
 60        "mdanalysis-orange": (255, 146, 0),
 61        "openff-toolkit-blue": (47, 158, 210),
 62        "openff-dataset-yellow": (240, 133, 33),
 63        "openff-evaluator-orange": (240, 58, 33),
 64        "aquamarine": (44, 218, 157),
 65        "lilac": (228, 183, 229),
 66        "amaranth": (164, 14, 76),
 67        "grape": (171, 146, 191),
 68        "violet": (141, 107, 148),
 69        "pink": (238, 66, 102),
 70        "pale-green": (238, 66, 102),
 71        "green": (4, 231, 98),
 72        "crimson": (214, 40, 57),
 73        "eggplant": (117, 79, 91),
 74        "turquoise": (45, 225, 194),
 75    }.get(accent_color, accent_color)
 76
 77    if app.config["html_theme_options"].get("css_minify", False):
 78        output_style = "compressed"
 79        source_comments = False
 80    else:
 81        output_style = "expanded"
 82        source_comments = True
 83
 84    css = sass.compile(
 85        filename=str(src),
 86        output_style=output_style,
 87        custom_functions={
 88            "accent_color": lambda: SassColor(*accent_color, 1),
 89            "hyphenate": lambda: app.config["html_theme_options"].get(
 90                "html_hyphenate_and_justify", False
 91            ),
 92        },
 93    )
 94
 95    print(f"Writing compiled SASS to {console.colorize('blue', str(dest))}")
 96
 97    with open(dest, "w") as f:
 98        print(css, file=f)
 99
100
101def set_default_settings(app, config):
102    if not config.html_sidebars:
103        config.html_sidebars["**"] = [
104            "globaltoc.html",
105            "localtoc.html",
106            "searchbox.html",
107        ]
108    if config.html_permalinks_icon == "¶":
109        config.html_permalinks_icon = "<i class='fas fa-link'></i>"
110
111
112def html_theme_path():
113    return [os.path.dirname(os.path.abspath(__file__))]
114
115
116def ul_to_list(node: bs4.element.Tag, fix_root: bool, page_name: str) -> List[dict]:
117    out = []
118    for child in node.find_all("li", recursive=False):
119        if callable(child.isspace) and child.isspace():
120            continue
121        formatted = {}
122        if child.a is not None:
123            formatted["href"] = child.a["href"]
124            formatted["contents"] = "".join(map(str, child.a.contents))
125            if fix_root and formatted["href"] == "#" and child.a.contents:
126                slug = slugify.slugify(page_name) + ROOT_SUFFIX
127                formatted["href"] = "#" + slug
128            formatted["current"] = "current" in child.a.get("class", [])
129        if child.ul is not None:
130            formatted["children"] = ul_to_list(child.ul, fix_root, page_name)
131        else:
132            formatted["children"] = []
133        out.append(formatted)
134    return out
135
136
137def derender_toc(
138    toc_text, fix_root=True, page_name: str = "md-page-root--link"
139) -> List[dict]:
140    nodes = []
141    try:
142        toc = BeautifulSoup(toc_text, features="html.parser")
143        for child in toc.children:
144            if callable(child.isspace) and child.isspace():
145                continue
146            if child.name == "p":
147                nodes.append({"caption": "".join(map(str, child.contents))})
148            elif child.name == "ul":
149                nodes.extend(ul_to_list(child, fix_root, page_name))
150            else:
151                raise NotImplementedError
152    except Exception as exc:
153        logger = logging.getLogger(__name__)
154        logger.warning(
155            "Failed to process toctree_text\n" + str(exc) + "\n" + str(toc_text)
156        )
157
158    return nodes
159
160
161# These final lines exist to give sphinx a stable str representation of
162# this function across runs, and to ensure that the str changes
163# if the source does.
164derender_toc_src = inspect.getsource(derender_toc)
165derender_toc_hash = hashlib.sha512(derender_toc_src.encode()).hexdigest()
166
167
168class DerenderTocMeta(type):
169    def __repr__(self):
170        return f"derender_toc, hash: {derender_toc_hash}"
171
172    def __str__(self):
173        return f"derender_toc, hash: {derender_toc_hash}"
174
175
176class DerenderToc(object, metaclass=DerenderTocMeta):
177    def __new__(cls, *args, **kwargs):
178        return derender_toc(*args, **kwargs)
179
180
181def get_html_context():
182    return {"derender_toc": DerenderToc}

It also works with existing Sphinx highlighting:

<html>
  <body>Hello World</body>
</html>
def hello():
    """Greet."""
    return "Hello World"
/**
 * Greet.
 */
function hello(): {
  return "Hello World";
}

Admonitions

The theme uses the admonition classes for the standard Sphinx admonitions.

Warning

Warning

This is a warning.

Attention

Attention

Do I have your attention?

Caution

Caution

Use caution!

Danger

Danger

This is danger-ous.

Error

Error

You have made a grave error.

Hint

Hint

Can you take a hint?

Important

Important

It is important to correctly use admonitions.

Note

Note

This is a note.

Tip

Tip

Please tip your waiter.

Deprecated

Deprecated since version 999.999.999: This API point was deprecated.

Todo

Todo

This is something we are yet to do.

Custom Admonitions

An admonition of my own making

You can create your own admonitions with the accent color.

Example

But lots of custom admonition styles are also defined.

Quote

The needs of the many outweigh the needs of the few

Bug

Bugs weren’t always a metaphor

Success

Woohoo!

Experimental

Experiments are the heart of science

Footnotes

I have footnoted a first item [1] and second item [2]. This also references the second item [2].

Footnotes

Icons

Font Awesome and Academicons are both available:

<i class="fa fa-camera-retro fa-lg"></i>
<i class="fa fa-camera-retro fa-2x"></i>
<i class="fa fa-camera-retro fa-3x"></i>
<i class="fa fa-camera-retro fa-4x"></i>
<i class="fa fa-camera-retro fa-5x"></i>
<i class="ai ai-google-scholar-square ai-3x"></i>
<i class="ai ai-zenodo ai-3x" style="color: red"></i>

Tables

Here are some examples of Sphinx tables.

Grid

A grid table:

Header1

Header2

Header3

Header4

row1, cell1

cell2

cell3

cell4

row2 …

Simple

A simple table:

H1

H2

H3

cell1

cell2

cell3

List Tables

A List Table

Column 1

Column 2

Item 1

Item 2

50% width list table

One fifth width column

Four fifths width column

Item 1

Item 2

Alignment

Left Aligned

Column 1

Column 2

Item 1

Item 2

Center Aligned

Column 1

Column 2

Item 1

Item 2

Right Aligned

Treat

Quantity

Albatross

2.99

Crunchy Frog

1.49

Gannet Ripple

1.99

Code Documentation

An example Python function.

format_exception(etype, value, tb[, limit=None])

Format the exception with a traceback.

Parameters:
  • etype – exception type

  • value – exception value

  • tb – traceback object

  • limit (integer or None) – maximum number of stack frames to show

Return type:

list of strings

An example JavaScript function.

class MyAnimal(name[, age])
Arguments:
  • name (string()) – The name of the animal

  • age (number()) – an optional age for the animal

Glossaries

environment

A structure where information about all documents under the root is saved, and used for cross-referencing. The environment is pickled after the parsing stage, so that successive runs only need to read and parse new and changed documents.

source directory

The directory which, including its subdirectories, contains all source files for one Sphinx project.

Math

\[ \begin{align}\begin{aligned}(a + b)^2 = a^2 + 2ab + b^2\\(a - b)^2 = a^2 - 2ab + b^2\end{aligned}\end{align} \]
\[\begin{split}(a + b)^2 &= (a + b)(a + b) \\ &= a^2 + 2ab + b^2\end{split}\]
\begin{eqnarray} y & = & ax^2 + bx + c \\ f(x) & = & x^2 + 2xy + y^2 \end{eqnarray}

Production Lists

try_stmt  ::=  try1_stmt | try2_stmt
try1_stmt ::=  "try" ":" suite
               ("except" [expression ["," target]] ":" suite)+
               ["else" ":" suite]
               ["finally" ":" suite]
try2_stmt ::=  "try" ":" suite
               "finally" ":" suite