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 append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
def clone(self, parent=None) -> 'TerminalTextDocument': """Create a new TerminalTextDocument that is a copy of this document.""" clone = type(self)() clone.setParent(parent) clone.setDocumentLayout(QPlainTextDocumentLayout(clone)) cursor = QTextCursor(clone) cursor.insertFragment(QTextDocumentFragment(self)) clone.rootFrame().setFrameFormat(self.rootFrame().frameFormat()) clone.setDefaultStyleSheet(self.defaultStyleSheet()) clone.setDefaultFont(self.defaultFont()) clone.setDefaultTextOption(self.defaultTextOption()) clone.setCurrentCharFormat(self.currentCharFormat()) for s, w in self.__streams: clone.connectStream(s, w.charformat if w is not None else None) return clone
def update_source_file(self): if (self.source_file != ""): #Update highlighter filename, extension = os.path.splitext(self.source_file) self.code_editor.set_highlighter(extension) try: with open(self.directory + "/" + self.source_file, 'r') as file: code = file.read() self.code_editor.setPlainText(code) self.display_source_file() except IOError: _, err, _ = sys.exc_info() self.display_error(str(err)) else: self.display_no_source_selected() return if (self.source_line != -1): #print(self.source_line) block = self.code_editor.document().findBlockByLineNumber( self.source_line - 1) self.code_editor.setTextCursor(QTextCursor(block)) self.code_editor.moveCursor(QTextCursor.EndOfBlock)
def pasteFile(self, url): new = read_file_content(url.toLocalFile()) if new: # inserting text like this allows undo cursor = QTextCursor(self.document()) cursor.select(QTextCursor.Document) cursor.insertText(new)
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) tformat = self.__textFormat if tformat == Qt.AutoText: if mightBeRichText(self.__message): tformat = Qt.RichText else: tformat = Qt.PlainText if tformat == Qt.RichText: 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)
def cursors(self): """Cursors for rectangular selection. 1 cursor for every line """ cursors = [] if self._start is not None: startLine, startVisibleCol = self._start currentLine, currentCol = self._qpart.cursorPosition if abs(startLine - currentLine) > self._MAX_SIZE or \ abs(startVisibleCol - currentCol) > self._MAX_SIZE: # Too big rectangular selection freezes the GUI self._qpart.userWarning.emit( 'Rectangular selection area is too big') self._start = None return [] currentBlockText = self._qpart.textCursor().block().text() currentVisibleCol = self._realToVisibleColumn( currentBlockText, currentCol) for lineNumber in range(min(startLine, currentLine), max(startLine, currentLine) + 1): block = self._qpart.document().findBlockByNumber(lineNumber) cursor = QTextCursor(block) realStartCol = self._visibleToRealColumn( block.text(), startVisibleCol) realCurrentCol = self._visibleToRealColumn( block.text(), currentVisibleCol) if realStartCol is None: realStartCol = block.length() # out of range value if realCurrentCol is None: realCurrentCol = block.length() # out of range value cursor.setPosition(cursor.block().position() + min(realStartCol, block.length() - 1)) cursor.setPosition( cursor.block().position() + min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor) cursors.append(cursor) return cursors
def _makeMatchSelection(self, block, columnIndex, matched): """Make matched or unmatched QTextEdit.ExtraSelection """ selection = QTextEdit.ExtraSelection() darkMode = QApplication.instance().property('darkMode') if matched: fgColor = self.MATCHED_COLOR else: fgColor = self.UNMATCHED_COLOR selection.format.setForeground(fgColor) # repaint hack selection.format.setBackground( Qt.white if not darkMode else QColor('#111111')) selection.cursor = QTextCursor(block) selection.cursor.setPosition(block.position() + columnIndex) selection.cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) return selection
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 write(self, data): cursor = QTextCursor(self.document()) cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.insertText(data) self.setTextCursor(cursor) self.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 _setBlockText(blockIndex, text): cursor = QTextCursor(self._doc.findBlockByNumber(blockIndex)) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) cursor.insertText(text)
def textCursor(self) -> QTextCursor: """Return a text cursor positioned at the end of the document.""" cursor = QTextCursor(self) cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) cursor.setCharFormat(self.__currentCharFormat) return cursor
def onChangeSelectedBlocksIndent(self, increase, withSpace=False): """Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks """ def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith( self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if (cursor.selectionStart() != cursor.selectionEnd() and endBlock.position() == cursor.selectionEnd() and endBlock.previous().isValid()): # do not indent not selected line if indenting multiple lines endBlock = endBlock.previous() indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock)
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 cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor