Example #1
0
    def highlightHorizontalLine(self, text, cursor, bf, strt):
        found = False
        for mo in re.finditer(self.MARKDOWN_KEYS_REGEX['HR'],text):
            prevBlock = self.currentBlock().previous()
            prevCursor = QTextCursor(prevBlock)
            prev = prevBlock.text()
            prevAscii = str(prev.replace(u'\u2029','\n'))
            if prevAscii.strip():
                #print "Its a header"
                prevCursor.select(QTextCursor.LineUnderCursor)
                #prevCursor.setCharFormat(self.MARKDOWN_KWS_FORMAT['Header'])
                formatRange = QTextLayout.FormatRange()
                formatRange.format = self.MARKDOWN_KWS_FORMAT['Header']
                formatRange.length = prevCursor.block().length()
                formatRange.start = 0
                prevCursor.block().layout().setAdditionalFormats([formatRange])
            self.setFormat(mo.start()+strt, mo.end() - mo.start(), self.MARKDOWN_KWS_FORMAT['HR'])

        for mo in re.finditer(self.MARKDOWN_KEYS_REGEX['eHR'],text):
            prevBlock = self.currentBlock().previous()
            prevCursor = QTextCursor(prevBlock)
            prev = prevBlock.text()
            prevAscii = str(prev.replace(u'\u2029','\n'))
            if prevAscii.strip():
                #print "Its a header"
                prevCursor.select(QTextCursor.LineUnderCursor)
                #prevCursor.setCharFormat(self.MARKDOWN_KWS_FORMAT['Header'])
                formatRange = QTextLayout.FormatRange()
                formatRange.format = self.MARKDOWN_KWS_FORMAT['Header']
                formatRange.length = prevCursor.block().length()
                formatRange.start = 0
                prevCursor.block().layout().setAdditionalFormats([formatRange])
            self.setFormat(mo.start()+strt, mo.end() - mo.start(), self.MARKDOWN_KWS_FORMAT['HR'])
        return found
Example #2
0
    def check(self):

        cursor = self.textCursor()
        block = cursor.block()
        expression = QRegExp("\\w{120,}\\b")
        if len(block.text()) > 120:
            index = 0  # expression.indexIn(block.text())
            layout = block.layout()
            ranges = layout.formats()
            format = QTextCharFormat()
            format.setUnderlineStyle(QTextCharFormat.WaveUnderline)
            format.setUnderlineColor(QColor("#FF0000"))

            # while index >= 0:
            length = len(block.text())  # expression.matchedLength()
            formatrange = QTextLayout.FormatRange()

            formatrange.format = format
            formatrange.length = length
            formatrange.start = index

            ranges.append(formatrange)

            layout.setFormats(ranges)
            self.document().markContentsDirty(block.position(), block.length())
            QToolTip.showText(
                QCursor.pos(),
                "Line too long: {} > 120".format(len(block.text())))
Example #3
0
    def highlightBlocks(self, justOpened=False):

        if justOpened:  # Highlight more than the user can see

            self.visibleTextBlocks = self.onFirstOpen()

        for block in self.visibleTextBlocks:

            layout = block.layout()

            ranges = layout.formats()
            for pattern, format in self.highlightingRules:
                expression = QRegExp(pattern)
                index = expression.indexIn(block.text())
                while index >= 0:
                    length = expression.matchedLength()
                    formatrange = QTextLayout.FormatRange()

                    formatrange.format = format
                    formatrange.length = length
                    formatrange.start = index

                    ranges.append(formatrange)

                    layout.setFormats(ranges)
                    self.editor.document().markContentsDirty(
                        block.position(), block.length()
                    )
                    index = expression.indexIn(block.text(), index + length)
Example #4
0
    def highlightOneBlock(self, block):

        layout = block.layout()
        if not layout:
            return self.editor.blockCount()

        ranges = layout.formats()

        if len(ranges) > 0:
            ranges.clear()

        for pattern, format in self.highlightingRules:
            expression = QRegExp(pattern)
            index = expression.indexIn(block.text())

            while index >= 0:
                length = expression.matchedLength()
                formatrange = QTextLayout.FormatRange()

                formatrange.format = format
                formatrange.length = length
                formatrange.start = index

                ranges.append(formatrange)

                layout.setFormats(ranges)
                self.editor.document().markContentsDirty(
                    block.position(), block.length()
                )
                index = expression.indexIn(block.text(), index + length)
Example #5
0
    def formatting(self) -> List[QTextLayout.FormatRange]:
        """
        Determine the formatting rules of the display text.
        """
        if self.select_size == 0:
            return []

        selection = QTextLayout.FormatRange()
        selection.start = self.select_start
        selection.length = self.select_size
        selection.format.setBackground(self.palette().brush(
            QPalette.Highlight))
        selection.format.setForeground(self.palette().brush(
            QPalette.HighlightedText))
        return [selection]
Example #6
0
    def _applyHighlightedSegments(self, block, highlightedSegments):
        ranges = []
        currentPos = 0

        for length, format in highlightedSegments:
            if format is not None:  # might be in incorrect syntax file
                range = QTextLayout.FormatRange()
                range.format = format
                range.start = currentPos
                range.length = length
                ranges.append(range)
            currentPos += length

        if not _formatRangeListsEqual(block.layout().additionalFormats(),
                                      ranges):
            block.layout().setAdditionalFormats(ranges)
            self._document.markContentsDirty(block.position(), block.length())
