Example #1
0
    def unindent(self):
        cursor = self._neditor.textCursor()
        start_block = self._neditor.document().findBlock(
            cursor.selectionStart())
        end_block = self._neditor.document().findBlock(cursor.selectionEnd())

        position = cursor.position()
        if position == 0:
            return

        if start_block != end_block:
            # Unindent multiple lines
            block = start_block
            stop_block = end_block.next()
            while block != stop_block:
                indentation = self.__block_indentation(block)
                if indentation.endswith(self.text()):
                    cursor = QTextCursor(block)
                    cursor.setPosition(block.position() + len(indentation))
                    cursor.setPosition(cursor.position() - self.WIDTH,
                                       QTextCursor.KeepAnchor)
                    cursor.removeSelectedText()
                block = block.next()
        else:
            # Unindent one line
            indentation = self.__block_indentation(start_block)
            cursor = QTextCursor(start_block)
            cursor.setPosition(start_block.position() + len(indentation))
            cursor.setPosition(cursor.position() - self.WIDTH,
                               QTextCursor.KeepAnchor)
            cursor.removeSelectedText()
Example #2
0
 def _cursor_moved(self):
     tc = QTextCursor(self.Editor.textCursor())  # copy of cursor
     self.ColNumber.setText(str(tc.positionInBlock()))
     tb = tc.block()
     if tb == self.last_text_block:
         return  # still on same line, nothing more to do
     # Fill in line-number widget, line #s are origin-1
     self.LineNumber.setText(str(tb.blockNumber() + 1))
     # Fill in the image name and folio widgets
     pn = self.page_model.page_index(tc.position())
     if pn is not None:  # the page model has info on this position
         self.ImageFilename.setText(self.page_model.filename(pn))
         self.Folio.setText(self.page_model.folio_string(pn))
     else:  # no image data, or cursor is above page 1
         self.ImageFilename.setText('')
         self.Folio.setText('')
     # Change the current-line "extra selection" to the new current line.
     # Note: the cursor member of the extra selection may not have a
     # selection. If it does, the current line highlight disappears. The
     # cursor "tc" may or may not have a selection; to make sure, we clone
     # it and remove any selection from it.
     cltc = QTextCursor(tc)
     cltc.setPosition(tc.position(), QTextCursor.MoveAnchor)
     # Set the cloned cursor into the current line extra selection object.
     self.current_line_sel.cursor = cltc
     # Re-assign the list of extra selections to force update of display.
     self.Editor.setExtraSelections(self.extra_sel_list)
Example #3
0
    def edit(self, cursor):
        """Edit the block at the specified QTextCursor."""
        if self._document:
            self._document.closed.disconnect(self.reject)
        self._document = cursor.document()
        self._document.closed.connect(self.reject)

        # don't change the cursor
        c = self._range = QTextCursor(cursor)
        cursorpos = c.position() - c.block().position()
        cursortools.strip_indent(c)
        indentpos = c.position() - c.block().position()
        c.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
        self.view.setPlainText(c.selection().toPlainText())

        self.highlighter.setInitialState(
            tokeniter.state(cursortools.block(cursor)))
        self.highlighter.setHighlighting(
            metainfo.info(cursor.document()).highlighting)
        self.highlighter.rehighlight()

        # let autocomplete query the real document as if we're at the start
        # of the current block
        self.completer.document_cursor = QTextCursor(cursor.block())
        self.completer.autoComplete = QSettings().value(
            "autocomplete", True, bool)

        cursor = self.view.textCursor()
        cursor.setPosition(max(0, cursorpos - indentpos))
        self.view.setTextCursor(cursor)

        self.updateMessage()
Example #4
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 #5
0
    def update_minimap_doc(self, position, charsRemoved, charsAdded):
        def select_blocks(first_block, last_block):
            first_block_pos = first_block.position()
            doc_cursor.setPosition(first_block_pos)
            last_block_pos = last_block.position()
            doc_cursor.setPosition(last_block_pos, QTextCursor.KeepAnchor)
            doc_cursor.movePosition(QTextCursor.EndOfBlock,
                                    QTextCursor.KeepAnchor)
            print("selected text :", doc_cursor.selectedText())
            return doc_cursor.selectedText()

        doc_cursor = QTextCursor(self._doc)
        minimap_cursor = QTextCursor(self._minimap_doc)

        # IF one same block is modified
        if self._minimap_doc.blockCount() == self._doc.blockCount():
            doc_cursor.setPosition(position)
            doc_cursor.select(QTextCursor.BlockUnderCursor)
            minimap_cursor.setPosition(position)
            minimap_cursor.select(QTextCursor.BlockUnderCursor)
            minimap_cursor.insertFragment(doc_cursor.selection())
        # TODO: if the doc is modified on more than one block but resulting in
        # the same count of blocks (right now only the first block would be
        # updated)
        else:
            # ELSE
            doc_cursor.select(QTextCursor.Document)
            minimap_cursor.select(QTextCursor.Document)
            minimap_cursor.insertFragment(doc_cursor.selection())
