3 from PyQt4
.QtCore
import Qt
4 from PyQt4
.QtGui
import QFont
5 from PyQt4
.QtGui
import QSyntaxHighlighter
6 from PyQt4
.QtGui
import QTextCharFormat
8 class DiffSyntaxHighlighter(QSyntaxHighlighter
):
9 def __init__(self
, doc
):
10 QSyntaxHighlighter
.__init
__(self
, doc
)
12 begin
= self
.__mkformat
(QFont
.Bold
, Qt
.darkCyan
)
13 diffhead
= self
.__mkformat
(QFont
.Bold
, Qt
.darkYellow
)
14 addition
= self
.__mkformat
(QFont
.Bold
, Qt
.green
)
15 removal
= self
.__mkformat
(QFont
.Bold
, Qt
.red
)
17 # Catch trailing whitespace
18 bad_ws_format
= self
.__mkformat
(QFont
.Bold
, Qt
.black
, Qt
.red
)
19 self
._bad
_ws
_regex
= re
.compile('(.*?)(\s+)$')
20 self
._bad
_ws
_format
= bad_ws_format
23 ( re
.compile('^(@@|\+\+\+|---)'), begin
),
24 ( re
.compile('^\+'), addition
),
25 ( re
.compile('^-'), removal
),
26 ( re
.compile('^(diff --git|index \S+\.\.\S+|new file mode)'),
30 def getFormat(self
, line
):
31 for regex
, rule
in self
._rules
:
36 def highlightBlock(self
, qstr
):
37 ascii
= qstr
.toAscii().data()
39 fmt
= self
.getFormat(ascii
)
41 match
= self
._bad
_ws
_regex
.match(ascii
)
42 if match
and match
.group(2):
43 start
= len(match
.group(1))
44 self
.setFormat(0, start
, fmt
)
45 self
.setFormat(start
, len(ascii
),
48 self
.setFormat(0, len(ascii
), fmt
)
50 def __mkformat(self
, weight
, color
, bgcolor
=None):
51 format
= QTextCharFormat()
52 format
.setFontWeight(weight
)
53 format
.setForeground(color
)
54 if bgcolor
: format
.setBackground(bgcolor
)
57 if __name__
== '__main__':
59 from PyQt4
import QtCore
, QtGui
60 class SyntaxTestDialog(QtGui
.QDialog
):
61 def __init__(self
, parent
):
62 QtGui
.QDialog
.__init
__(self
, parent
)
64 def setupUi(self
, dialog
):
65 dialog
.resize(QtCore
.QSize(QtCore
.QRect(0,0,720,512).size()).expandedTo(dialog
.minimumSizeHint()))
66 self
.vboxlayout
= QtGui
.QVBoxLayout(dialog
)
67 self
.vboxlayout
.setObjectName("vboxlayout")
68 self
.outputText
= QtGui
.QTextEdit(dialog
)
70 font
.setFamily("Monospace")
72 self
.outputText
.setFont(font
)
73 self
.outputText
.setAcceptDrops(False)
74 self
.vboxlayout
.addWidget(self
.outputText
)
75 DiffSyntaxHighlighter(self
.outputText
.document())
76 app
= QtGui
.QApplication(sys
.argv
)
77 dialog
= SyntaxTestDialog(app
.activeWindow())