def foo(self):
        fmt = QTextCharFormat()
        fmt.setObjectType(QAbstractTextDocumentLayoutTest.objectType)

        cursor = self.textEdit.textCursor()
        cursor.insertText(py3k.unichr(0xfffc), fmt)
        self.textEdit.setTextCursor(cursor)
        self.textEdit.close()
Exemple #2
0
 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 foo(self):
        fmt = QTextCharFormat()
        fmt.setObjectType(QAbstractTextDocumentLayoutTest.objectType)

        cursor = self.textEdit.textCursor()
        cursor.insertText(py3k.unichr(0xFFFC), fmt)
        self.textEdit.setTextCursor(cursor)
        self.textEdit.close()
Exemple #4
0
 def __init__(self, state, parent=None):
     super().__init__(parent)
     self.state = state
     self.unknownWords = []
     self.wordsToIgnore = set()
     self.spellFormat = QTextCharFormat()
     self.spellFormat.setFontUnderline(True)
     self.spellFormat.setUnderlineColor(Qt.red)
     self.spellFormat.setUnderlineStyle(QTextCharFormat.WaveUnderline)
Exemple #5
0
 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)
Exemple #6
0
    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)
Exemple #7
0
  def __init__(self):
    self.start = 0
    self.stop = 0

    f = self.highlightFormat = QTextCharFormat()
    f.setForeground(Qt.blue)
    #f.setFontWeight(QFont.Bold) // this will cause text width change
    f.setFontUnderline(True)
    f.setUnderlineColor(Qt.red)
    f.setUnderlineStyle(QTextCharFormat.DashUnderline)

    f = self.openFormat = self.closeFormat = QTextCharFormat()
    f.setForeground(Qt.red)
Exemple #8
0
    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)
Exemple #9
0
    def highlightBlock(self, text):
        if not self.dict:
            return

        text = unicode(text)

        error_format = QTextCharFormat()
        error_format.setUnderlineColor(Qt.red)
        error_format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

        for word_object in re.finditer(self.WORDS, text):
            if not self.dict.check(word_object.group()):
                self.setFormat(word_object.start(),
                    word_object.end() - word_object.start(), error_format)
Exemple #10
0
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
Exemple #11
0
 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)
Exemple #12
0
    def tesIterator(self):
        edit = QTextEdit()
        cursor = edit.textCursor()
        fmt = QTextCharFormat()
        frags = []
        for i in range(10):
            fmt.setFontPointSize(i+10)
            frags.append("block%d"%i)
            cursor.insertText(frags[i], fmt)

        doc = edit.document()
        block = doc.begin()

        index = 0
        for i in block:
            self.assertEqual(i.fragment().text(), frags[index])
            index += 1
Exemple #13
0
    def tesIterator(self):
        edit = QTextEdit()
        cursor = edit.textCursor()
        fmt = QTextCharFormat()
        frags = []
        for i in range(10):
            fmt.setFontPointSize(i + 10)
            frags.append("block%d" % i)
            cursor.insertText(frags[i], fmt)

        doc = edit.document()
        block = doc.begin()

        index = 0
        for i in block:
            self.assertEqual(i.fragment().text(), frags[index])
            index += 1
Exemple #14
0
 def __init__(self):
     self.blockFormat = QTextBlockFormat()
     self.blockFormat.setAlignment(Qt.AlignLeft)
     self.charFormat = QTextCharFormat()
     self.frameFormat = QTextFrameFormat()
     self.frameFormat.setTopMargin(0)
     self.frameFormat.setBottomMargin(0)
     self.frameFormat.setLeftMargin(0)
     self.frameFormat.setPosition(QTextFrameFormat.InFlow)
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
Exemple #16
0
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 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
Exemple #18
0
    def mouseMoveEvent(self, event):
        if event.modifiers() & Qt.ControlModifier:
            self.clear_underline()
            cursor, line = self._get_line_cursor(event.pos())

            for goto in self.gotos:
                if line.strip().startswith(goto):
                    fmt = QTextCharFormat()
                    fmt.setFontUnderline(True)
                    fmt.setUnderlineStyle(QTextCharFormat.WaveUnderline)
                    fmt.setUnderlineColor(QtGui.QColor('blue'))
                    # cursor.clearSelection()
                    cursor.select(QTextCursor.BlockUnderCursor)

                    cursor.beginEditBlock()
                    cursor.setCharFormat(fmt)
                    cursor.endEditBlock()

                    break

        super(myCodeWidget, self).mouseMoveEvent(event)