Example #7
0
    def __init__(self, parent):
        QLineEdit.__init__(self, parent)
        self.tags: List[Tag] = [Tag("", QRectF())]
        self.blink_timer: int = 0
        self.cursor_ind: int = 0
        self.blink_status: bool = True
        self.select_start: int = 0
        self.select_size: int = 0
        self.text_layout: QTextLayout = QTextLayout()
        self.editing_index: int = 0  # The position of the tag being edited
        self.set_cursor_visible(self.hasFocus())

        self.move_cursor(0, False)
        self.update_display_text()
        self.compute_tag_rects()

        self.update()
    def paintEvent(self, event):
        if self.elideMode == 0:  # if not set then behave as a normal label
            QLabel.paintEvent(self, event)
        else:
            QFrame.paintEvent(self, event)
            painter = QPainter(self)
            painter.setFont(self.font())

            # gets the spacing between lines
            lineSpacing = self.fontMetrics().lineSpacing()
            y = 0

            textLayout = QTextLayout(self.text(), self.font())
            textLayout.beginLayout()

            # loops  til the end of line
            while True:
                # create a line
                line = textLayout.createLine()

                if line.isValid() != True:
                    break
                self.lines += 1
                # set limit of line width
                line.setLineWidth(self.width())
                # calculate position of next line
                nextLineY = y + lineSpacing

                if self.height() >= nextLineY + lineSpacing:
                    line.draw(painter, QPoint(0, y))
                    y = nextLineY
                else:  # regenerate each line so that they do not overflow the width of widget
                    lastLine = self.text()[line.textStart():len(self.text())]
                    elidedLastLine = self.fontMetrics().elidedText(
                        lastLine, Qt.ElideRight, self.width())
                    painter.drawText(
                        QPoint(0, y + self.fontMetrics().ascent()),
                        elidedLastLine)
                    line = textLayout.createLine()
                    break
            textLayout.endLayout()
Example #9
0
 def new_format_range(r, offset=0):
     n = QTextLayout.FormatRange()
     n.format = r.format
     n.start = r.start + offset
     n.length = r.length
     return n
Example #10
0
    def draw_highlighting(self, root, start, end, interruptible=False):
        """Draw the highlighting using tree ``root`` from ``start`` to ``end``.

        If ``interruptible`` is True, ``QApplication::process_events()`` is
        called every 1000 lines, to enable the user typing in the document,
        which also causes the highlighting to quit and resume later.

        """
        if not self._formatter:
            return

        doc = self.document()

        if interruptible:
            c = self._cursor
            if c:
                # our previous highlighting run was interrupted, fix it now
                start = min(start, c.selectionStart())
                end = max(end, c.selectionEnd())
            else:
                c = self._cursor = QTextCursor(doc)
                c.setKeepPositionOnInsert(True)
        else:
            c = None

        block = doc.findBlock(start)
        pos = block.position()
        last_block = doc.findBlock(end)
        if not last_block.isValid():
            last_block = doc.lastBlock()
        end = last_block.position() + last_block.length() - 1

        if c:
            c.setPosition(end)

        num = block.blockNumber() + 100
        formats = split_formats(block, start)[0]
        for f in self._formatter.format_ranges(root, start, end):
            while f.pos >= pos + block.length():
                block.layout().setFormats(formats)
                block = block.next()
                pos = block.position()
                formats = []
            r = QTextLayout.FormatRange()
            r.format = f.textformat
            r.start = f.pos - pos
            f_end = min(end, f.end)
            while f_end > pos + block.length():
                r.length = block.length() - r.start - 1
                formats.append(r)
                block.layout().setFormats(formats)
                block = block.next()
                pos = block.position()
                formats = []
                r = QTextLayout.FormatRange()
                r.format = f.textformat
                r.start = 0
            r.length = f_end - pos - r.start
            formats.append(r)
            if c and block.blockNumber() > num:
                num = block.blockNumber() + 1000
                doc.markContentsDirty(start, pos - start)
                start = pos
                c.setPosition(start, QTextCursor.KeepAnchor)
                revision = doc.revision()
                QGuiApplication.processEvents(
                    QEventLoop.ExcludeSocketNotifiers)
                # if the user typed, immediately quit, but come back!
                if doc.revision() != revision:
                    return
        block.layout().setFormats(formats)
        while block < last_block:
            block = block.next()
            block.layout().clearFormats()
        doc.markContentsDirty(start, end - start)
        # we have finished highlighting
        if c:
            self._cursor = None
Example #11
0
	def text_layout(self, text, width, font, font_metrics):
		"Lays out wrapped text"
		text_option = QTextOption(Qt.AlignCenter)
		text_option.setUseDesignMetrics(True)
		text_option.setWrapMode(QTextOption.WordWrap)
		layout = QTextLayout(text, font)
		layout.setTextOption(text_option)
		leading = font_metrics.leading()
		height = 0
		layout.setCacheEnabled(True)
		layout.beginLayout()
		while True:
			line = layout.createLine()
			if not line.isValid():
				break
			line.setLineWidth(width)
			height += leading
			line.setPosition(QPointF(0, height))
			height += line.height()
		layout.endLayout()
		return layout