Example #6
0
 def highlightError(self, index):
     """Hihglights the error message at the given index and jumps to its location."""
     self._currentErrorIndex = index
     # set text format
     pos, anchor, url = self._errors[index]
     es = QTextEdit.ExtraSelection()
     es.cursor = QTextCursor(self.document())
     es.cursor.setPosition(pos)
     es.cursor.setPosition(anchor, QTextCursor.KeepAnchor)
     bg = qutil.mixcolor(self.palette().highlight().color(),
                         self.palette().base().color(), 0.4)
     es.format.setBackground(bg)
     es.format.setProperty(QTextFormat.FullWidthSelection, True)
     self.setExtraSelections([es])
     # scroll log to the message
     cursor = QTextCursor(self.document())
     cursor.setPosition(anchor)
     self.setTextCursor(cursor)
     cursor.setPosition(pos)
     self.setTextCursor(cursor)
     # jump to the error location
     cursor = errors.errors(self._document()).cursor(url, True)
     if cursor:
         self.parentWidget().mainwindow().setTextCursor(cursor,
                                                        findOpenView=True)
 def highlightBlockBefore(self, text):
     """Highlighting to do before anything else.
     
     When subclassing basicHighlighter, you must call highlightBlockBefore
     before you do any custom highlighting.
     """
     bf = QTextBlockFormat(self._defaultBlockFormat)
     bf.setAlignment(QTextCursor(self.currentBlock()).blockFormat().alignment())
     QTextCursor(self.currentBlock()).setBlockFormat(bf)
Example #8
0
def insert_python(text, cursor, name, view):
    """Regards the text as Python code, and exec it.

    name and view are given in case an exception occurs.

    The following variables are available:

    - text: contains selection or '', set it to insert new text
    - state: contains simplestate for the cursor position
    - cursor: the QTextCursor

    After the insert, the cursor points to the end of the inserted snippet.

    """
    namespace = {
        'cursor': QTextCursor(cursor),
        'state': state(cursor),
        'text': cursor.selection().toPlainText(),
        'view': view,
        'ANCHOR': 1,
        'CURSOR': 2,
    }
    try:
        code = compile(text, "<snippet>", "exec")
        if sys.version_info < (3, 0):
            exec("exec code in namespace")
        else:
            exec(code, namespace)
        if 'main' in namespace:
            return namespace['main']()
    except Exception:
        handle_exception(name, view)
    else:
        text = namespace.get('text', '')
        if isinstance(text, (tuple, list)):
            ANCHOR = namespace.get('ANCHOR', 1)
            CURSOR = namespace.get('CURSOR', 2)
            a, c = -1, -1
            for t in text:
                if t == ANCHOR:
                    a = cursor.selectionStart()
                elif t == CURSOR:
                    c = cursor.selectionStart()
                else:
                    cursor.insertText(t)
            if (a, c) != (-1, -1):
                new = QTextCursor(cursor)
                if a != -1:
                    new.setPosition(a)
                if c != -1:
                    new.setPosition(
                        c, QTextCursor.KeepAnchor
                        if a != -1 else QTextCursor.MoveAnchor)
                return new
        else:
            cursor.insertText(namespace['text'])
Example #9
0
 def _insert_byte(self, cursor, b):
     f = QTextImageFormat()
     f2 = QTextCursor().charFormat()
     cursor.document().addResource(QTextDocument.ImageResource,
                                   QUrl(self.byte_url),
                                   HextEditor.byte_image)
     f.setName(self.byte_url)
     f.setProperty(HextEditor.byte_property, b + 1)
     f.setProperty(HextEditor.nonce_property, next(self.byte_nonce))
     cursor.insertImage(f)
     cursor.setCharFormat(QTextCursor().charFormat())
