1 from __future__
import division
, absolute_import
, unicode_literals
3 from qtpy
import QtCore
5 from qtpy
import QtWidgets
9 from pygments
.styles
import get_style_by_name
10 from pygments
import lex
11 from pygments
.util
import ClassNotFound
12 from pygments
.lexers
import get_lexer_for_filename
17 def highlight_document(edit
, filename
):
22 lexer
= get_lexer_for_filename(filename
, stripnl
=False)
26 style
= get_style_by_name('default')
28 font
= doc
.defaultFont()
29 base_format
= QtGui
.QTextCharFormat()
30 base_format
.setFont(font
)
33 window
= edit
.window()
34 if hasattr(window
, 'processEvents'):
35 processEvents
= window
.processEvents
37 processEvents
= QtCore
.QCoreApplication
.processEvents
39 def get_token_format(token
):
40 if token
in token_formats
:
41 return token_formats
[token
]
44 parent_format
= get_token_format(token
.parent
)
46 parent_format
= base_format
48 fmt
= QtGui
.QTextCharFormat(parent_format
)
50 if style
.styles_token(token
):
51 tstyle
= style
.style_for_token(token
)
53 fmt
.setForeground(QtGui
.QColor('#' + tstyle
['color']))
55 font
.setWeight(QtGui
.QFont
.Bold
)
58 if tstyle
['underline']:
59 fmt
.setFontUnderline(True)
61 fmt
.setBackground(QtGui
.QColor('#' + tstyle
['bgcolor']))
62 token_formats
[token
] = fmt
65 text
= doc
.toPlainText()
68 block
= doc
.firstBlock()
69 assert isinstance(block
, QtGui
.QTextBlock
)
71 block_len
= block
.length()
74 for token
, ttext
in lex(text
, lexer
):
75 format_len
= len(ttext
)
76 fmt
= get_token_format(token
)
78 format_range
= QtGui
.QTextLayout
.FormatRange()
79 format_range
.start
= block_pos
80 format_range
.length
= min(format_len
, block_len
)
81 format_range
.format
= fmt
82 block_formats
.append(format_range
)
83 block_len
-= format_range
.length
84 format_len
-= format_range
.length
85 block_pos
+= format_range
.length
87 block
.layout().setAdditionalFormats(block_formats
)
88 doc
.markContentsDirty(block
.position(), block
.length())
89 block
= block
.next() # pylint: disable=next-method-called
91 block_len
= block
.length()
95 if block_count
% 100 == 0:
99 if __name__
== '__main__':
100 app
= QtWidgets
.QApplication([])
102 python
= QtWidgets
.QPlainTextEdit()
103 f
= open(__file__
, 'r')
104 python
.setPlainText(f
.read())
107 python
.setWindowTitle('python')
109 highlight_document(python
, __file__
)