From 2befc94f859622d7c736d3005cf1feaf955eaf05 Mon Sep 17 00:00:00 2001 From: Federico Capoano Date: Tue, 16 Jun 2026 15:28:51 -0300 Subject: [PATCH] [fix] Made dark syntax highlighting follow the theme toggle Sphinx 9 and sphinxawesome-theme 6 gate the dark Pygments palette on `@media (prefers-color-scheme: dark)`, both in the block appended to pygments.css and in the separately media-linked pygments_dark.css. The theme, however, toggles dark mode with a `.dark` class on that is persisted in localStorage and can diverge from the OS preference (for example the site is kept dark while the OS turns light at dawn). The code blocks therefore switched palette independently of the rest of the page, producing low-contrast, unreadable syntax highlighting. Re-scope the dark palette under `.dark` so the syntax colors track the same toggle as the rest of the theme. --- conf.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/conf.py b/conf.py index 6bab602c..31d10b72 100644 --- a/conf.py +++ b/conf.py @@ -508,10 +508,13 @@ def write_pygments_dark_css(app, exception): - """Write the dark Pygments stylesheet expected by Sphinx 9. + """Re-scope the dark Pygments palette under the theme's `.dark` class. - sphinxawesome-theme appends dark styles to pygments.css, but Sphinx 9 - links pygments_dark.css separately when a dark Pygments style is set. + Runs on ``build-finished`` for HTML builds: drops the + ``@media (prefers-color-scheme: dark)`` block from ``pygments.css`` so only + the light palette remains, then appends the dark palette scoped under + ``.dark .highlight``. The separately linked ``pygments_dark.css`` is emptied + so it cannot apply the dark palette on its own. """ if exception or app.builder.format != "html": return @@ -520,9 +523,16 @@ def write_pygments_dark_css(app, exception): return static_dir = Path(app.outdir) / "_static" static_dir.mkdir(exist_ok=True) - (static_dir / "pygments_dark.css").write_text( - dark_highlighter.get_stylesheet(), encoding="utf-8" - ) + pygments_css = static_dir / "pygments.css" + if not pygments_css.exists(): + return + light = pygments_css.read_text(encoding="utf-8") + light = light.split("@media (prefers-color-scheme: dark)", 1)[0].rstrip() + dark = dark_highlighter.get_formatter().get_style_defs(".dark .highlight") + pygments_css.write_text(light + "\n" + dark + "\n", encoding="utf-8") + # Neutralize the separately media-linked dark stylesheet so it cannot apply + # the dark palette based on the OS preference. + (static_dir / "pygments_dark.css").write_text("", encoding="utf-8") def setup(app):