Example #10
0
    def keywordHighlight(self, doc):
        cursor = QTextCursor(doc)
        cursor.beginEditBlock()
        fmt = QTextCharFormat()
        fmt.setBackground(Qt.darkYellow)

        highlightCursor = QTextCursor(doc)
        while not highlightCursor.isNull() and not highlightCursor.atEnd():
            highlightCursor = doc.find(self.keyword, highlightCursor)
            if not highlightCursor.isNull():
                highlightCursor.mergeCharFormat(fmt)
        cursor.endEditBlock()
Example #11
0
 def _removeBlock(blockIndex):
     block = self._doc.findBlockByNumber(blockIndex)
     if block.next().isValid():  # not the last
         cursor = QTextCursor(block)
         cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor)
     elif block.previous().isValid():  # the last, not the first
         cursor = QTextCursor(block.previous())
         cursor.movePosition(QTextCursor.EndOfBlock)
         cursor.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor)
         cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
     else:  # only one block
         cursor = QTextCursor(block)
         cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
     cursor.removeSelectedText()
Example #12
0
    def highlightSearch(self, wordList=None, regExpList=None):
        """Highlight any found search terms.

        Arguments:
            wordList -- list of words to highlight
            regExpList -- a list of regular expression objects to highlight
        """
        backColor = self.palette().brush(QPalette.Active, QPalette.Highlight)
        foreColor = self.palette().brush(QPalette.Active,
                                         QPalette.HighlightedText)
        if wordList is None:
            wordList = []
        if regExpList is None:
            regExpList = []
        for regExp in regExpList:
            for match in regExp.finditer(self.toPlainText()):
                matchText = match.group()
                if matchText not in wordList:
                    wordList.append(matchText)
        selections = []
        for word in wordList:
            while self.find(word):
                extraSel = QTextEdit.ExtraSelection()
                extraSel.cursor = self.textCursor()
                extraSel.format.setBackground(backColor)
                extraSel.format.setForeground(foreColor)
                selections.append(extraSel)
        cursor = QTextCursor(self.document())
        self.setTextCursor(cursor)  # reset main cursor/selection
        self.setExtraSelections(selections)
Example #13
0
 def append(self, text):
     """Append line to the end
     """
     cursor = QTextCursor(self._doc)
     cursor.movePosition(QTextCursor.End)
     cursor.insertBlock()
     cursor.insertText(text)
Example #14
0
    def cmdJoinLines(self, cmd, repeatLineCount=None):
        if repeatLineCount is not None:
            self._selectRangeForRepeat(repeatLineCount)

        start, end = self._selectedLinesRange()
        count = end - start

        if not count:  # nothing to join
            return

        self._saveLastEditLinesCmd(cmd, end - start + 1)

        cursor = QTextCursor(self._qpart.document().findBlockByNumber(start))
        with self._qpart:
            for _ in range(count):
                cursor.movePosition(QTextCursor.EndOfBlock)
                cursor.movePosition(QTextCursor.NextCharacter,
                                    QTextCursor.KeepAnchor)
                self.moveToFirstNonSpace(cursor, QTextCursor.KeepAnchor)
                nonEmptyBlock = cursor.block().length() > 1
                cursor.removeSelectedText()
                if nonEmptyBlock:
                    cursor.insertText(' ')

        self._qpart.setTextCursor(cursor)
Example #15
0
 def test_indentLessWithSelection(self):
     self.document.setPlainText('    foo\n    bar\nbaz')
     cursor = QTextCursor(self.document)
     cursor.setPosition(5)
     cursor.setPosition(11, QTextCursor.KeepAnchor)
     documentIndentLess(self.document, cursor, self.settings)
     self.assertEqual('foo\nbar\nbaz', self.document.toPlainText())
Example #16
0
    def drawContents(self, painter):
        """
        Reimplementation of drawContents to limit the drawing
        inside `textRext`.

        """
        painter.setPen(self.__color)
        painter.setFont(self.font())

        if self.__textRect:
            rect = self.__textRect
        else:
            rect = self.rect().adjusted(5, 5, -5, -5)
        if Qt.mightBeRichText(self.__message):
            doc = QTextDocument()
            doc.setHtml(self.__message)
            doc.setTextWidth(rect.width())
            cursor = QTextCursor(doc)
            cursor.select(QTextCursor.Document)
            fmt = QTextBlockFormat()
            fmt.setAlignment(self.__alignment)
            cursor.mergeBlockFormat(fmt)
            painter.save()
            painter.translate(rect.topLeft())
            doc.drawContents(painter)
            painter.restore()
        else:
            painter.drawText(rect, self.__alignment, self.__message)
