Example #1
0
    def __init__(self, parent=None):
        super(CodePreview_Highlighter, self).__init__(parent)

        keyword_format = QTextCharFormat()
        keyword_format.setFontWeight(QFont.Bold)
        keyword_format.setForeground(QColor(80, 80, 240))

        keyword_patterns = ["class", "def"]

        self.highlighting_rules = [(QRegExp(pattern), keyword_format)
                                   for pattern in keyword_patterns]

        # individual patterns
        if_format = QTextCharFormat()
        if_format.setForeground(QColor(255, 153, 51))
        self.highlighting_rules.append((QRegExp('if .+:'), if_format))

        elif_format = QTextCharFormat()
        elif_format.setForeground(QColor(255, 153, 51))
        self.highlighting_rules.append((QRegExp('elif .+:'), elif_format))

        else_format = QTextCharFormat()
        else_format.setForeground(QColor(255, 153, 51))
        self.highlighting_rules.append((QRegExp('else:'), else_format))

        else_format = QTextCharFormat()
        else_format.setFontItalic(True)
        else_format.setForeground(QColor(255, 179, 102))
        self.highlighting_rules.append((QRegExp('pass'), else_format))

        variable_assignment_format = QTextCharFormat()
        variable_assignment_format.setForeground(QColor(224, 108, 117))
        self.highlighting_rules.append(
            (QRegExp('[a-zA-Z_]+( +)=( +)'), variable_assignment_format))

        parameter_format = QTextCharFormat()
        parameter_format.setForeground(QColor(229, 192, 123))
        self.highlighting_rules.append(
            (QRegExp("[a-zA-Z_]+\(.*\)"),
             parameter_format))  # not working with standard values ('=') yet

        function_call_format = QTextCharFormat()
        function_call_format.setForeground(QColor(204, 204, 255))
        self.highlighting_rules.append(
            (QRegExp('[A-Za-z0-9_]+(?=\\()'), function_call_format))

        self_format = QTextCharFormat()
        self_format.setForeground(QColor(204, 204, 255))
        self.highlighting_rules.append((QRegExp('self'), self_format))

        return_format = QTextCharFormat()
        return_format.setFontItalic(True)
        return_format.setForeground(QColor(204, 82, 0))
        self.highlighting_rules.append((QRegExp('return'), return_format))

        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setFontItalic(True)
        singleLineCommentFormat.setForeground(QColor(92, 99, 112))
        self.highlighting_rules.append(
            (QRegExp('#[^\n]*'), singleLineCommentFormat))
    def setup_editor(self):
        variable_format = QTextCharFormat()
        variable_format.setFontWeight(QFont.Bold)
        variable_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\\b[A-Z_]+\\b", variable_format)

        single_line_comment_format = QTextCharFormat()
        single_line_comment_format.setBackground(QColor("#77ff77"))
        self._highlighter.add_mapping("#[^\n]*", single_line_comment_format)

        quotation_format = QTextCharFormat()
        quotation_format.setBackground(Qt.cyan)
        quotation_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\".*\"", quotation_format)

        function_format = QTextCharFormat()
        function_format.setFontItalic(True)
        function_format.setForeground(Qt.blue)
        self._highlighter.add_mapping("\\b[a-z0-9_]+\\(.*\\)", function_format)

        font = QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(10)

        self._editor = QPlainTextEdit()
        self._editor.setFont(font)
        self._highlighter.setDocument(self._editor.document())
Example #3
0
def text_format(color, style=''):
    f = QTextCharFormat()
    f.setForeground(color)
    if 'bold' in style:
        f.setFontWeight(QFont.Bold)
    if 'italic' in style:
        f.setFontItalic(True)
    return f
Example #4
0
 def _formatiraj(self, r, g, b, stil=''):
     #_boja = QColor()
     _boja = QColor.fromRgb(r, g, b, 255)
     _format = QTextCharFormat()
     _format.setForeground(_boja)
     if 'bold' in stil:
         _format.setFontWeight(QFont.Bold)
     if 'italic' in stil:
         _format.setFontItalic(True)
     return _format
