def pixmap(cursor, num_lines=6, scale=0.8): """Return a QPixmap displaying the selected lines of the document. If the cursor has no selection, num_lines are drawn. By default the text is drawn 0.8 * the normal font size. You can change that by supplying the scale parameter. """ block = cursor.document().findBlock(cursor.selectionStart()) c2 = QTextCursor(block) if cursor.hasSelection(): c2.setPosition(cursor.selectionEnd(), QTextCursor.KeepAnchor) c2.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) else: c2.movePosition(QTextCursor.NextBlock, QTextCursor.KeepAnchor, num_lines) data = textformats.formatData('editor') doc = QTextDocument() font = QFont(data.font) font.setPointSizeF(font.pointSizeF() * scale) doc.setDefaultFont(font) doc.setPlainText(c2.selection().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlighter.highlight(doc, state=tokeniter.state(block)) size = doc.size().toSize() + QSize(8, -4) pix = QPixmap(size) pix.fill(data.baseColors['background']) doc.drawContents(QPainter(pix)) return pix
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
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)
def scrollToLine(self, lineNumber, columnNumber=None): """ Scrolls this widget’s viewport to the line *lineNumber* and sets the text cursor to that line, at *columnNumber*. If *columnNumber* is None, bookkeeping will be performed. Strictly positive numbers are expected. """ lineNumber -= 1 if columnNumber is None: columnNumber = self.textCursor().positionInBlock() else: columnNumber -= 1 scrollingUp = lineNumber < self.textCursor().blockNumber() # scroll to block textBlock = self.document().findBlockByLineNumber(lineNumber) newCursor = QTextCursor(textBlock) self.setTextCursor(newCursor) # make some headroom one, two = QTextCursor.Down, QTextCursor.Up if scrollingUp: one, two = two, one for move in (one, one, two, two): self.moveCursor(move) # address column newCursor.movePosition(QTextCursor.NextCharacter, n=columnNumber) self.setTextCursor(newCursor)
def append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
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)
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)
def write(self, data): """ This uses insertPlainText (maybe in a later version HTML, so that we can change the colour of the output) and scrolls down to the bottom of the field. The problem with append() is that it puts the inserted text in its own paragraph, which is not good if we do not want the linefeed. :param data: a unicode string :return: nothing """ # move cursor to end (in case user clicked somewhere else in the window) cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.End) self.setTextCursor(cursor) while True: # find all carriage returns i = data.find('\r') if i >= 0: # means we have to deal with a carriage return self.insertPlainText(QString(data[0:i])) cursor.select(QTextCursor.LineUnderCursor) cursor.removeSelectedText() data = data[i + 1:] else: break # insert remaining text self.insertPlainText(data) sb = self.verticalScrollBar() sb.setValue(sb.maximum())
def handlePaintRequest(self, printer): # find empty cells for row in range(self.tableView.rowCount()): for column in range(self.tableView.columnCount()): myitem = self.tableView.item(row, column) if myitem is None: item = QTableWidgetItem("") self.tableView.setItem(row, column, item) 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(), model.columnCount(), tableFormat) for row in range(table.rows()): for column in range(table.columns()): cursor.insertText(self.tableView.item(row, column).text()) cursor.movePosition(QTextCursor.NextCell) document.print_(printer)
def fixUpLine(self, line: int, newText: str, data: int): """ The receiver of the 'fixupText' signal should invoke this method to replace the line with the cleaned text and the model's matching row """ block = self.document().findBlockByLineNumber(line) if block.isValid(): if block.userData() is None: block.setUserData(self._UserData(data)) else: block.userData().row = data text = newText.strip() if not text: block.setUserState(self._State.Blank) elif data < 0: block.setUserState(self._State.Error) else: block.setUserState(self._State.Fixup) cursor = QTextCursor(block) cursor.beginEditBlock() cursor.movePosition(QTextCursor.StartOfLine) cursor.select(QTextCursor.LineUnderCursor) cursor.removeSelectedText() cursor.insertText(text) cursor.endEditBlock()
def handlePaintRequest(self,printer): """ This is the backbone main function that handles all the print functions PrintPreview and PrintCsv . This handles all the required operations like bolding the header labels and all the other things like moving the cursor for each cell row and column wise and finally printing to document. :param printer: :return: """ document = QTextDocument() cursor = QTextCursor(document) table = cursor.insertTable(self.tableWidget.rowCount(), self.tableWidget.columnCount()) fm = QTextCharFormat() font = QFont() font.setBold(True) font.setUnderline(True) fm.setFont(font) for i in range(self.tableWidget.columnCount()): col = self.tableWidget.horizontalHeaderItem(i).text() if col is not None: cursor.insertText(col,fm) cursor.movePosition(QTextCursor.NextCell) for row in range(self.tableWidget.rowCount()): for col in range(self.tableWidget.columnCount()): w = self.tableWidget.cellWidget(row, col) it = self.tableWidget.item(row, col) if w is not None: cursor.insertText(self.get_text_from_widget(w)) elif it is not None: cursor.insertText(it.text()) cursor.movePosition(QTextCursor.NextCell) document.print_(printer)
def cursor(self): """Return a QTextCursor with the same selection.""" c = QTextCursor(self.document.document) c.movePosition(QTextCursor.End) if self.end is None else c.setPosition( self.end) c.setPosition(self.start, QTextCursor.KeepAnchor) return c
class ExtraSelection(QTextEdit.ExtraSelection): def __init__(self, cursor, start_pos=None, end_pos=None, start_line=None): super().__init__() self.cursor = QTextCursor(cursor) if start_pos is not None: self.cursor.setPosition(start_pos) if end_pos is not None: self.cursor.setPosition(end_pos, QTextCursor.KeepAnchor) if start_line is not None: self.cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) self.cursor.movePosition(QTextCursor.Down, QTextCursor.MoveAnchor, start_line) def set_underline(self, color, style=QTextCharFormat.SingleUnderline): if isinstance(color, str): color = QColor(color) self.format.setUnderlineStyle(style) self.format.setUnderlineColor(color) def set_background(self, color): if isinstance(color, str): color = QColor(color) color.setAlpha(150) self.format.setBackground(color) def set_outline(self, color): self.format.setProperty(QTextFormat.OutlinePen, QPen(QColor(color))) def set_full_width(self): # self.cursor.clearSelection() self.format.setProperty(QTextFormat.FullWidthSelection, True)
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)
def show_msg(self, message): """Show message in textBrowser """ self.textEdit.append(message) # Scroll to end of the last message cursor = QTextCursor(self.textEdit.textCursor()) cursor.movePosition(QTextCursor.End) self.textEdit.setTextCursor(cursor) QApplication.processEvents()
def insertText(self, text: str) -> None: cursor = QTextCursor(self.editor.document()) cursor.movePosition(QTextCursor.End) self.editor.setTextCursor(cursor) self.editor.insertPlainText(text)
def _make_selection(self, block, index, matched): cur = QTextCursor(block) cur.setPosition(block.position() + index) cur.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) selection = ExtraSelection(cur) background = self.matched_background if not matched: background = self.unmatched_background selection.set_background(background) return selection
def lineNumberAreaWidth(self): if not globalSettings.lineNumbersEnabled: return 0 cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.MoveOperation.End) if globalSettings.relativeLineNumbers: digits = len(str(cursor.blockNumber())) + 1 else: digits = len(str(cursor.blockNumber() + 1)) return 5 + self.fontMetrics().horizontalAdvance('9') * digits
def add_debug_message(self, message): self.text_debug.append(message) while self.text_debug.document().blockCount() > 1000: cursor = QTextCursor(self.text_debug.document().begin()) cursor.select(QTextCursor.BlockUnderCursor) cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) cursor.removeSelectedText() if self.checkbox_debug_auto_scroll.isChecked(): self.text_debug.verticalScrollBar().setValue(self.text_debug.verticalScrollBar().maximum())
def write(self, s): if self.echo: sys.__stdout__.write(s) doc = self.document() cursor = QTextCursor(doc) cursor.clearSelection() cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertText(s) cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.clearSelection() self.ensureCursorVisible() qApp.processEvents()
def highlight(self): char_format = QTextCharFormat() cursor = QTextCursor(self.doc) while not cursor.isNull() and not cursor.atEnd(): cursor.movePosition(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) color = self.get_color(cursor.selectedText()) if color is not None: if self.use_darker_text_color: color = color.darker() char_format.setForeground(color) cursor.mergeCharFormat(char_format) self.move_to_next_word(self.doc, cursor)
def _insertDoc(self, code: str): # def _insertDoc(self): # self.codeReview.insertPlainText("model = Sequential()"+'\n') # code = "test" doc = self.codeReview.document() curosr = QTextCursor(doc) searchText = "model = Sequential()" tmp = doc.find(searchText, curosr) if tmp is not None: curosr.movePosition(QTextCursor.StartOfLine, QTextCursor.KeepAnchor, 0) curosr.insertText(code + '\n\n')
def new_formula(self): # встретилась фраза "новая формула" del self.queue[:] # удаляем необработанные слова del self.constraint[:] # удаляем все слова-ограничители del self.constraint_kind[:] # и их категории self.mem = '' # очищаем строку для проверки ожидаемых слов, self.kind = '' # категорию последнего слова, self.basic_notation = '' # команду tex для него, self.exp = self.exp[0:0] # словарь ожидаемых слов, self.pos = 0 # ставим указатель на текущеее слово в очереди на начало place = QTextCursor(self.text.textCursor()) # получаем копию курсора в редактируемом текстовом поле place.movePosition(QTextCursor.EndOfLine) # перемещаем курсор в конец строки self.text.setTextCursor(place) # устанавливаем новый курсор self.text.insertPlainText(' \\\\\n') # переход на новую строку
def textCursor(self): """Return a QTextCursor for our document with the same position and selection. (This method uses the Qt camelCase naming convention.) """ c = QTextCursor(self.document().document()) if self.end is None: c.movePosition(QTextCursor.End) else: c.setPosition(self.end) c.setPosition(self.start, QTextCursor.KeepAnchor) return c
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()
def slotCursorPositionChanged(self): """Called whenever the cursor position changes. Highlights matching characters if the cursor is at one of them. """ cursor = self.edit().textCursor() block = cursor.block() text = block.text() # try both characters at the cursor col = cursor.position() - block.position() end = col + 1 col = max(0, col - 1) for c in text[col:end]: if c in self.matchPairs: break col += 1 else: self.clear() return # the cursor is at a character from matchPairs i = self.matchPairs.index(c) cursor.setPosition(block.position() + col) # find the matching character new = QTextCursor(cursor) if i & 1: # look backward match = self.matchPairs[i - 1] flags = QTextDocument.FindBackward else: # look forward match = self.matchPairs[i + 1] flags = QTextDocument.FindFlags() new.movePosition(QTextCursor.Right) # search, also nesting rx = QRegExp(QRegExp.escape(c) + '|' + QRegExp.escape(match)) nest = 0 while nest >= 0: new = cursor.document().find(rx, new, flags) if new.isNull(): self.clear() return nest += 1 if new.selectedText() == c else -1 cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) self.highlight([cursor, new])
def slotCursorPositionChanged(self): """Called whenever the cursor position changes. Highlights matching characters if the cursor is at one of them. """ cursor = self.edit().textCursor() block = cursor.block() text = block.text() # try both characters at the cursor col = cursor.position() - block.position() end = col + 1 col = max(0, col - 1) for c in text[col:end]: if c in self.matchPairs: break col += 1 else: self.clear() return # the cursor is at a character from matchPairs i = self.matchPairs.index(c) cursor.setPosition(block.position() + col) # find the matching character new = QTextCursor(cursor) if i & 1: # look backward match = self.matchPairs[i - 1] flags = QTextDocument.FindBackward else: # look forward match = self.matchPairs[i + 1] flags = QTextDocument.FindFlags() new.movePosition(QTextCursor.Right) # search, also nesting rx = QRegExp(QRegExp.escape(c) + "|" + QRegExp.escape(match)) nest = 0 while nest >= 0: new = cursor.document().find(rx, new, flags) if new.isNull(): self.clear() return nest += 1 if new.selectedText() == c else -1 cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) self.highlight([cursor, new])
def apply_changes(self): """Apply the changes and update the tokens.""" c = QTextCursor(self._d) # record a sensible position for undo c.setPosition(self._changes_list[-1][0]) c.joinPreviousEditBlock() if self.combine_undo else c.beginEditBlock() try: for start, end, text in self._changes_list: c.movePosition(QTextCursor.End) if end is None else c.setPosition(end) c.setPosition(start, QTextCursor.KeepAnchor) c.insertText(text) finally: c.endEditBlock() if self.combine_undo is None: self.combine_undo = True
def apply_changes(self): """Apply the changes and update the tokens.""" c = QTextCursor(self._d) # record a sensible position for undo c.setPosition(self._changes_list[-1][0]) c.joinPreviousEditBlock() if self.combine_undo else c.beginEditBlock() try: for start, end, text in self._changes_list: c.movePosition( QTextCursor.End) if end is None else c.setPosition(end) c.setPosition(start, QTextCursor.KeepAnchor) c.insertText(text) finally: c.endEditBlock() if self.combine_undo is None: self.combine_undo = True
def _getCursorSelectAll(self, morph): ''' Cursor on entire document (text) of a morph (DocumentElement) of type Text. morph may be empty of text. !!! Cursor may not hasSelection() if morph is empty of text. ''' cursor = QTextCursor(morph.document()) cursor.setPosition(0) cursor.clearSelection() # programmatic selection requires movePosition(), not setPosition() cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) # In Qt, cursor is valid for further operations regardless of whether hasSelection() # ensure document not empty => cursor.hasSelection assert morph.document().isEmpty() or cursor.hasSelection() return cursor
def SaveTableImage(table): pixmap = table.grab() pixmap.save("widget.png") SaveTableImage(table) nrows = table.rowCount() ncols = table.columnCount() doc = QTextDocument() cursor = QTextCursor(doc) tableFormat = QTextTableFormat() tableFormat.setHeaderRowCount(1) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setCellPadding(0) tableFormat.setCellSpacing(0) tableFormat.setBorder(1) tableFormat.setBorderBrush(QBrush(Qt.SolidPattern)) tableFormat.clearColumnWidthConstraints() textTable = cursor.insertTable(nrows + 1, ncols, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setBackground(QColor("#DADADA")) for i in range(ncols): cell = textTable.cellAt(0, i) cell.setFormat(tableHeaderFormat) cellCursor = cell.firstCursorPosition() cellCursor.insertText(table.horizontalHeaderItem(i).text()) for i in range(nrows): for j in range(ncols): item = table.item(i, j) t = "" if item is None else str(item.text()) # if item.text().iEmpty(): # table.setItem(i,j,QTableWidgetItem("0")) cell = textTable.cellAt(i + 1, j) cellCursor = cell.firstCursorPosition() cellCursor.insertText(t) cursor.movePosition(QTextCursor.End) printer = QPrinter(QPrinter.PrinterResolution) printer.setPaperSize(QPrinter.A4) printer.setOrientation(QPrinter.Landscape) printer.setOutputFileName("w8.pdf") doc.setDocumentMargin(0) doc.setTextWidth(5) doc.print(printer)
def html_copy(cursor, scheme='editor', number_lines=False): """Return a new QTextDocument with highlighting set as HTML textcharformats. The cursor is a cursor of a document.Document instance. If the cursor has a selection, only the selection is put in the new document. If number_lines is True, line numbers are added. """ data = textformats.formatData(scheme) doc = QTextDocument() doc.setDefaultFont(data.font) doc.setPlainText(cursor.document().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlight(doc, mapping(data), ly.lex.state(documentinfo.mode(cursor.document()))) if cursor.hasSelection(): # cut out not selected text start, end = cursor.selectionStart(), cursor.selectionEnd() cur1 = QTextCursor(doc) cur1.setPosition(start, QTextCursor.KeepAnchor) cur2 = QTextCursor(doc) cur2.setPosition(end) cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) cur2.removeSelectedText() cur1.removeSelectedText() if number_lines: c = QTextCursor(doc) f = QTextCharFormat() f.setBackground(QColor('#eeeeee')) if cursor.hasSelection(): num = cursor.document().findBlock( cursor.selectionStart()).blockNumber() + 1 last = cursor.document().findBlock(cursor.selectionEnd()) else: num = 1 last = cursor.document().lastBlock() lastnum = last.blockNumber() + 1 padding = len(format(lastnum)) block = doc.firstBlock() while block.isValid(): c.setPosition(block.position()) c.setCharFormat(f) c.insertText('{0:>{1}d} '.format(num, padding)) block = block.next() num += 1 return doc
async def __readAndPrintStream(self, sr: asyncio.StreamReader, text_cursor: QTextCursor): leftover_data = bytearray() while not sr.at_eof() or len(leftover_data) > 0: separator_encountered = False meaningful_data = None cr_found = False lf_found = False while not separator_encountered: leftover_data += await sr.read(64) separator_index = -1 for index, b in enumerate(leftover_data): if b == ord(b'\r'): separator_index = index cr_found = True break elif b == ord(b'\n'): separator_index = index lf_found = True break if separator_index != -1: separator_encountered = True meaningful_data = leftover_data[0:separator_index] leftover_data = leftover_data[separator_index + 1:] else: leftover_data += leftover_data[separator_index + 1:] text = meaningful_data.decode( ) if meaningful_data is not None else '' text_cursor.beginEditBlock() if cr_found: text_cursor.movePosition(QTextCursor.StartOfLine) text_cursor.insertText(text) i = 1 count = len(text) while i <= count: text_cursor.deleteChar() i += 1 elif lf_found: text_cursor.insertText(text + '\n') else: text_cursor.insertText(text) text_cursor.endEditBlock() self.__ui.terminalLogWindow.ensureCursorVisible()
def insert(self, index, text): """Insert line to the document """ if index < 0 or index > self._doc.blockCount(): raise IndexError('Invalid block index', index) if index == 0: # first cursor = QTextCursor(self._doc.firstBlock()) cursor.insertText(text) cursor.insertBlock() elif index != self._doc.blockCount(): # not the last cursor = QTextCursor(self._doc.findBlockByNumber(index).previous()) cursor.movePosition(QTextCursor.EndOfBlock) cursor.insertBlock() cursor.insertText(text) else: # last append to the end self.append(text)
def html_copy(cursor, scheme='editor', number_lines=False): """Return a new QTextDocument with highlighting set as HTML textcharformats. The cursor is a cursor of a document.Document instance. If the cursor has a selection, only the selection is put in the new document. If number_lines is True, line numbers are added. """ data = textformats.formatData(scheme) doc = QTextDocument() doc.setDefaultFont(data.font) doc.setPlainText(cursor.document().toPlainText()) if metainfo.info(cursor.document()).highlighting: highlight(doc, mapping(data), ly.lex.state(documentinfo.mode(cursor.document()))) if cursor.hasSelection(): # cut out not selected text start, end = cursor.selectionStart(), cursor.selectionEnd() cur1 = QTextCursor(doc) cur1.setPosition(start, QTextCursor.KeepAnchor) cur2 = QTextCursor(doc) cur2.setPosition(end) cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) cur2.removeSelectedText() cur1.removeSelectedText() if number_lines: c = QTextCursor(doc) f = QTextCharFormat() f.setBackground(QColor('#eeeeee')) if cursor.hasSelection(): num = cursor.document().findBlock(cursor.selectionStart()).blockNumber() + 1 last = cursor.document().findBlock(cursor.selectionEnd()) else: num = 1 last = cursor.document().lastBlock() lastnum = last.blockNumber() + 1 padding = len(format(lastnum)) block = doc.firstBlock() while block.isValid(): c.setPosition(block.position()) c.setCharFormat(f) c.insertText('{0:>{1}d} '.format(num, padding)) block = block.next() num += 1 return doc
def gotoTextCursor(self, cursor, numlines=3): """Go to the specified cursor. If possible, at least numlines (default: 3) number of surrounding lines is shown. The number of surrounding lines can also be set in the preferences, under the key "view_preferences/context_lines". This setting takes precedence. """ numlines = QSettings().value("view_preferences/context_lines", numlines, int) if numlines > 0: c = QTextCursor(cursor) c.setPosition(cursor.selectionEnd()) c.movePosition(QTextCursor.Down, QTextCursor.MoveAnchor, numlines) self.setTextCursor(c) c.setPosition(cursor.selectionStart()) c.movePosition(QTextCursor.Up, QTextCursor.MoveAnchor, numlines) self.setTextCursor(c) self.setTextCursor(cursor)
def insert_snippet(self): cursor = self._editor.word_under_cursor() prefix = cursor.selectedText() # pos = cursor.position() # cursor.movePosition(QTextCursor.StartOfWord) # start_pos = cursor.position() # cursor.setPosition(pos, QTextCursor.KeepAnchor) copy = QTextCursor(cursor) copy.movePosition(QTextCursor.StartOfWord) start = copy.position() self._current_snippet = self.snippets.get(prefix) if self._current_snippet is not None: self.active = True cursor.removeSelectedText() cursor.insertText(self._current_snippet.body) self._highlight(start) else: self.active = False
class ExtraSelection(QTextEdit.ExtraSelection): def __init__(self, cursor, start_pos=None, end_pos=None, start_line=None, col_start=None, col_end=None): super().__init__() self.cursor = QTextCursor(cursor) # Highest value will appear on top of the lowest values self.order = 0 if start_pos is not None: self.cursor.setPosition(start_pos) if end_pos is not None: self.cursor.setPosition(end_pos, QTextCursor.KeepAnchor) if start_line is not None: self.cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) self.cursor.movePosition(QTextCursor.Down, QTextCursor.MoveAnchor, start_line) self.cursor.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, col_end - 1) self.cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, col_end - col_start) def set_underline(self, color, style=QTextCharFormat.DashUnderline): if isinstance(color, str): color = QColor(color) self.format.setUnderlineStyle(style) self.format.setUnderlineColor(color) def set_foreground(self, color): if isinstance(color, str): color = QColor(color) self.format.setForeground(color) def set_background(self, color): if isinstance(color, str): color = QColor(color) self.format.setBackground(color) def set_outline(self, color): self.format.setProperty(QTextFormat.OutlinePen, QPen(QColor(color))) def set_full_width(self): # self.cursor.clearSelection() self.format.setProperty(QTextFormat.FullWidthSelection, True)
def indent_line(self, line_no, indent_length): block = self._get_block(line_no) cursor = QTextCursor(block) cursor.joinPreviousEditBlock() cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.MoveAnchor) if indent_length < 0: for i in range(-indent_length): cursor.deleteChar() else: cursor.insertText(" " * indent_length) if indent_length: cursor.movePosition(QTextCursor.StartOfBlock, QTextCursor.MoveAnchor) line = unicode(cursor.block().text()) if len(line) and line[0] == " ": cursor.movePosition(QTextCursor.NextWord, QTextCursor.MoveAnchor) self.editview.setTextCursor(cursor) cursor.endEditBlock()
def lineNumberAreaPaintEvent(self, event): painter = QPainter(self.lineNumberArea) painter.fillRect(event.rect(), colorValues['lineNumberArea']) cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.Start) atEnd = False while not atEnd: rect = self.cursorRect(cursor) block = cursor.block() if block.isVisible(): number = str(cursor.blockNumber() + 1) painter.setPen(colorValues['lineNumberAreaText']) painter.drawText(0, rect.top(), self.lineNumberArea.width()-2, self.fontMetrics().height(), Qt.AlignRight, number) cursor.movePosition(QTextCursor.EndOfBlock) atEnd = cursor.atEnd() if not atEnd: cursor.movePosition(QTextCursor.NextBlock)
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)
def write(self, data): cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertText(data) self.setTextCursor(cursor) self.ensureCursorVisible()
def cursor(self): """Return a QTextCursor with the same selection.""" c = QTextCursor(self.document.document) c.movePosition(QTextCursor.End) if self.end is None else c.setPosition(self.end) c.setPosition(self.start, QTextCursor.KeepAnchor) return c
def _setBlockText(blockIndex, text): cursor = QTextCursor(self._doc.findBlockByNumber(blockIndex)) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) cursor.insertText(text)