Skip to content

Commit

Permalink
Merge pull request #481 from Carreau/highlight-jump
Browse files Browse the repository at this point in the history
Monkeypatch RegexLexer only while in use by qtconsole.
  • Loading branch information
ccordoba12 committed Apr 20, 2021
2 parents 9f754cb + 8ad6f6d commit 5d90896
Showing 1 changed file with 33 additions and 19 deletions.
52 changes: 33 additions & 19 deletions qtconsole/pygments_highlighter.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,19 @@ def get_tokens_unprocessed(self, text, stack=('root',)):


# Monkeypatch!
RegexLexer.get_tokens_unprocessed = get_tokens_unprocessed
from contextlib import contextmanager


@contextmanager
def _lexpatch():

try:
orig = RegexLexer.get_tokens_unprocessed
RegexLexer.get_tokens_unprocessed = get_tokens_unprocessed
yield
finally:
pass
RegexLexer.get_tokens_unprocessed = orig


class PygmentsBlockUserData(QtGui.QTextBlockUserData):
Expand Down Expand Up @@ -117,24 +129,26 @@ def highlightBlock(self, string):
""" Highlight a block of text.
"""
prev_data = self.currentBlock().previous().userData()
if prev_data is not None:
self._lexer._saved_state_stack = prev_data.syntax_stack
elif hasattr(self._lexer, '_saved_state_stack'):
del self._lexer._saved_state_stack

# Lex the text using Pygments
index = 0
for token, text in self._lexer.get_tokens(string):
length = qstring_length(text)
self.setFormat(index, length, self._get_format(token))
index += length

if hasattr(self._lexer, '_saved_state_stack'):
data = PygmentsBlockUserData(
syntax_stack=self._lexer._saved_state_stack)
self.currentBlock().setUserData(data)
# Clean up for the next go-round.
del self._lexer._saved_state_stack
with _lexpatch():
if prev_data is not None:
self._lexer._saved_state_stack = prev_data.syntax_stack
elif hasattr(self._lexer, "_saved_state_stack"):
del self._lexer._saved_state_stack

# Lex the text using Pygments
index = 0
for token, text in self._lexer.get_tokens(string):
length = qstring_length(text)
self.setFormat(index, length, self._get_format(token))
index += length

if hasattr(self._lexer, "_saved_state_stack"):
data = PygmentsBlockUserData(
syntax_stack=self._lexer._saved_state_stack
)
self.currentBlock().setUserData(data)
# Clean up for the next go-round.
del self._lexer._saved_state_stack

#---------------------------------------------------------------------------
# 'PygmentsHighlighter' interface
Expand Down

0 comments on commit 5d90896

Please sign in to comment.