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))
class YouTubeHighlighter(QSyntaxHighlighter): def __init__(self, parent=None): """ @param parent QObject or QTextDocument or QTextEdit or None """ super(YouTubeHighlighter, self).__init__(parent) self._format = QTextCharFormat() self._format.setForeground(Qt.blue) #self._format.setFontWeight(QFont.Bold) self._format.setFontUnderline(True) self._format.setUnderlineColor(Qt.red) self._format.setUnderlineStyle(QTextCharFormat.DashUnderline) def highlightBlock(self, text): """@reimp @protected""" for vid in self._itervids(text): index = text.index(vid) length = len(vid) self.setFormat(index, length, self._format) @staticmethod def _itervids(text): """ @param text unicode @yield str """ if text: for it in 'http://', 'www.', 'youtu.be', 'youtube.com': text = text.replace(it, '') for word in re.split(r'\s', text): vid = re.sub(r'.*v=([0-9a-zA-Z_-]+).*', r'\1', word) if re.match(r'[0-9a-zA-Z_-]+', vid): yield vid
def _create_info_cursor(self): cursor = self.cursorForPosition(self._mouse_position) cursor.select(QTextCursor.WordUnderCursor) format = QTextCharFormat() format.setFontUnderline(True) format.setForeground(QBrush(QColor('blue'))) cursor.setCharFormat(format) return cursor
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 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 __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))
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)
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]
# Open the text finder if event.key() == Qt.Key_F and event.modifiers() == Qt.ControlModifier: customKey = True print("Opening finder...") if not customKey: QPlainTextEdit.keyPressEvent(self, event) def initUI(self): pass # Create the font styles that will highlight the code keywordFormat = QTextCharFormat() keywordFormat.setForeground(QColor('blue')) operatorFormat = QTextCharFormat() operatorFormat.setForeground(QColor('red')) braceFormat = QTextCharFormat() braceFormat.setForeground(QColor('darkGray')) defClassFormat = QTextCharFormat() defClassFormat.setForeground(QColor('black')) stringFormat = QTextCharFormat() stringFormat.setForeground(QColor('magenta')) string2Format = QTextCharFormat() string2Format.setForeground(QColor('darkMagenta')) commentFormat = QTextCharFormat() commentFormat.setForeground(QColor('darkGreen')) commentFormat.setFontItalic(True) selfFormat = QTextCharFormat() selfFormat.setForeground(QColor('purple'))
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"\*/")
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])
class PyHighlighter(QSyntaxHighlighter): KEYWORD_PATTERNS = ( r"\bbreak\b", r"\bclass\b", r"\bcontinue\b", r"\bdef\b", r"\bdo\b", r"\belif\b", r"\belse\b", r"\bfor\b", r"\bfunction\b", r"\bid\b", r"\bif\b", r"\bimport\b", r"\bin\b", r"\bprint\b", r"\breturn\b", r"\btype\b", r"\bwhile\b", ) TYPE_PATTERNS = ( r"\bbool\b", r"\bdouble\b", r"\bint\b", r"\blong\b", r"\bprint\b", r"\bstr\b", r"\bunicode\b", ) CONSTANT_PATTERNS = ( r"\bTrue\b", r"\bFalse\b", ) 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 highlightBlock(self, text): """@reimp @protected""" for pattern, format in self.highlightingRules: expression = QRegExp(pattern) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, format) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0) startIndex = 0 if self.previousBlockState() != 1: startIndex = self.commentStartExpression.indexIn(text) while startIndex >= 0: endIndex = self.commentEndExpression.indexIn(text, startIndex +1) if endIndex == -1: self.setCurrentBlockState(1) commentLength = len(text) - startIndex else: commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength() self.setFormat(startIndex, commentLength, self.multiLineCommentFormat) startIndex = self.commentStartExpression.indexIn(text, startIndex + commentLength); for pattern, format in self.postHighlightingRules: expression = QRegExp(pattern) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, format) index = expression.indexIn(text, index + length)
class CppHighlighter(QSyntaxHighlighter): KEYWORD_PATTERNS = ( r"\bcase\b", r"\bclass\b", r"\bdefault\b", r"\benum\b", r"\bexplicit\b", r"\bfriend\b", r"\bfor\b", r"\belse\b", r"\bif\b", r"\binline\b", r"\bnamespace\b", r"\boperator\b", r"\bprivate\b", r"\bprotected\b", r"\bpublic\b", r"\breturn\b", r"\bswitch\b", r"\bstruct\b", r"\btemplate\b", r"\btypedef\b", r"\btypename\b", r"\bunion\b", r"\bvirtual\b", r"\bvolatile\b", ) TYPE_PATTERNS = ( r"\bchar\b", r"\bconst\b", r"\bdouble\b", r"\bexplicit\b", r"\bint\b", r"\blong\b", r"\bshort\b", r"\bfloat\b", r"\bdouble\b", r"\bsignals\b", r"\bsigned\b", r"\bslots\b", r"\bstatic\b", r"\bstruct\b", r"\bunsigned\b", ) CONSTANT_PATTERNS = ( r"\btrue\b", r"\bfalse\b", ) 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"\*/") def highlightBlock(self, text): """@reimp @protected""" for pattern, format in self.highlightingRules: expression = QRegExp(pattern) index = expression.indexIn(text) while index >= 0: length = expression.matchedLength() self.setFormat(index, length, format) index = expression.indexIn(text, index + length) self.setCurrentBlockState(0) startIndex = 0 if self.previousBlockState() != 1: startIndex = self.commentStartExpression.indexIn(text) while startIndex >= 0: endIndex = self.commentEndExpression.indexIn(text, startIndex +1) if endIndex == -1: self.setCurrentBlockState(1) commentLength = len(text) - startIndex else: commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength() self.setFormat(startIndex, commentLength, self.multiLineCommentFormat) startIndex = self.commentStartExpression.indexIn(text, startIndex + commentLength);
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)