Debian Codegraph @

src/pydata_sphinx_theme/pygments.py

raw
1 """Handle Pygments css.
2
3 inspired by the Furo theme
4 https://github.com/pradyunsg/furo/blob/main/src/furo/__init__.py
5 """
6
7 from functools import partial
8 from pathlib import Path
9
10 from pygments.formatters import HtmlFormatter
11 from pygments.styles import get_all_styles
12 from sphinx.application import Sphinx
13
14 from .utils import get_theme_options_dict, maybe_warn
15
16
17 def _get_styles(formatter: HtmlFormatter, prefix: str) -> None:
18 """Get styles out of a formatter, where everything has the correct prefix."""
19 for line in formatter.get_linenos_style_defs():
20 yield f"{prefix} {line}"
21 yield from formatter.get_background_style_defs(prefix)
22 yield from formatter.get_token_style_defs(prefix)
23
24
25 def get_pygments_stylesheet(light_style: str, dark_style: str) -> str:
26 """Generate the theme-specific pygments.css.
27
28 There is no way to tell Sphinx how the theme handles modes.
29 """
30 light_formatter = HtmlFormatter(style=light_style)
31 dark_formatter = HtmlFormatter(style=dark_style)
32
33 lines = []
34
35 light_prefix = 'html[data-theme="light"] .highlight'
36 lines.extend(_get_styles(light_formatter, prefix=light_prefix))
37
38 dark_prefix = 'html[data-theme="dark"] .highlight'
39 lines.extend(_get_styles(dark_formatter, prefix=dark_prefix))
40
41 return "\n".join(lines)
42
43
44 def overwrite_pygments_css(app: Sphinx, exception=None):
45 """Overwrite pygments.css to allow dynamic light/dark switching.
46
47 Sphinx natively supports config variables `pygments_style` and
48 `pygments_dark_style`. However, quoting from
49 www.sphinx-doc.org/en/master/development/theming.html#creating-themes
50
51 The pygments_dark_style setting [...is used] when the CSS media query
52 (prefers-color-scheme: dark) evaluates to true.
53
54 This does not allow for dynamic switching by the user, so at build time we
55 overwrite the pygment.css file so that it embeds 2 versions:
56
57 - the light theme prefixed with "[data-theme="light"]"
58 - the dark theme prefixed with "[data-theme="dark"]"
59
60 Fallbacks are defined in this function in case the user-requested (or our
61 theme-specified) pygments theme is not available.
62 """
63 if exception is not None:
64 return
65
66 assert app.builder
67 theme_options = get_theme_options_dict(app)
68 warning = partial(maybe_warn, app)
69 pygments_styles = list(get_all_styles())
70 fallbacks = dict(light="tango", dark="monokai")
71
72 for light_or_dark, fallback in fallbacks.items():
73 # make sure our fallbacks work; if not fall(further)back to "default"
74 if fallback not in pygments_styles:
75 fallback = pygments_styles[0] # should resolve to "default"
76
77 # see if user specified a light/dark pygments theme:
78 style_key = f"pygments_{light_or_dark}_style"
79 style_name = theme_options.get(style_key, None)
80 # if not, use the one we set in `theme.conf`:
81 if style_name is None and hasattr(app.builder, "theme"):
82 style_name = app.builder.theme.get_options()[style_key]
83
84 # make sure we can load the style
85 if style_name not in pygments_styles:
86 # only warn if user asked for a highlight theme that we can't find
87 if style_name is not None:
88 warning(
89 f"Highlighting style {style_name} not found by pygments, "
90 f"falling back to {fallback}."
91 )
92 style_name = fallback
93
94 # assign to the appropriate variable
95 if light_or_dark == "light":
96 light_theme = style_name
97 else:
98 dark_theme = style_name
99
100 # re-write pygments.css
101 pygments_css = Path(app.builder.outdir) / "_static" / "pygments.css"
102 # Ensure the _static folder exists for all builders
103 pygments_css.parent.mkdir(exist_ok=True)
104 pygments_css.write_text(get_pygments_stylesheet(light_theme, dark_theme))