From df008464cca9296a25be4d5ab7ef131a35dc1d24 Mon Sep 17 00:00:00 2001 From: Hanjin Liu <40591297+hanjinliu@users.noreply.github.com> Date: Sun, 15 Dec 2024 02:37:17 +0900 Subject: [PATCH] Fix KeyError in CodeSyntaxHighlight (#258) * use dict.get * typing * Update src/superqt/utils/_code_syntax_highlight.py Co-authored-by: Grzegorz Bokota --------- Co-authored-by: Talley Lambert Co-authored-by: Grzegorz Bokota --- src/superqt/utils/_code_syntax_highlight.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/superqt/utils/_code_syntax_highlight.py b/src/superqt/utils/_code_syntax_highlight.py index d990f8a1..73f2ef15 100644 --- a/src/superqt/utils/_code_syntax_highlight.py +++ b/src/superqt/utils/_code_syntax_highlight.py @@ -9,7 +9,9 @@ # https://pygments.org/docs/formatterdevelopment/#html-3-2-formatter -def get_text_char_format(style): +def get_text_char_format( + style: dict[str, QtGui.QTextCharFormat], +) -> QtGui.QTextCharFormat: text_char_format = QtGui.QTextCharFormat() if hasattr(text_char_format, "setFontFamilies"): text_char_format.setFontFamilies(["monospace"]) @@ -36,7 +38,7 @@ def get_text_char_format(style): class QFormatter(Formatter): def __init__(self, **kwargs): super().__init__(**kwargs) - self.data = [] + self.data: list[QtGui.QTextCharFormat] = [] self._style = {name: get_text_char_format(style) for name, style in self.style} def format(self, tokensource, outfile): @@ -49,7 +51,11 @@ def format(self, tokensource, outfile): self.data = [] for token, value in tokensource: - self.data.extend([self._style[token]] * len(value)) + # using get method to workaround not defined style for plain token + # https://github.com/pygments/pygments/issues/2149 + self.data.extend( + [self._style.get(token, QtGui.QTextCharFormat())] * len(value) + ) class CodeSyntaxHighlight(QtGui.QSyntaxHighlighter):