From 7b1aefd119383ff3f87623a7ce997ec4d45b50f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Althviz=20Mor=C3=A9?= <16781833+dalthviz@users.noreply.github.com> Date: Tue, 28 May 2024 06:11:57 -0500 Subject: [PATCH] Prevent computing full document content highlight and only parse current block content for performance (#246) --- src/superqt/utils/_code_syntax_highlight.py | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-) diff --git a/src/superqt/utils/_code_syntax_highlight.py b/src/superqt/utils/_code_syntax_highlight.py index 9aa16464..d990f8a1 100644 --- a/src/superqt/utils/_code_syntax_highlight.py +++ b/src/superqt/utils/_code_syntax_highlight.py @@ -1,5 +1,3 @@ -from itertools import takewhile - from pygments import highlight from pygments.formatter import Formatter from pygments.lexers import find_lexer_class, get_lexer_by_name @@ -68,21 +66,10 @@ def background_color(self): return self.formatter.style.background_color def highlightBlock(self, text): - cb = self.currentBlock() - p = cb.position() - text_ = self.document().toPlainText() + "\n" - highlight(text_, self.lexer, self.formatter) - - enters = sum(1 for _ in takewhile(lambda x: x == "\n", text_)) - # pygments lexer ignore leading empty lines, so we need to do correction - # here calculating the number of empty lines. - # dirty, dirty hack # The core problem is that pygemnts by default use string streams, # that will not handle QTextCharFormat, so we need use `data` property to # work around this. + highlight(text, self.lexer, self.formatter) for i in range(len(text)): - try: - self.setFormat(i, 1, self.formatter.data[p + i - enters]) - except IndexError: # pragma: no cover - pass + self.setFormat(i, 1, self.formatter.data[i])