Example #17
0
 def abrirConFormato(self,file_text):
     count=0
     for f in file_text:
         count+=1
         if count<40:
             if f[0]=='.':                     
                 self.ui.cancionTE.setTextColor(QtGui.QColor("blue"))
                 self.ui.cancionTE.setFontWeight(QtGui.QFont.Bold)
                 self.ui.cancionTE.setFontPointSize(10)
                 self.ui.cancionTE.append(f.strip('\n'))
             if f[0]!='.':
                 self.ui.cancionTE.setTextColor(QtGui.QColor("black"))
                 self.ui.cancionTE.setFontWeight(QtGui.QFont.Bold)
                 self.ui.cancionTE.setFontPointSize(10)                            
                 self.ui.cancionTE.append(f.strip('\n'))
         if count>=40:
             if f[0]=='.':                     
                 self.ui.cancionTE2.setTextColor(QtGui.QColor("blue"))
                 self.ui.cancionTE2.setFontWeight(QtGui.QFont.Bold)
                 self.ui.cancionTE2.setFontPointSize(10)
                 self.ui.cancionTE2.append(f.strip('\n'))
             if f[0]!='.':
                 self.ui.cancionTE2.setTextColor(QtGui.QColor("black"))
                 self.ui.cancionTE2.setFontWeight(QtGui.QFont.Bold)
                 self.ui.cancionTE2.setFontPointSize(10)                            
                 self.ui.cancionTE2.append(f.strip('\n'))
     #posicionar cursor arriba
     cursor = QTextCursor(self.ui.cancionTE2.document())
     cursor.setPosition(0)
     self.ui.cancionTE2.setTextCursor(cursor)
Example #18
0
    def load(self, url=None, encoding=None, keepUndo=False):
        """Load the specified or current url (if None was specified).

        Currently only local files are supported. An IOError is raised
        when trying to load a nonlocal URL.

        If loading succeeds and an url was specified, the url is made the
        current url (by calling setUrl() internally).

        If keepUndo is True, the loading can be undone (with Ctrl-Z).

        """
        if url is None:
            url = QUrl()
        u = url if not url.isEmpty() else self.url()
        text = self.load_data(u, encoding or self._encoding)
        if keepUndo:
            c = QTextCursor(self)
            c.select(QTextCursor.Document)
            c.insertText(text)
        else:
            self.setPlainText(text)
        self.setModified(False)
        if not url.isEmpty():
            self.setUrl(url)
Example #19
0
def spanner_positions(cursor):
    """Return a list with 0 to 2 QTextCursor instances.

    At the first cursor a starting spanner item can be inserted, at the
    second an ending item.

    """
    c = lydocument.cursor(cursor)
    if cursor.hasSelection():
        partial = ly.document.INSIDE
    else:
        # just select until the end of the current line
        c.select_end_of_block()
        partial = ly.document.OUTSIDE

    items = list(ly.rhythm.music_items(c, partial=partial))
    if cursor.hasSelection():
        del items[1:-1]
    else:
        del items[2:]

    positions = []
    for i in items:
        c = QTextCursor(cursor.document())
        c.setPosition(i.end)
        positions.append(c)
    return positions
Example #20
0
 def setLine(self, line):
     cursor = QTextCursor(self.document())
     cursor.movePosition(QTextCursor.End)
     cursor.setPosition(self.newPromptPos, QTextCursor.KeepAnchor)
     cursor.removeSelectedText()
     cursor.insertText(line)
     self.setTextCursor(cursor)
Example #21
0
    def mousePressEvent(self, event):
        """Handle ctrl + click to follow links.

        Arguments:
            event -- the mouse event
        """
        if (event.button() == Qt.LeftButton
                and event.modifiers() == Qt.ControlModifier):
            cell = self.itemAt(event.pos())
            if cell and isinstance(cell, DataEditCell):
                xOffest = (event.pos().x() -
                           self.columnViewportPosition(cell.column()))
                yOffset = (event.pos().y() -
                           self.rowViewportPosition(cell.row()))
                pt = QPointF(xOffest, yOffset)
                pos = cell.doc.documentLayout().hitTest(pt, Qt.ExactHit)
                if pos >= 0:
                    cursor = QTextCursor(cell.doc)
                    cursor.setPosition(pos)
                    address = cursor.charFormat().anchorHref()
                    if address:
                        if address.startswith('#'):
                            (self.treeView.selectionModel().selectNodeById(
                                address[1:]))
                        else:  # check for relative path
                            if urltools.isRelative(address):
                                defaultPath = (
                                    globalref.mainControl.defaultPathObj(True))
                                address = urltools.toAbsolute(
                                    address, str(defaultPath))
                            dataeditors.openExtUrl(address)
            event.accept()
        else:
            super().mousePressEvent(event)
