Skip to content

Commit 850d9d7

Browse files
committed
[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 <html> 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.
1 parent 8edf7ab commit 850d9d7

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

conf.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -508,10 +508,13 @@
508508

509509

510510
def write_pygments_dark_css(app, exception):
511-
"""Write the dark Pygments stylesheet expected by Sphinx 9.
511+
"""Re-scope the dark Pygments palette under the theme's `.dark` class.
512512
513-
sphinxawesome-theme appends dark styles to pygments.css, but Sphinx 9
514-
links pygments_dark.css separately when a dark Pygments style is set.
513+
Runs on ``build-finished`` for HTML builds: drops the
514+
``@media (prefers-color-scheme: dark)`` block from ``pygments.css`` so only
515+
the light palette remains, then appends the dark palette scoped under
516+
``.dark .highlight``. The separately linked ``pygments_dark.css`` is emptied
517+
so it cannot apply the dark palette on its own.
515518
"""
516519
if exception or app.builder.format != "html":
517520
return
@@ -520,9 +523,14 @@ def write_pygments_dark_css(app, exception):
520523
return
521524
static_dir = Path(app.outdir) / "_static"
522525
static_dir.mkdir(exist_ok=True)
523-
(static_dir / "pygments_dark.css").write_text(
524-
dark_highlighter.get_stylesheet(), encoding="utf-8"
525-
)
526+
pygments_css = static_dir / "pygments.css"
527+
light = pygments_css.read_text(encoding="utf-8")
528+
light = light.split("@media (prefers-color-scheme: dark)", 1)[0].rstrip()
529+
dark = dark_highlighter.get_formatter().get_style_defs(".dark .highlight")
530+
pygments_css.write_text(light + "\n" + dark + "\n", encoding="utf-8")
531+
# Neutralize the separately media-linked dark stylesheet so it cannot apply
532+
# the dark palette based on the OS preference.
533+
(static_dir / "pygments_dark.css").write_text("", encoding="utf-8")
526534

527535

528536
def setup(app):

0 commit comments

Comments
 (0)