Example #5
0
    def getTextCharFormat(self, color, style=None):
        """Return a QTextCharFormat with the given attributes."""
        textCharFormat = QTextCharFormat()
        textCharFormat.setForeground(color)
        if style is not None:
            if 'bold' in style:
                textCharFormat.setFontWeight(QFont.Bold)
            if 'italic' in style:
                textCharFormat.setFontItalic(True)

        return textCharFormat
Example #6
0
def format(color, style=''):
    """Return a QTextCharFormat with the given attributes."""
    _color = eval('getThemeColor(ThemeColor.%s)' % 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=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(QColor("#00CCFF"))
        keywordFormat.setFontCapitalization(QFont.AllUppercase)

        keywordPatterns = ["\\bSELECT\\b", "\\bFROM\\b", "\\bWHERE\\b",
                "\\bselect\\b", "\\bfrom\\b", "\\bwhere\\b", 
                "\\bTABLE\\b", "\\btable\\b", "\\bON\\b", "\\bon\\b",
                "\\bORDER\\b", "\\border\\b", "\\bBY\\b", "\\bby\\b",
                "\\bLIMIT\\b", "\\blimit\\b", "\\bBETWEEN\\b",
                "\\bbetween\\b", "\\bLIKE\\b", "\\blike\\b", "\\bTO\\b", "\\bto\\b",
                "\\bINNER\\b", "\\inner\\b", "\\bJOIN\\b", "\\bjoin\\b", 
                "\\bAND\\b", "\\and\\b", "\\bOR\\b", "\\bor\\b", 
                ]

        self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                for pattern in keywordPatterns]
        
        keyword2Format = QTextCharFormat()
        keyword2Format.setForeground(QColor("#DE0000"))
        keyword2Format.setFontCapitalization(QFont.AllUppercase)

        keyword2Patterns = ["\\bCREATE\\b", "\\bcreate\\b",
                 "\\bINSERT\\b", "\\binsert\\b", "\\bUPDATE\\b", "\\bupdate\\b",
                "\\bDELETE\\b","\\bdelete\\b", "\\bREPLACE\\b", "\\breplace\\b",
                "\\bDROP\\b", "\\bdrop\\b", "\\bRENAME\\b", "\\rename\\b",
                "\\bALTER\\b", "\\alter\\b",
                "\\bSET\\b", "\\bset\\b"
                ]


        self.highlightingRules.extend([(QRegExp(pattern), keyword2Format)
                for pattern in keyword2Patterns])
        
        table_name_format = QTextCharFormat()
        table_name_format.setForeground(QColor("#00FF7F"))
        table_name_format.setFontWeight(QFont.Bold)
        table_name_patterns = ["\\b{tn}\\b".format(tn=table.name) for table in Tables]
        ex_tables = ["\\b{tn}\\b".format(tn=table.name) for table in ExclusiveDbTables]
        table_name_patterns.extend(ex_tables)
        self.highlightingRules.extend([(QRegExp(pattern), table_name_format) for pattern in table_name_patterns])

        field_name_format = QTextCharFormat()
        field_name_format.setForeground(QColor("#00FF7F"))
        field_names = []
        for table in Tables:
            field_names.extend(getFieldNames(table.name))
        for table in ExclusiveDbTables:
            field_names.extend(getAllFieldNames(table.name, False))
        field_name_patterns = ["\\b{fn}\\b".format(fn=field_name) for field_name in field_names]
        self.highlightingRules.extend([(QRegExp(pattern), field_name_format) for pattern in field_name_patterns])
Example #8
0
    def highlightBlock(self, text):
        myClassFormat = QTextCharFormat()
        myClassFormat.setFontWeight(QFont.Bold)

        expression = QRegularExpression(self.pattern)
        i = expression.globalMatch(text)

        while i.hasNext():
            match = i.next()
            myClassFormat.setForeground(
                self.tagColorMap[match.capturedTexts()[0]])
            self.setFormat(match.capturedStart(), match.capturedLength(),
                           myClassFormat)
