Refactor boilerplate functionality into base class

This commit is contained in:
Kovid Goyal 2013-10-30 18:57:00 +05:30
parent d565ccc717
commit 2e5808c9de
2 changed files with 27 additions and 23 deletions

View File

@ -26,3 +26,27 @@ class SyntaxHighlighter(QSyntaxHighlighter):
def create_formats(self):
pass
def highlightBlock(self, text):
try:
state = self.previousBlockState()
if state == -1:
state = 0
self.do_highlight(state, unicode(text))
except:
import traceback
traceback.print_exc()
def do_highlight(self, state, text):
state = self.state_class(state)
i = 0
while i < len(text):
fmt = self.state_map[state.parse](state, text, i, self.formats)
for num, f in fmt:
if f is not None:
self.setFormat(i, num, f)
i += num
self.setCurrentBlockState(state.value)

View File

@ -251,6 +251,9 @@ for x in (State.SQ_VAL, State.DQ_VAL):
class HTMLHighlighter(SyntaxHighlighter):
state_map = state_map
state_class = State
def __init__(self, parent):
SyntaxHighlighter.__init__(self, parent)
@ -284,29 +287,6 @@ class HTMLHighlighter(SyntaxHighlighter):
f = self.formats['title'] = QTextCharFormat()
f.setFontWeight(QFont.Bold)
def highlightBlock(self, text):
try:
self.do_highlight(unicode(text))
except:
import traceback
traceback.print_exc()
def do_highlight(self, text):
state = self.previousBlockState()
if state == -1:
state = State.NORMAL
state = State(state)
i = 0
while i < len(text):
fmt = state_map[state.parse](state, text, i, self.formats)
for num, f in fmt:
if f is not None:
self.setFormat(i, num, f)
i += num
self.setCurrentBlockState(state.value)
if __name__ == '__main__':
from calibre.gui2.tweak_book.editor.text import launch_editor
launch_editor('''\