From 7bf5fb5d923826ae49ee6bca8d89c0d5b113f669 Mon Sep 17 00:00:00 2001 From: omicron Date: Wed, 5 Aug 2026 00:51:30 +0200 Subject: [PATCH] refactor highlighting to use module level singletons remove the repeated instantiation of TextLexer and HtmlFormatter in favor of a singleton --- omicron/ssg/content.py | 22 ++++++++++++++++------ omicron/ssg/site.py | 3 ++- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/omicron/ssg/content.py b/omicron/ssg/content.py index f10b550..e69b772 100644 --- a/omicron/ssg/content.py +++ b/omicron/ssg/content.py @@ -15,6 +15,7 @@ from pygments import highlight as pygments_highlight from pygments.formatters import HtmlFormatter from pygments.lexers import get_lexer_by_name from pygments.lexers.special import TextLexer +from pygments.util import ClassNotFound log = logging.getLogger(__name__) @@ -26,12 +27,21 @@ class ContentError(RuntimeError): pass -def _highlight_code(code: str, lang: str, attrs: str) -> str: +text_lexer = TextLexer() +html_formatter = HtmlFormatter() + + +def highlight_style() -> str: + style = html_formatter.get_style_defs(".highlight") # type: ignore[no-untyped-call] + return cast(str, style) + + +def highlight(code: str, lang: str, attrs: str) -> str: try: - lexer = get_lexer_by_name(lang) if lang else TextLexer() - except Exception: - lexer = TextLexer() - return pygments_highlight(code, lexer, HtmlFormatter()) + lexer = get_lexer_by_name(lang) if lang else text_lexer + except ClassNotFound: + lexer = text_lexer + return pygments_highlight(code, lexer, html_formatter) def read_frontmatter(path: Path) -> dict[str, Any]: @@ -127,7 +137,7 @@ class Article(Content): def render(self, site: Site) -> None: md = MarkdownIt() - md.options["highlight"] = _highlight_code + md.options["highlight"] = highlight self.content = Markup(md.render(self.read_body())) template = site.jinja_env.get_template("article.html") diff --git a/omicron/ssg/site.py b/omicron/ssg/site.py index bbaea42..e5956c4 100644 --- a/omicron/ssg/site.py +++ b/omicron/ssg/site.py @@ -6,6 +6,7 @@ from omicron.ssg.content import ( create_content, CONTENT_EXTENSIONS, ContentError, + highlight_style, ) from pathlib import Path import yaml @@ -90,7 +91,7 @@ class Site: self.discover() self.output_path.mkdir(parents=True, exist_ok=True) (self.output_path / "pygments.css").write_text( - HtmlFormatter().get_style_defs(".highlight"), encoding="utf-8" + highlight_style(), encoding="utf-8" ) for content in self.content: content.render(self)