Skip to content

Commit

Permalink
Fix KeyError in CodeSyntaxHighlight (#258)
Browse files Browse the repository at this point in the history
* use dict.get

* typing

* Update src/superqt/utils/_code_syntax_highlight.py

Co-authored-by: Grzegorz Bokota <[email protected]>

---------

Co-authored-by: Talley Lambert <[email protected]>
Co-authored-by: Grzegorz Bokota <[email protected]>
  • Loading branch information
3 people authored Dec 14, 2024
1 parent e99adaa commit df00846
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/superqt/utils/_code_syntax_highlight.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand All @@ -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):
Expand All @@ -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):
Expand Down

0 comments on commit df00846

Please sign in to comment.