Example #9
0
def format(color, style=''):
    """Return a QTextCharFormat with the given attributes.
    """
    _color = QColor(color[0], color[1], color[2])

    _format = QTextCharFormat()
    _format.setFontFamily("Courier New")
    _format.setForeground(_color)
    if 'bold' in style:
        _format.setFontWeight(QFont.Bold)
    if 'italic' in style:
        _format.setFontItalic(True)

    return _format
Example #10
0
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
Example #11
0
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
Example #12
0
    def get_format(cls, color: str, style='', fontsize=None) -> QTextCharFormat:
        """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)

        if fontsize:
            _format.setFontPointSize(fontsize)

        return _format
Example #13
0
def formatColor(color, style=None):
    """Return a QTextCharFormat with the given attributes.
    :param color: float3 rgb
    :type color: tuple
    :param style: the style name eg. 'bold'
    :type style: str or None
    """
    style = style or ""
    _color = QColor(*color)
    _format = QTextCharFormat()
    _format.setForeground(_color)
    if "bold" in style:
        _format.setFontWeight(QFont.Bold)
    if "italic" in style:
        _format.setFontItalic(True)

    return _format
Example #14
0
 def formatText(cls, color, style=""):
     """
     Return a QTextCharFormat with the given attributes.
     """
     
     clr = QColor(*color)
 
     txt_format = QTextCharFormat()
     txt_format.setForeground(clr)
     
     if "bold" in style:
         txt_format.setFontWeight(QFont.Bold)
         
     if "italic" in style:
         txt_format.setFontItalic(True)
 
     return txt_format    
Example #15
0
    def newLetter(self):
        self.textEdit.clear()

        cursor = self.textEdit.textCursor()
        cursor.movePosition(QTextCursor.Start)
        topFrame = cursor.currentFrame()
        topFrameFormat = topFrame.frameFormat()
        topFrameFormat.setPadding(16)
        topFrame.setFrameFormat(topFrameFormat)
        #        timer = QTimer(self)
        #        timer.timeout.connect(self.showTime)
        #        timer.start(1000)
        textFormat = QTextCharFormat()
        boldFormat = QTextCharFormat()
        boldFormat.setFontWeight(QFont.Bold)
        italicFormat = QTextCharFormat()
        italicFormat.setFontItalic(True)

        tableFormat = QTextTableFormat()
        tableFormat.setBorder(1)
        tableFormat.setCellPadding(16)
        tableFormat.setAlignment(Qt.AlignRight)
        cursor.insertTable(1, 1, tableFormat)
        cursor.insertText("Tomasz Dróżdż", boldFormat)
        cursor.insertBlock()
        cursor.insertText("Politechnika Wrocławska", textFormat)
        cursor.insertBlock()
        cursor.insertText("Automatyka i Robotyka")
        cursor.insertBlock()
        cursor.insertText("SOLAR PANEL Program")
        cursor.setPosition(topFrame.lastPosition())
        cursor.insertText(
            QDate.currentDate().toString("Dziś jest: d MMMM yyyy:"),
            textFormat)
        cursor.insertText(QTime.currentTime().toString("  hh:mm:ss"),
                          textFormat)
        #        cursor.insertText(QTimer.timer("  hh:mm:ss", 1000), textFormat)
        cursor.insertBlock()
        cursor.insertBlock()
        cursor.insertText("Wrocław: ", textFormat)
        cursor.insertText("17.03 deg; 51.10 deg", textFormat)
        cursor.insertText(",", textFormat)
        for i in range(3):
            cursor.insertBlock()
        cursor.insertText("Text", textFormat)
Example #16
0
def format(color, style=''):
    """
    Return a QTextCharFormat with the given attributes.
    """
    _color = QColor()
    if type(color) is not str:
        _color.setRgb(color[0], color[1], color[2])
    else:
        _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
Example #17
0
    def __init__(self, document, **options):
        Formatter.__init__(self, **options)

        self.document = document

        # Prepare format by styles
        self.styles = {}
        for token, style in self.style:
            format = QTextCharFormat()
            if style['color']:
                format.setForeground(QColor('#' + style['color']))
            if style['bold']:
                format.setFontWeight(QFont.Bold)
            if style['italic']:
                format.setFontItalic(True)
            if style['underline']:
                format.setFontUnderline(True)
            self.styles[token] = format
    def newLetter(self):
        self.textEdit.clear()

        cursor = self.textEdit.textCursor()
        cursor.movePosition(QTextCursor.Start)
        topFrame = cursor.currentFrame()
        topFrameFormat = topFrame.frameFormat()
        topFrameFormat.setPadding(16)
        topFrame.setFrameFormat(topFrameFormat)

        textFormat = QTextCharFormat()
        boldFormat = QTextCharFormat()
        boldFormat.setFontWeight(QFont.Bold)
        italicFormat = QTextCharFormat()
        italicFormat.setFontItalic(True)

        tableFormat = QTextTableFormat()
        tableFormat.setBorder(1)
        tableFormat.setCellPadding(16)
        tableFormat.setAlignment(Qt.AlignRight)
        cursor.insertTable(1, 1, tableFormat)
        cursor.insertText("The Firm", boldFormat)
        cursor.insertBlock()
        cursor.insertText("321 City Street", textFormat)
        cursor.insertBlock()
        cursor.insertText("Industry Park")
        cursor.insertBlock()
        cursor.insertText("Some Country")
        cursor.setPosition(topFrame.lastPosition())
        cursor.insertText(QDate.currentDate().toString("d MMMM yyyy"),
                          textFormat)
        cursor.insertBlock()
        cursor.insertBlock()
        cursor.insertText("Dear ", textFormat)
        cursor.insertText("NAME", italicFormat)
        cursor.insertText(",", textFormat)
        for i in range(3):
            cursor.insertBlock()
        cursor.insertText("Yours sincerely,", textFormat)
        for i in range(3):
            cursor.insertBlock()
        cursor.insertText("The Boss", textFormat)
        cursor.insertBlock()
        cursor.insertText("ADDRESS", italicFormat)
Example #19
0
    def updateRules(self):
        try:
            keywordFormat = QTextCharFormat()
            keywordFormat.setForeground(QColor("#000099"))
            keywordFormat.setFontWeight(QFont.Bold)
            keywordFormat.setFontUnderline(True)
            keywordFormat.setAnchor(True)

            dict_words = self._database.getAllDictWords()
            keywordPatterns = ["\\b" + word + "\\b" for word in dict_words]
            keywordPatterns.extend(
                ["\\b" + word.upper() + "\\b" for word in dict_words])
            keywordPatterns.extend(
                ["\\b" + word.lower() + "\\b" for word in dict_words])
            self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                                      for pattern in keywordPatterns]

        except Exception as e:
            print("Failed to update the highlighting rules:", e)
Example #20
0
    def get_format(self, color, style=''):
        """
        Returns a QTextCharFormat with the given attributes
        :param color:
        :param style:
        :return:
        """
        c = QColor()
        c.setNamedColor(color)

        f = QTextCharFormat()
        f.setForeground(c)

        if 'bold' in style:
            f.setFontWeight(QFont.Bold)

        if 'italic' in style:
            f.setFontItalic(True)

        return f
Example #21
0
    def __init__(self, *args):
        super().__init__(*args)

        if FORMATS['keyword'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkBlue)
            f.setFontWeight(QFont.Bold)
            FORMATS['keyword'] = f
        if FORMATS['quotation'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            FORMATS['quotation'] = f
        if FORMATS['function'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.blue)
            f.setFontWeight(QFont.Bold)
            FORMATS['function'] = f
        if FORMATS['comment'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            f.setFontWeight(QFont.Bold)
            FORMATS['comment'] = f
    def __init__(self, parent, color_scheme=None):
        # TODO: Use the color scheme. it's not used right now
        super().__init__(parent, color_scheme=color_scheme)

        self.doc = parent  # type: QCodeDocument

        if FORMATS['keyword'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkBlue)
            f.setFontWeight(QFont.Bold)
            FORMATS['keyword'] = f
        if FORMATS['quotation'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            FORMATS['quotation'] = f
        if FORMATS['function'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.blue)
            f.setFontWeight(QFont.Bold)
            FORMATS['function'] = f
        if FORMATS['comment'] is None:
            f = QTextCharFormat()
            f.setFont(Conf.code_font)
            f.setForeground(Qt.darkGreen)
            f.setFontWeight(QFont.Bold)
            FORMATS['comment'] = f
Example #23
0
    def newLetter(self):

        self.textEdit.clear()
        self.text2 = QLabel("<b>Domyślne Współrzędne:</b><br/>"
                            "Szerokość: 51° 06' 00''<br/>"
                            "Długość: 17° 01' 00''<br/>"
                            "(Współrzędne geograficzne Wrocławia)")

        cursor = self.textEdit.textCursor()
        cursor.movePosition(QTextCursor.Start)
        topFrame = cursor.currentFrame()
        topFrameFormat = topFrame.frameFormat()
        topFrameFormat.setPadding(16)
        topFrame.setFrameFormat(topFrameFormat)
        textFormat = QTextCharFormat()
        boldFormat = QTextCharFormat()
        boldFormat.setFontWeight(QFont.Bold)
        italicFormat = QTextCharFormat()
        italicFormat.setFontItalic(True)

        tableFormat = QTextTableFormat()
        tableFormat.setBorder(1)
        tableFormat.setCellPadding(16)
        tableFormat.setAlignment(Qt.AlignRight)
        cursor.insertTable(1, 1, tableFormat)
        cursor.insertText("Domyślne Współrzędne: ", boldFormat)
        self.text2.setText(self.nameEdit.text())
        cursor.insertText
        #self.text1.setText(self.nameEdit.text())
        cursor.insertBlock()
        cursor.insertBlock()
        cursor.insertText("Szerokość: 51° 06' 00''", textFormat)
        cursor.insertBlock()
        cursor.insertBlock()
        cursor.insertText("Długość: 17° 01' 00''")
        cursor.insertBlock()
        cursor.insertBlock()
        cursor.insertText("(Współrzędne geograficzne Wrocławia)")
        cursor.setPosition(topFrame.lastPosition())
Example #24
0
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(Qt.darkBlue)
        keywordFormat.setFontWeight(QFont.Bold)

        keywordPatterns = [
            "\\bimport\\b", "\\bcomponent\\b", "\\bcommunications\\b",
            "\\bpublishes\\b", "\\bimplements\\b", "\\bsubscribesTo\\b",
            "\\brequires\\b", "\\blanguage\\b", "\\bgui\\b", "\\boptions\\b",
            "\\binnermodelviewer\\b", "\\bstateMachine\\b", "\\bmodules\\b",
            "\\bagmagent\\b"
        ]

        self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                                  for pattern in keywordPatterns]

        self.multiLineCommentFormat = QTextCharFormat()
        self.multiLineCommentFormat.setForeground(Qt.red)

        self.commentStartExpression = QRegExp("/\\*")
        self.commentEndExpression = QRegExp("\\*/")
Example #25
0
 def make_formats(self):
     self.formats = {}
     for kind, color in (
             (Syntax.NORMAL, Qt.black),
             (Syntax.CONSTANT, Qt.darkCyan),
             (Syntax.FUNCTION, Qt.blue),
             (Syntax.KEYWORD, Qt.darkBlue),
             (Syntax.NUMBER, Qt.darkRed),
             (Syntax.OPERATOR, Qt.darkMagenta),
             (Syntax.STRING, Qt.darkYellow),
             (Syntax.COMMENT, Qt.darkGreen)):
         fmt = QTextCharFormat()
         fmt.setFontFamily('Consolas' if WIN else 'Monospace')
         fmt.setFontFixedPitch(True)
         fmt.setFontStyleHint(QFont.Monospace)
         fmt.setForeground(QColor(color))
         if kind in {Syntax.CONSTANT, Syntax.FUNCTION, Syntax.KEYWORD,
                     Syntax.OPERATOR}:
             fmt.setFontCapitalization(QFont.AllUppercase)
             if kind is Syntax.KEYWORD:
                 fmt.setFontWeight(QFont.DemiBold)
         elif kind is Syntax.COMMENT:
             fmt.setFontItalic(True)
         self.formats[kind] = fmt
Example #26
0
class PythonHighlighter(QSyntaxHighlighter):
    def __init__(self, document):
        super(PythonHighlighter, self).__init__(document)

        self.keyword_format = QTextCharFormat()
        self.keyword_format.setForeground(QtGui.QBrush(
            QtGui.QColor("#804515")))
        self.keyword_format.setFontWeight(QFont.Bold)

        self.string_format = QTextCharFormat()
        self.string_format.setForeground(QtGui.QBrush(QtGui.QColor("#116611")))

        self.operator_format = QTextCharFormat()
        self.operator_format.setForeground(
            QtGui.QBrush(QtGui.QColor("#003333")))
        self.operator_format.setFontWeight(QFont.Bold)

        self.comment_format = QTextCharFormat()
        self.comment_format.setForeground(QtGui.QBrush(
            QtGui.QColor("#888888")))

        self.selector_format = QTextCharFormat()
        self.selector_format.setForeground(
            QtGui.QBrush(QtGui.QColor("#003333")))
        self.selector_format.setFontWeight(QFont.Bold)

    def highlightBlock(self, text, *args, **kwargs):
        tokens = tokenize.generate_tokens(StringIO(text).readline)

        if not tokens:
            return

        for token_type, token_string, token_start, token_end, token_line in tokens:
            if token_type == tokenize.STRING:
                self._highlight_token(token_start, token_end,
                                      self.string_format)
            elif token_type == tokenize.COMMENT:
                self._highlight_token(token_start, token_end,
                                      self.comment_format)
            elif token_type == tokenize.OP:
                self._highlight_token(token_start, token_end,
                                      self.operator_format)
            elif token_type == tokenize.NAME and token_string in python_keywords:
                self._highlight_token(token_start, token_end,
                                      self.keyword_format)
            elif token_type == tokenize.NAME and token_string in germaninum_selectors:
                self._highlight_token(token_start, token_end,
                                      self.selector_format)

    def _highlight_token(self, token_start, token_end, format):
        self.setFormat(token_start[1], token_end[1] - token_start[1], format)
Example #27
0
def reset_formats():
    f = QTextCharFormat()
    f.setForeground(QBrush(Conf.pseudocode_keyword_color))
    f.setFontWeight(QFont.Bold)
    FORMATS['keyword'] = f

    f = QTextCharFormat()
    f.setForeground(QBrush(Conf.pseudocode_quotation_color))
    FORMATS['quotation'] = f

    f = QTextCharFormat()
    f.setForeground(QBrush(Conf.pseudocode_function_color))
    f.setFontWeight(QFont.Bold)
    FORMATS['function'] = f

    f = QTextCharFormat()
    f.setForeground(QBrush(Conf.pseudocode_comment_color))
    f.setFontWeight(QFont.Bold)
    FORMATS['comment'] = f
Example #28
0
    def __init__(self, document=None):
        super().__init__(document)

        palette = QApplication.instance().palette("QTextEdit")

        # SQL Syntax highlighter rules
        # dict: pattern, font, color, minimal (not greedy)
        #  TODO : What about dark mode ?
        self.highlighting_patterns = [
            {
                # Keywords
                # \b allows to perform a "whole words only"
                "pattern":
                "|".join(("\\b%s\\b" % keyword
                          for keyword in VqlSyntaxHighlighter.sql_keywords)),
                "font":
                QFont.Bold,
                "color":
                palette.color(QPalette.Highlight),  # default: Qt.darkBlue
                "case_insensitive":
                True,
            },
            {
                # Strings simple quotes '...'
                "pattern": r"\'.*\'",
                "color": Qt.red,
                "minimal": True,  # Need to stop match as soon as possible
            },
            {
                # Strings double quotes: "..."
                "pattern": r"\".*\"",
                "color": Qt.red,
                "minimal": True,  # Need to stop match as soon as possible
            },
            {
                # Numbers
                "pattern": r"\\b[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\\b",
                "color": Qt.darkGreen,
            },
            {
                # Comments
                "pattern": r"--[^\n]*",
                "color": Qt.gray,
            },
        ]

        self.highlighting_rules = list()

        for pattern in self.highlighting_patterns:

            t_format = QTextCharFormat()
            font = pattern.get("font", None)
            if font:
                t_format.setFontWeight(font)

            color = pattern.get("color", None)
            if color:
                t_format.setForeground(color)

            regex = QRegularExpression(pattern["pattern"])
            if pattern.get("minimal", False):
                # The greediness of the quantifiers is inverted: *, +, ?, {m,n}, etc.
                # become lazy, while their lazy versions (*?, +?, ??, {m,n}?, etc.)
                # become greedy.
                # https://doc.qt.io/Qt-5/qregularexpression.html#setPatternOptions
                regex.setPatternOptions(
                    QRegularExpression.InvertedGreedinessOption)

            if pattern.get("case_insensitive", False):
                # NOTE: Deletes previous pattern options
                # Not serious in practice, this only concerns the keywords
                regex.setPatternOptions(
                    QRegularExpression.CaseInsensitiveOption)

            self.highlighting_rules.append((regex, t_format))
Example #29
0
class TextView(QPlainTextEdit):
    def __init__(self, parent: Optional[QWidget]):
        super().__init__(parent)

        self.setTabChangesFocus(True)
        self.setReadOnly(False)
        self.setCenterOnScroll(True)

        self.verticalScrollBar().valueChanged.connect(self.highlight_visible)

        self._search_term = None

        self._text_format = QTextCharFormat()
        self._text_format.setFontWeight(QFont.Bold)
        self._text_format.setForeground(Qt.darkMagenta)
        self._text_format.setBackground(Qt.yellow)

    def clear(self):
        super().clear()

    def set_text(self, text: Optional[str]):
        super().setPlainText(text)
        self.scroll_to_first_location()
        self.highlight_visible()

    def set_search_term(self, search_term: Optional[str]):
        self._search_term = search_term
        self.unhighlight()
        self.highlight_visible()

    def unhighlight(self):
        cursor = QTextCursor(self.document())
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        cursor.setCharFormat(QTextCharFormat())

    def scroll_to_first_location(self):
        cursor = self.document().find(self._search_term)
        if not cursor.isNull():
            self.setTextCursor(cursor)
            self.ensureCursorVisible()
            self.setTextCursor(QTextCursor())

    def start_cursor(self):
        return self.cursorForPosition(self.viewport().rect().topLeft())

    def end_cursor(self):
        return self.cursorForPosition(self.viewport().rect().bottomRight())

    def highlight_visible(self):
        # Might not work with RTL text
        document = self.document()
        end = self.end_cursor()

        # Highlighting is a little slow for large documents, so we limit
        # highlighting to the visible range.
        # We should be searching in the visible range (start to end), but it
        # seems like we can't do that. So we search as long as we find anything,
        # and stop when it is beyond the visible range. This means that we might
        # be searching more text than we need to.
        cursor = self.start_cursor()
        while not (cursor := document.find(self._search_term,
                                           cursor)).isNull():
            if cursor.position() > end.position():
                break

            cursor.setCharFormat(self._text_format)
Example #30
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
Example #31
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.assertTrue(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.assertTrue(b.parentFrame(), items[i].parentFrame())
            b.__isub__(1)
            i -= 1