Exemple #19
0
    def highlightBlock(self, text):
        if not self.dict:
            return

        text = unicode(text)

        error_format = QTextCharFormat()
        error_format.setUnderlineColor(Qt.red)
        error_format.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

        for word_object in re.finditer(self.WORDS, text):
            if not self.dict.check(word_object.group()):
                self.setFormat(word_object.start(),
                               word_object.end() - word_object.start(),
                               error_format)
Exemple #20
0
  def highlightBlock(self, text):
    """@reimp @public"""
    dic = self.__d.dic
    if not dic:
      return

    WORDS = "(?iu)[\w']+"
    #WORDS = "(?iu)[\w]+"    # ' is not considered as part of a world

    fmt = QTextCharFormat()
    fmt.setUnderlineColor(Qt.red)
    fmt.setUnderlineStyle(QTextCharFormat.SpellCheckUnderline)

    for word_object in re.finditer(WORDS, text):
      if not dic.check(word_object.group()):
        self.setFormat(word_object.start(),
          word_object.end() - word_object.start(), fmt)
Exemple #21
0
    def mouseMoveEvent(self, event):
        if event.modifiers() & Qt.ControlModifier:
            self.clear_underline()
            cursor, line = self._get_line_cursor(event.pos())

            for goto in self.gotos:
                if line.strip().startswith(goto):
                    fmt = QTextCharFormat()
                    fmt.setFontUnderline(True)
                    fmt.setUnderlineStyle(QTextCharFormat.WaveUnderline)
                    fmt.setUnderlineColor(QtGui.QColor('blue'))
                    # cursor.clearSelection()
                    cursor.select(QTextCursor.BlockUnderCursor)

                    cursor.beginEditBlock()
                    cursor.setCharFormat(fmt)
                    cursor.endEditBlock()

                    break

        super(myCodeWidget, self).mouseMoveEvent(event)
Exemple #22
0
class Highlighter(QSyntaxHighlighter):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        self.state = state
        self.unknownWords = []
        self.wordsToIgnore = set()
        self.spellFormat = QTextCharFormat()
        self.spellFormat.setFontUnderline(True)
        self.spellFormat.setUnderlineColor(Qt.red)
        self.spellFormat.setUnderlineStyle(QTextCharFormat.WaveUnderline)

    def highlightBlock(self, text):
        self.unknownWords = []
        language = self.state.language.value
        for match in WORD_LIKE_RX.finditer(text):
            word = match.group()
            start = match.start()
            length = match.end() - match.start()
            if (word not in self.wordsToIgnore
                    and not Spell.check(word, language)):
                self.setFormat(start, length, self.spellFormat)
                self.unknownWords.append((start, word))
Exemple #23
0
    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
Exemple #24
0
  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])
Exemple #25
0
    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))
Exemple #26
0
    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))
Exemple #27
0
    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
Exemple #28
0
    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)
Exemple #29
0
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()
Exemple #30
0
    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)
Exemple #31
0
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);
Exemple #32
0
 def __init__(self, selection, button):
     self.selection = selection
     self.cursor = QTextCursor(self.selection.textEdit.textCursor())
     self.format = QTextCharFormat()
     self.button = button
Exemple #33
0
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]
Exemple #34
0
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)
Exemple #35
0
                currBlock = currBlock.next()

        # 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()
Exemple #36
0
  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"\*/")
Exemple #37
0
    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 _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)
Exemple #39
0
    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