def _add_table(self, tab, cursor): fmt = QTextCharFormat() fmt.setFont(QFont(self.factory.font_name)) fmt.setFontPointSize(self.factory.font_size) bc = QColor(self.factory.bg_color) if self.factory.bg_color else None ec, oc, hc = bc, bc, bc if self.factory.even_color: ec = QColor(self.factory.even_color) if self.factory.odd_color: oc = QColor(self.factory.odd_color) if self.factory.header_color: hc = QColor(self.factory.header_color) with edit_block(cursor): for i, row in enumerate(tab.items): cell = row.cells[0] if cell.bold: fmt.setFontWeight(QFont.Bold) else: fmt.setFontWeight(QFont.Normal) if i == 0 and hc: c = hc elif (i - 1) % 2 == 0: c = ec else: c = oc if c: fmt.setBackground(c) txt = ''.join([u'{{:<{}s}}'.format(cell.width).format(cell.text) for cell in row.cells ]) cursor.insertText(txt + '\n', fmt)
def __init__(self, parent, blackbold_patterns, redbold_patterns): ''' Define highlighting rules - inputs = lists of patterns ''' super(Highlighter, self).__init__(parent) self.highlighting_rules = [] # Black bold items (allowed keywords) black_bold_format = QTextCharFormat() black_bold_format.setFontWeight(QFont.Bold) self.highlighting_rules = [(QRegExp(pattern, cs=Qt.CaseInsensitive), black_bold_format) for pattern in blackbold_patterns] # Red bold items (reserved keywords) red_bold_format = QTextCharFormat() red_bold_format.setFontWeight(QFont.Bold) red_bold_format.setForeground(Qt.red) for pattern in redbold_patterns: self.highlighting_rules.append( (QRegExp(pattern, cs=Qt.CaseInsensitive), red_bold_format)) # Comments comment_format = QTextCharFormat() comment_format.setForeground(Qt.darkBlue) comment_format.setFontItalic(True) self.highlighting_rules.append((QRegExp('--[^\n]*'), comment_format))
def formatConverterFunction(format): if format == qutepart.syntax.TextFormat(): return None # Do not apply default format. Performance optimization qtFormat = QTextCharFormat() qtFormat.setForeground(QBrush(QColor(format.color))) qtFormat.setBackground(QBrush(QColor(format.background))) qtFormat.setFontItalic(format.italic) qtFormat.setFontWeight(QFont.Bold if format.bold else QFont.Normal) qtFormat.setFontUnderline(format.underline) qtFormat.setFontStrikeOut(format.strikeOut) return qtFormat
def syntax_format(color, style=''): """Return a QTextCharFormat with the given attributes. """ _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _format.setFontItalic(True) return _format
def txformat(color, style=''): """Return a QTextCharFormat with the given attributes. """ _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _format.setFontItalic(True) return _format
def _add_table(self, tab, cursor): fmt = QTextCharFormat() fmt.setFont(QFont(self.factory.font_name)) fmt.setFontPointSize(self.factory.font_size) bc = QColor(self.factory.bg_color) if self.factory.bg_color else None ec, oc, hc = bc, bc, bc if self.factory.even_color: ec = QColor(self.factory.even_color) if self.factory.odd_color: oc = QColor(self.factory.odd_color) if self.factory.header_color: hc = QColor(self.factory.header_color) with edit_block(cursor): for i, row in enumerate(tab.items): cell = row.cells[0] if cell.bold: fmt.setFontWeight(QFont.Bold) else: fmt.setFontWeight(QFont.Normal) if i == 0 and hc: c = hc elif (i - 1) % 2 == 0: c = ec else: c = oc if c: fmt.setBackground(c) txt = ''.join([ u'{{:<{}s}}'.format(cell.width).format(cell.text) for cell in row.cells ]) cursor.insertText(txt + '\n', fmt)
class MacroHighlighter(QSyntaxHighlighter): def __init__(self,textboxdoc,valid_list_of_commands): QSyntaxHighlighter.__init__(self,textboxdoc) self.valid_syntax="|".join([command.regexp_str for command in valid_list_of_commands]) self.my_expression = QRegExp(self.valid_syntax) #define a blue font format for valid commands self.valid = QTextCharFormat() self.valid.setForeground(Qt.black) #define a bold red font format for invalid commands self.invalid = QTextCharFormat() self.invalid.setFontWeight(QFont.Bold) self.invalid.setForeground(Qt.red) #define a blue font format for valid parameters self.valid_value=QTextCharFormat() self.valid_value.setFontWeight(QFont.Bold) #self.valid_value.setForeground(QColor.fromRgb(255,85,0)) self.valid_value.setForeground(Qt.blue) def highlightBlock(self, text): #this function is automatically called when some text is changed #in the texbox. 'text' is the line of text where the change occured #check if the line of text contains a valid command match = self.my_expression.exactMatch(text) if match: #valid command found: highlight the command in blue self.setFormat(0, len(text), self.valid) #highlight the parameters in orange #loop on all the parameters that can be captured for i in range(self.my_expression.captureCount()): #if a parameter was captured, it's position in the text will be >=0 and its capture contains some value 'xxx' #otherwise its position is -1 and its capture contains an empty string '' if self.my_expression.pos(i+1)!=-1: self.setFormat(self.my_expression.pos(i+1), len(self.my_expression.cap(i+1)), self.valid_value) else: #no valid command found: highlight in red self.setFormat(0, len(text), self.invalid)
def __init__(self, parent=None): """ @param parent QObject or QTextDocument or QTextEdit or None """ super(CppHighlighter, self).__init__(parent) keywordFormat = QTextCharFormat() keywordFormat.setForeground(HLS_KEYWORD_COLOR) keywordFormat.setFontWeight(QFont.Bold) self.highlightingRules = [(QRegExp(pattern), keywordFormat) for pattern in self.KEYWORD_PATTERNS] typeFormat = QTextCharFormat() typeFormat.setForeground(HLS_TYPE_COLOR) typeFormat.setFontWeight(QFont.Bold) self.highlightingRules.extend([(QRegExp(pattern), typeFormat) for pattern in self.TYPE_PATTERNS]) constantFormat = QTextCharFormat() constantFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.extend([(QRegExp(pattern), constantFormat) for pattern in self.CONSTANT_PATTERNS]) classFormat = QTextCharFormat() classFormat.setFontWeight(QFont.Bold) classFormat.setForeground(HLS_CLASS_COLOR) self.highlightingRules.append((QRegExp(r"\bQ[A-Za-z]+\b"), classFormat)) functionFormat = QTextCharFormat() functionFormat.setFontItalic(True) functionFormat.setForeground(HLS_FUNCTION_COLOR) self.highlightingRules.append((QRegExp(r"\b[A-Za-z0-9_]+(?=\()"), functionFormat)) quotationFormat = QTextCharFormat() quotationFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.append((QRegExp(r'"[^"]*"'), quotationFormat)) # This must comes before the line comments since they conficts pragmaFormat = QTextCharFormat() pragmaFormat.setForeground(HLS_PRAGMA_COLOR) self.highlightingRules.append((QRegExp(r"#[^\n]*"), pragmaFormat)) self.multiLineCommentFormat = QTextCharFormat() self.multiLineCommentFormat.setForeground(HLS_COMMENT_COLOR) singleLineCommentFormat = QTextCharFormat() singleLineCommentFormat.setForeground(HLS_COMMENT_COLOR) self.highlightingRules.append((QRegExp("//[^\n]*"), singleLineCommentFormat)) self.commentStartExpression = QRegExp(r"/\*") self.commentEndExpression = QRegExp(r"\*/")
class TextFormat(): def __init__(self, selection, button): self.selection = selection self.cursor = QTextCursor(self.selection.textEdit.textCursor()) self.format = QTextCharFormat() self.button = button def bold_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.bold_selection() if self.selection.textEdit.fontWeight() == QFont.Bold: self.button.setDown(False) return self.selection.textEdit.setFontWeight(QFont.Normal) self.button.setDown(True) return self.selection.textEdit.setFontWeight(QFont.Bold) def bold_selection(self): if self.selection.bold_button.isDown(): self.selection.bold_button.setDown(False) return self.selection.textEdit.setFontWeight(QFont.Normal) if not self.selection.textEdit.textCursor().charFormat().fontWeight() == QFont.Bold: self.format.setFontWeight(QFont.Bold) self.selection.bold_button.setDown(True) return self.cursor.mergeCharFormat(self.format) return self.selection.textEdit.setFontWeight(QFont.Normal) def italic_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.italic_selection() if self.selection.textEdit.fontItalic(): self.button.setDown(False) return self.selection.textEdit.setFontItalic(False) self.button.setDown(True) return self.selection.textEdit.setFontItalic(True) def italic_selection(self): if self.selection.italic_button.isDown(): self.selection.italic_button.setDown(False) return self.selection.textEdit.setFontItalic() if not self.selection.textEdit.textCursor().charFormat().fontItalic(): self.format.setFontItalic(True) return self.cursor.mergeCharFormat(self.format) self.selection.italic_button.setDown(False) return self.selection.textEdit.setFontItalic(False) def underline_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.underline_selection() if self.selection.textEdit.fontUnderline(): self.button.setDown(False) return self.selection.textEdit.setFontUnderline(False) self.button.setDown(True) return self.selection.textEdit.setFontUnderline(True) def underline_selection(self): if self.selection.underline_button.isDown(): self.selection.underline_button.setDown(False) return self.selection.textEdit.setFontUnderline(False) if not self.selection.textEdit.textCursor().charFormat().fontUnderline(): self.format.setFontUnderline(True) return self.cursor.mergeCharFormat(self.format) return self.selection.textEdit.setFontUnderline(False) def strikeout_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.strikeout_selection() if self.selection.textEdit.textCursor().charFormat().fontStrikeOut(): self.button.setDown(False) return self.selection.textEdit.textCursor().charFormat().setFontStrikeOut(False) self.button.setDown(True) formatter = QTextCharFormat() formatter.setFontStrikeOut(True) return self.selection.textEdit.setCurrentCharFormat(formatter) def strikeout_selection(self): if self.selection.textEdit.textCursor().charFormat().fontStrikeOut(): self.selection.strikeout_button.setDown(False) self.format.setFontStrikeOut(False) return self.cursor.mergeCharFormat(self.format) if not self.selection.textEdit.textCursor().charFormat().fontStrikeOut(): self.format.setFontStrikeOut(True) return self.cursor.mergeCharFormat(self.format) return self.selection.textEdit.textCursor().charFormat()
class SyntaxHighlightSetting(): """ This class contains a single Setting for a code block in the SyntaxHighlighter. Variables: - expression: The regular expression of the syntax block - expression_end: If the expression has a start and an end expression - font_size - font_color - font_weight - font_style - font_underline - use_font_size """ def __init__(self, expression, font_family, font_size, font_color, font_weight, font_style, font_underline, use_font_size, expression_end=''): self.expression = expression if expression_end != '': self.expression_end = expression_end self.font_family = font_family self.font_size = font_size self.font_color = font_color self.font_weight = font_weight self.font_style = font_style self.font_underline = font_underline self.use_font_size = use_font_size self.createFormat() def createFormat(self): """ Create a QTextCharformat and saves it in self.class_format""" self.class_format = QTextCharFormat() self.class_format.setFontFamily(self.font_family) if self.use_font_size: self.class_format.setFontPointSize(self.font_size) self.class_format.setForeground(self.font_color) self.class_format.setFontWeight(self.font_weight) self.class_format.setFontItalic(self.font_style) self.class_format.setFontUnderline(self.font_underline) def get_format(self): return self.class_format def getValues(self): return [self.expression, self.font_color, self.font_weight] def serialize(self): str1 = "" str1 += self.expression + "//" str1 += str(self.font_color) + "//" str1 += str(self.font_weight) + "//" return str1 def deserialize(self, string): splitted = string.split("//") self.expression = splitted[0] self.font_color = splitted[1] self.font_weight = splitted[2]
def __init__(self, parent=None): """ @param parent QObject or QTextDocument or QTextEdit or None """ super(PyHighlighter, self).__init__(parent) keywordFormat = QTextCharFormat() keywordFormat.setForeground(HLS_KEYWORD_COLOR) keywordFormat.setFontWeight(QFont.Bold) self.highlightingRules = [(QRegExp(pattern), keywordFormat) for pattern in self.KEYWORD_PATTERNS] typeFormat = QTextCharFormat() typeFormat.setForeground(HLS_TYPE_COLOR) typeFormat.setFontWeight(QFont.Bold) self.highlightingRules.extend([(QRegExp(pattern), typeFormat) for pattern in self.TYPE_PATTERNS]) constantFormat = QTextCharFormat() constantFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.extend([(QRegExp(pattern), constantFormat) for pattern in self.CONSTANT_PATTERNS]) classFormat = QTextCharFormat() classFormat.setFontWeight(QFont.Bold) classFormat.setForeground(HLS_CLASS_COLOR) self.highlightingRules.append((QRegExp(r"\bQ[A-Za-z]+\b"), classFormat)) functionFormat = QTextCharFormat() functionFormat.setFontItalic(True) functionFormat.setForeground(HLS_FUNCTION_COLOR) self.highlightingRules.append((QRegExp(r"\b[A-Za-z0-9_]+(?=\()"), functionFormat)) quotationFormat = QTextCharFormat() quotationFormat.setForeground(HLS_LITERAL_COLOR) self.highlightingRules.append((QRegExp(r'"[^"]*"'), quotationFormat)) self.highlightingRules.append((QRegExp(r'u"[^"]*"'), quotationFormat)) self.highlightingRules.append((QRegExp(r"'[^']*'"), quotationFormat)) self.highlightingRules.append((QRegExp(r"u'[^']*'"), quotationFormat)) singleLineCommentFormat = QTextCharFormat() singleLineCommentFormat.setForeground(HLS_COMMENT_COLOR) self.highlightingRules.append((QRegExp("#[^\n]*"), singleLineCommentFormat)) self.multiLineCommentFormat = QTextCharFormat() self.multiLineCommentFormat.setForeground(HLS_COMMENT_COLOR) self.commentStartExpression = QRegExp(r'"""') self.commentEndExpression = QRegExp(r'"""') todoFormat = QTextCharFormat() todoFormat.setBackground(HLS_TODO_COLOR) self.postHighlightingRules = [(QRegExp(pattern), todoFormat) for pattern in HLS_TODO_PATTERNS] doxyFormat = QTextCharFormat() doxyFormat.setForeground(HLS_COMMENT_COLOR) doxyFormat.setFontWeight(QFont.Bold) self.postHighlightingRules.extend([(QRegExp(pattern), doxyFormat) for pattern in HLS_DOXY_PATTERNS])
def testCase(self): editor = QTextEdit() cursor = QTextCursor(editor.textCursor()) cursor.movePosition(QTextCursor.Start) mainFrame = cursor.currentFrame() plainCharFormat = QTextCharFormat() boldCharFormat = QTextCharFormat() boldCharFormat.setFontWeight(QFont.Bold) cursor.insertText( """ Text documents are represented by the QTextDocument class, rather than by QString objects. Each QTextDocument object contains information about the document's internal representation, its structure, and keeps track of modifications to provide undo/redo facilities. This approach allows features such as the layout management to be delegated to specialized classes, but also provides a focus for the framework.""", plainCharFormat) frameFormat = QTextFrameFormat() frameFormat.setMargin(32) frameFormat.setPadding(8) frameFormat.setBorder(4) cursor.insertFrame(frameFormat) cursor.insertText( """ Documents are either converted from external sources or created from scratch using Qt. The creation process can done by an editor widget, such as QTextEdit, or by explicit calls to the Scribe API.""", boldCharFormat) cursor = mainFrame.lastCursorPosition() cursor.insertText( """ There are two complementary ways to visualize the contents of a document: as a linear buffer that is used by editors to modify the contents, and as an object hierarchy containing structural information that is useful to layout engines. In the hierarchical model, the objects generally correspond to visual elements such as frames, tables, and lists. At a lower level, these elements describe properties such as the style of text used and its alignment. The linear representation of the document is used for editing and manipulation of the document's contents.""", plainCharFormat) frame = cursor.currentFrame() items = [] #test iterator for i in frame: items.append(i) #test __iadd__ b = frame.begin() i = 0 while not b.atEnd(): self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__iadd__(1) i += 1 #test __isub__ b = frame.end() i = 0 while i > 0: self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__isub__(1) i -= 1
def applyFormatting(self): """ TOWRITE """ prefixLength = len(self.prefix) start = -1 stop = -1 formats = [] # QList<QTextLayout.FormatRange> # Bold Prefix formatPrefix = QTextCharFormat() formatPrefix.setFontWeight(QFont.Bold) rangePrefix = QTextLayout.FormatRange() rangePrefix.start = 0 rangePrefix.length = prefixLength rangePrefix.format = formatPrefix formats.append(rangePrefix) # Keywords start = self.prefix.find('[') stop = self.prefix.rfind(']') if (start != -1 & stop != -1 & start < stop): formatKeyword = QTextCharFormat() formatKeyword.setFontWeight(QFont.Bold) formatKeyword.setForeground(QColor("#0095FF")) rangeStart = -1 rangeStop = -1 for i in reversed(range(start, stop + 1)): if self.prefix[i] == ']': rangeStop = i if self.prefix[i] == '[' or self.prefix[i] == '/': rangeStart = i rangeKeyword = QTextLayout.FormatRange() rangeKeyword.start = rangeStart + 1 rangeKeyword.length = rangeStop - rangeStart - 1 rangeKeyword.format = formatKeyword formats.append(rangeKeyword) rangeStop = i # Default Values start = self.prefix.find('{') stop = self.prefix.rfind('}') if start != -1 & stop != -1 & start < stop: formatKeyword = QTextCharFormat() formatKeyword.setFontWeight(QFont.Bold) formatKeyword.setForeground(QColor("#00AA00")) rangeStart = -1 rangeStop = -1 for i in reversed(range(start, stop + 1)): if self.prefix[i] == '}': rangeStop = i if self.prefix[i] == '{': rangeStart = i rangeKeyword = QTextLayout.FormatRange() rangeKeyword.start = rangeStart + 1 rangeKeyword.length = rangeStop - rangeStart - 1 rangeKeyword.format = formatKeyword formats.append(rangeKeyword) rangeStop = i self.changeFormatting(formats)
def testCase(self): editor = QTextEdit() cursor = QTextCursor(editor.textCursor()) cursor.movePosition(QTextCursor.Start) mainFrame = cursor.currentFrame() plainCharFormat = QTextCharFormat() boldCharFormat = QTextCharFormat() boldCharFormat.setFontWeight(QFont.Bold); cursor.insertText(""" Text documents are represented by the QTextDocument class, rather than by QString objects. Each QTextDocument object contains information about the document's internal representation, its structure, and keeps track of modifications to provide undo/redo facilities. This approach allows features such as the layout management to be delegated to specialized classes, but also provides a focus for the framework.""", plainCharFormat) frameFormat = QTextFrameFormat() frameFormat.setMargin(32) frameFormat.setPadding(8) frameFormat.setBorder(4) cursor.insertFrame(frameFormat) cursor.insertText(""" Documents are either converted from external sources or created from scratch using Qt. The creation process can done by an editor widget, such as QTextEdit, or by explicit calls to the Scribe API.""", boldCharFormat) cursor = mainFrame.lastCursorPosition() cursor.insertText(""" There are two complementary ways to visualize the contents of a document: as a linear buffer that is used by editors to modify the contents, and as an object hierarchy containing structural information that is useful to layout engines. In the hierarchical model, the objects generally correspond to visual elements such as frames, tables, and lists. At a lower level, these elements describe properties such as the style of text used and its alignment. The linear representation of the document is used for editing and manipulation of the document's contents.""", plainCharFormat) frame = cursor.currentFrame() items = [] #test iterator for i in frame: items.append(i) #test __iadd__ b = frame.begin() i = 0 while not b.atEnd(): self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__iadd__(1) i += 1 #test __isub__ b = frame.end() i = 0 while i > 0: self.assertEqual(b, items[i]) self.assert_(b.parentFrame(), items[i].parentFrame()) b.__isub__(1) i -= 1