Example #22
0
 def lineNumberAreaWidth(self):
     if not globalSettings.lineNumbersEnabled:
         return 0
     cursor = QTextCursor(self.document())
     cursor.movePosition(QTextCursor.End)
     digits = len(str(cursor.blockNumber() + 1))
     return 5 + self.fontMetrics().width('9') * digits
Example #23
0
    def highlight(self, document: QTextDocument, rules: list):
        """Highlights document"""
        char_format = QTextCharFormat()
        cursor = QTextCursor(document)

        while not cursor.isNull() and not cursor.atEnd():
            cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor)

            text = cursor.selectedText()
            color, bgcolor = self.get_register_hl_color(
                text, self.highlighted_regs)

            if not color:
                color, bgcolor = self.get_color(text, rules)

            if color:
                char_format.setForeground(QColor(color))

            if bgcolor:
                char_format.setBackground(QColor(bgcolor))

            if color or bgcolor:
                cursor.mergeCharFormat(char_format)
                char_format.clearBackground()

            self.move_to_next_word(document, cursor)
Example #24
0
def articulation_positions(cursor):
    """Returns a list of positions where an articulation can be added.
    
    Every position is given as a QTextCursor instance.
    If the cursor has a selection, all positions in the selection are returned.
    
    """
    c = lydocument.cursor(cursor)
    if not cursor.hasSelection():
        # just select until the end of the current line
        c.select_end_of_block()
        rests = True
        partial = ly.document.OUTSIDE
    else:
        rests = False
        partial = ly.document.INSIDE

    positions = []
    for item in ly.rhythm.music_items(c, partial):
        if not rests and item.tokens and isinstance(item.tokens[0],
                                                    ly.lex.lilypond.Rest):
            continue
        csr = QTextCursor(cursor.document())
        csr.setPosition(item.end)
        positions.append(csr)
        if not cursor.hasSelection():
            break  # leave if first found, that's enough
    return positions
 def handlePaintRequest(self, printer):
     printer.setDocName(self.fname)
     document = QTextDocument()
     cursor = QTextCursor(document)
     model = self.tableView.model()
     tableFormat = QTextTableFormat()
     tableFormat.setBorder(0.2)
     tableFormat.setBorderStyle(3)
     tableFormat.setCellSpacing(0)
     tableFormat.setTopMargin(0)
     tableFormat.setCellPadding(4)
     table = cursor.insertTable(model.rowCount() + 1, model.columnCount(),
                                tableFormat)
     model = self.tableView.model()
     ### get headers
     myheaders = []
     for i in range(0, model.columnCount()):
         myheader = model.headerData(i, Qt.Horizontal)
         cursor.insertText(str(myheader))
         cursor.movePosition(QTextCursor.NextCell)
     ### get cells
     for row in range(0, model.rowCount()):
         for col in range(0, model.columnCount()):
             index = model.index(row, col)
             cursor.insertText(str(index.data()))
             cursor.movePosition(QTextCursor.NextCell)
     document.print_(printer)
Example #26
0
 def actionTriggered(self, name):
     # convert arpeggio_normal to arpeggioNormal, etc.
     name = _arpeggioTypes[name]
     cursor = self.mainwindow().textCursor()
     # which arpeggio type is last used?
     lastused = '\\arpeggioNormal'
     types = set(_arpeggioTypes.values())
     block = cursor.block()
     while block.isValid():
         s = types.intersection(tokeniter.tokens(block))
         if s:
             lastused = s.pop()
             break
         block = block.previous()
     # where to insert
     c = lydocument.cursor(cursor)
     c.select_end_of_block()
     with cursortools.compress_undo(cursor):
         for item in ly.rhythm.music_items(c, partial=ly.document.OUTSIDE):
             c = QTextCursor(cursor.document())
             c.setPosition(item.end)
             c.insertText('\\arpeggio')
             if name != lastused:
                 cursortools.strip_indent(c)
                 indent = c.block().text()[:c.position() -
                                           c.block().position()]
                 c.insertText(name + '\n' + indent)
             # just pick the first place
             return
