Added interactive diff gui
[ugit.git] / py / syntax.py
bloba8c3207059f7d75f9b6ea8c314ed2a37a26ddfa3
1 #!/usr/bin/python
2 import re
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 BEGIN = 0
9 ADD = 1
10 REMOVE = 2
11 TEXT = 3
13 class GitSyntaxHighlighter (QSyntaxHighlighter):
15 def __init__ (self, doc):
16 QSyntaxHighlighter.__init__ (self, doc)
18 begin = self.__mkformat (QFont.Bold, Qt.cyan)
19 addition = self.__mkformat (QFont.Bold, Qt.green)
20 removal = self.__mkformat (QFont.Bold, Qt.red)
21 message = self.__mkformat (QFont.Bold, Qt.yellow, Qt.black)
23 # Catch trailing whitespace
24 bad_ws_format = self.__mkformat (QFont.Bold, Qt.black, Qt.red)
25 self._bad_ws_regex = re.compile ('(.*?)(\s+)$')
26 self._bad_ws_format = bad_ws_format
28 self._rules = (
29 ( re.compile ('^(@@|\+\+\+|---)'), begin ),
30 ( re.compile ('^\+'), addition ),
31 ( re.compile ('^-'), removal ),
32 ( re.compile ('^:'), message ),
35 def getFormat (self, line):
36 for regex, rule in self._rules:
37 if regex.match (line):
38 return rule
39 return None
41 def highlightBlock (self, qstr):
42 ascii = qstr.toAscii().data()
43 if not ascii: return
44 fmt = self.getFormat (ascii)
45 if fmt:
46 match = self._bad_ws_regex.match (ascii)
47 if match and match.group (2):
48 start = len (match.group (1))
49 self.setFormat (0, start, fmt)
50 self.setFormat (start, len (ascii),
51 self._bad_ws_format)
52 else:
53 self.setFormat (0, len (ascii), fmt)
55 def __mkformat (self, weight, color, bgcolor=None):
56 format = QTextCharFormat()
57 format.setFontWeight (weight)
58 format.setForeground (color)
59 if bgcolor: format.setBackground (bgcolor)
60 return format
63 if __name__ == '__main__':
64 import sys
65 from PyQt4 import QtCore, QtGui
67 class SyntaxTestDialog(QtGui.QDialog):
68 def __init__ (self, parent):
69 QtGui.QDialog.__init__ (self, parent)
70 self.setupUi (self)
72 def setupUi(self, CommandDialog):
73 CommandDialog.resize(QtCore.QSize(QtCore.QRect(0,0,720,512).size()).expandedTo(CommandDialog.minimumSizeHint()))
75 self.vboxlayout = QtGui.QVBoxLayout(CommandDialog)
76 self.vboxlayout.setObjectName("vboxlayout")
78 self.commandText = QtGui.QTextEdit(CommandDialog)
80 font = QtGui.QFont()
81 font.setFamily("Monospace")
82 font.setPointSize(13)
83 self.commandText.setFont(font)
84 self.commandText.setAcceptDrops(False)
85 #self.commandText.setReadOnly(True)
86 self.vboxlayout.addWidget(self.commandText)
88 GitSyntaxHighlighter (self.commandText.document())
91 app = QtGui.QApplication (sys.argv)
92 dialog = SyntaxTestDialog (app.activeWindow())
93 dialog.show()
94 dialog.exec_()