Example #27
0
    def indent_selection(self):
        """Indent selection after tab pressed"""

        def indent_block(block):
            cursor = QTextCursor(block)
            indentation = self.block_indent(block)
            cursor.setPosition(block.position() + len(indentation))
            cursor.insertText(self.text())

        cursor = self._neditor.textCursor()
        start_block = self._neditor.document().findBlock(
            cursor.selectionStart())
        end_block = self._neditor.document().findBlock(
            cursor.selectionEnd())

        with self._neditor:
            if start_block != end_block:
                stop_block = end_block.next()
                # Indent multiple lines
                block = start_block
                while block != stop_block:
                    indent_block(block)
                    block = block.next()
                new_cursor = QTextCursor(start_block)
                new_cursor.setPosition(
                    end_block.position() + len(end_block.text()),
                    QTextCursor.KeepAnchor)
                self._neditor.setTextCursor(new_cursor)
            else:
                # Indent one line
                indent_block(start_block)
Example #28
0
    def highlight_ascii(self) -> None:
        """Bidirectional highlighting from ascii"""

        # Create and get cursors for getting and setting selections.
        highlight_cursor = QTextCursor(self.main_text_area.document())
        cursor = self.ascii_text_area.textCursor()

        # Clear any current selections and reset text color.
        highlight_cursor.select(QTextCursor.Document)
        highlight_cursor.setCharFormat(QTextCharFormat())
        highlight_cursor.clearSelection()

        # Information about where selections and rows start.
        selected_text = cursor.selectedText()  # The actual text selected.
        selection_start = cursor.selectionStart()

        ascii_text = self.ascii_text_area.toPlainText().replace('\n', '')
        main_start = self.__get_valuable_positions_length(ascii_text[:selection_start])
        main_start = self.__positive_compensation(main_start)

        total_bytes = self.__get_valuable_positions_length(selected_text)  # get all valuable positions
        # \n and word length compensation
        total_bytes = self.__positive_compensation(total_bytes)
        selection_end = main_start + total_bytes

        # Select text and highlight it.
        highlight_cursor.setPosition(main_start, QTextCursor.MoveAnchor)
        highlight_cursor.setPosition(selection_end, QTextCursor.KeepAnchor)

        highlight = QTextCharFormat()
        highlight.setBackground(Qt.red)
        highlight_cursor.setCharFormat(highlight)
        highlight_cursor.clearSelection()
Example #29
0
 def paintEvent(self, event):
     if not globalSettings.lineNumbersEnabled:
         return QWidget.paintEvent(self, event)
     painter = QPainter(self)
     painter.fillRect(event.rect(), colorValues['lineNumberArea'])
     cursor = QTextCursor(self.editor.document())
     cursor.movePosition(QTextCursor.Start)
     atEnd = False
     if globalSettings.relativeLineNumbers:
         relativeTo = self.editor.textCursor().blockNumber()
     else:
         relativeTo = -1
     while not atEnd:
         rect = self.editor.cursorRect(cursor)
         block = cursor.block()
         if block.isVisible():
             number = str(cursor.blockNumber() - relativeTo).replace(
                 '-', '−')
             painter.setPen(colorValues['lineNumberAreaText'])
             painter.drawText(0, rect.top(),
                              self.width() - 2,
                              self.fontMetrics().height(), Qt.AlignRight,
                              number)
         cursor.movePosition(QTextCursor.EndOfBlock)
         atEnd = cursor.atEnd()
         if not atEnd:
             cursor.movePosition(QTextCursor.NextBlock)
Example #30
0
    def titleSetext(self, level):
        cursor = self.textCursor()

        cursor.beginEditBlock()
        # Is it already a Setext header?
        if cursor.block().userState() in [
                MS.MarkdownStateSetextHeading1Line2,
                MS.MarkdownStateSetextHeading2Line2
        ]:
            cursor.movePosition(QTextCursor.PreviousBlock)

        text = cursor.block().text()

        if cursor.block().userState() in [
                MS.MarkdownStateSetextHeading1Line1,
                MS.MarkdownStateSetextHeading2Line1
        ]:
            # Need to remove line below
            c = QTextCursor(cursor.block().next())
            self.selectBlock(c)
            c.insertText("")

        char = "=" if level == 1 else "-"
        text = re.sub(r"^#*\s*(.*)\s*#*", "\\1", text)  # Removes #
        sub = char * len(text)
        text = text + "\n" + sub

        self.selectBlock(cursor)
        cursor.insertText(text)
        cursor.endEditBlock()