def __positionPair(self, pos): cursor = QTextCursor(self.document()) cursor.setPosition(pos) rootFrame = self.document().rootFrame() frames = rootFrame.childFrames() frame = cursor.currentFrame() if frame == rootFrame: # pos is outside any group return [pos, pos] p = frame.parentFrame() if p != rootFrame: # frame is an input or output frame containing pos return [frame.firstPosition(), frame.lastPosition()] # frame is a group frame containing pos in a comment position localFrames = frame.childFrames() inputStart = localFrames[0].firstPosition() if pos < inputStart: return [frame.firstPosition(), inputStart - 1] inputEnd = localFrames[0].lastPosition() outputStart = localFrames[1].firstPosition() if inputEnd < pos and pos < outputStart: return [inputEnd + 1, outputStart - 1] outputEnd = localFrames[1].lastPosition() if outputEnd < pos: return [outputEnd + 1, frame.lastPosition()] traceLogger.critical("bad position %d (%d %d) (%d %d)" % (pos, ifr.firstPosition(), ifr.lastPosition(), ofr.firstPosition(), ofr.lastPosition())) return [-1, -1]
def __positionPair(self,pos): cursor = QTextCursor(self.document()) cursor.setPosition(pos) rootFrame = self.document().rootFrame() frames = rootFrame.childFrames() frame = cursor.currentFrame() if frame == rootFrame: # pos is outside any group return [pos,pos] p = frame.parentFrame() if p != rootFrame: # frame is an input or output frame containing pos return [frame.firstPosition(),frame.lastPosition()] # frame is a group frame containing pos in a comment position localFrames = frame.childFrames() inputStart = localFrames[0].firstPosition() if pos < inputStart: return [frame.firstPosition(),inputStart-1] inputEnd = localFrames[0].lastPosition() outputStart = localFrames[1].firstPosition() if inputEnd < pos and pos < outputStart: return [inputEnd+1,outputStart-1] outputEnd = localFrames[1].lastPosition() if outputEnd < pos: return [outputEnd+1,frame.lastPosition()] traceLogger.critical("bad position %d (%d %d) (%d %d)" % (pos, ifr.firstPosition(), ifr.lastPosition(), ofr.firstPosition(), ofr.lastPosition())) return [-1,-1]
def markSentence(self): """Mark sentence with marker if marker ir checked.""" cursor = QTextCursor(self.sentence_mw.ui.textEditSentence.document()) begin = self.sentence_mw.ui.textEditSentence.textCursor( ).selectionStart() end = self.sentence_mw.ui.textEditSentence.textCursor().selectionEnd() marker = self.preferences['marker'] cursor.setPosition(begin, QTextCursor.MoveAnchor) cursor.insertText(marker[0]) cursor.setPosition(end + 1, QTextCursor.MoveAnchor) cursor.insertText(marker[1])
def gotoRow(self,row): rows = self.document().rootFrame().childFrames() if row >= len(rows): traceLogger.critical("invalid row %d > %d" % (row,len(rows)-1)) row = len(rows) cursor = QTextCursor(rows[row].lastCursorPosition()) cursor.movePosition(QTextCursor.NextBlock) self.setTextCursor(cursor) self.ensureCursorVisible() cursor = QTextCursor(rows[row].childFrames()[0]) self.setTextCursor(cursor) self.ensureCursorVisible()
def currentField(self,row): rows = self.document().rootFrame().childFrames() if row >= len(rows): traceLogger.critical("invalid row %d > %d" % (row,len(rows)-1)) row = len(rows) inputFrame = rows[row].childFrames()[0] cursor = QTextCursor(inputFrame) cursor.setPosition(inputFrame.lastPosition(),QTextCursor.KeepAnchor) command = cursor.selectedText() command = command.replace(u'\u2028',u'\n') command = command.replace(u'\u2029',u'\n') if command != '' and not command[-1] in [';','$']: command += ';' return command
def currentField(self, row): rows = self.document().rootFrame().childFrames() if row >= len(rows): traceLogger.critical("invalid row %d > %d" % (row, len(rows) - 1)) row = len(rows) inputFrame = rows[row].childFrames()[0] cursor = QTextCursor(inputFrame) cursor.setPosition(inputFrame.lastPosition(), QTextCursor.KeepAnchor) command = cursor.selectedText() command = command.replace(u'\u2028', u'\n') command = command.replace(u'\u2029', u'\n') if command != '' and not command[-1] in [';', '$']: command += ';' return command
def hideFrom(self, line): """ Hides a block starting by line. Do nothing if not hidable""" block = self.getWidget().document().findBlockByNumber(line - 1) openB = block.text().count("(") closeB = block.text().count(")") startline = line # go to line >= line: block starts counting by 0 block = self.getWidget().document().findBlockByNumber(line - 1) hidden = [] assert block.isValid() while openB > closeB and block.isValid(): assert block.isValid() block = block.next() line = block.blockNumber() + 1 if block.isVisible(): hidden.append(line) openB += block.text().count("(") closeB += block.text().count(")") if hidden == []: return self._hideLines(hidden) self.hidden[startline] = hidden # set current line in viewable area current_line = self.getWidget().document().findBlock( self.getWidget().textCursor().position()).blockNumber() + 1 if (startline < current_line and current_line <= line): block = block.next() cursor = QTextCursor(block) self.getWidget().setTextCursor(cursor)
def cursor_is_in_editing_region(self, cursor): # Want to be to the right of the prompt... if cursor.positionInBlock() < len(self.prompt): return False # ... and in the final line. if cursor.blockNumber() != self.te.blockCount() - 1: return False if cursor.anchor() != cursor.position(): # Anchor might be outside of editing region anchorCursor = QTextCursor(cursor) anchorCursor.setPosition(cursor.anchor()) if anchorCursor.positionInBlock() < len(self.prompt): return False if anchorCursor.blockNumber() != self.te.blockCount() - 1: return False return True
def append(self, text): """Append line to the end """ cursor = QTextCursor(self._doc) cursor.movePosition(QTextCursor.End) cursor.insertBlock() cursor.insertText(text)
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.setPositionInBlock(min(realStartCol, block.length() - 1)) cursor.setPositionInBlock(min(realCurrentCol, block.length() - 1), QTextCursor.KeepAnchor) cursors.append(cursor) return cursors
def __init__(self, cursorOrBlockOrDoc, startPos=None, endPos=None, draw_order=0, tooltip=None): """ Creates a text decoration :param cursorOrBlockOrDoc: Selection :type cursorOrBlockOrDoc: QTextCursor or QTextBlock or QTextDocument :param startPos: Selection start pos :param endPos: Selection end pos .. note:: Use the cursor selection if startPos and endPos are none. """ self.draw_order = draw_order self.tooltip = tooltip QTextEdit.ExtraSelection.__init__(self) cursor = QTextCursor(cursorOrBlockOrDoc) if startPos is not None: cursor.setPosition(startPos) if endPos is not None: cursor.setPosition(endPos, QTextCursor.KeepAnchor) self.cursor = cursor
def update_editor(self, *args, **kw): ''' ''' self.control.clear() adapter = self.factory.adapter tables = adapter.make_tables(self.value) cursor = QTextCursor(self.control.textCursor()) n = len(tables) for i, ti in enumerate(tables): self._add_table(ti, cursor) # timethis(self._add_table, args=(ti, cursor), msg='add_table') if i < n - 1: self._add_table_hook(cursor)
def testRefcount(self): textedit = QTextEdit() textedit.setReadOnly(True) doc = textedit.document() cursor = QTextCursor(doc) cursor.insertText("PySide Rocks") ud = TestUserData({"Life": 42}) self.assertEqual(sys.getrefcount(ud), 2) cursor.block().setUserData(ud) self.assertEqual(sys.getrefcount(ud), 3) ud2 = cursor.block().userData() self.assertEqual(sys.getrefcount(ud), 4) self.udata = weakref.ref(ud, None) del ud, ud2 self.assertEqual(sys.getrefcount(self.udata()), 2)
def _makeMatchSelection(self, block, columnIndex, matched): """Make matched or unmatched QTextEdit.ExtraSelection """ selection = QTextEdit.ExtraSelection() if matched: bgColor = QColor('#9ED1FF') else: bgColor = QColor('#FFDFDF') selection.format.setBackground(bgColor) selection.cursor = QTextCursor(block) selection.cursor.setPositionInBlock(columnIndex) selection.cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor) return selection
def gotoRow(self, row): rows = self.document().rootFrame().childFrames() if row >= len(rows): traceLogger.critical("invalid row %d > %d" % (row, len(rows) - 1)) row = len(rows) cursor = QTextCursor(rows[row].lastCursorPosition()) cursor.movePosition(QTextCursor.NextBlock) self.setTextCursor(cursor) self.ensureCursorVisible() cursor = QTextCursor(rows[row].childFrames()[0]) self.setTextCursor(cursor) self.ensureCursorVisible()
def testUndoRedo(self): text = 'foobar' doc = QTextDocument(text) self.assertFalse(doc.isRedoAvailable()) self.assertTrue(doc.isUndoAvailable()) self.assertEqual(doc.toPlainText(), text) cursor = QTextCursor(doc) doc.undo(cursor) self.assertTrue(doc.isRedoAvailable()) self.assertFalse(doc.isUndoAvailable()) self.assertEqual(doc.toPlainText(), '') doc.redo(cursor) self.assertFalse(doc.isRedoAvailable()) self.assertTrue(doc.isUndoAvailable()) self.assertEqual(doc.toPlainText(), text)
def testQTextCursorSelectedTableCells(self): obj = QTextCursor() self.assertEquals(obj.selectedTableCells(), (-1, -1, -1, -1))
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
def insertRow(self, row): self.insertingFrames = True document = self.document() rootFrame = document.rootFrame() rows = rootFrame.childFrames() if row > len(rows): traceLogger.critical("invalid row %d > %d" % (row, len(rows))) row = len(rows) if row == len(rows): cursor = QTextCursor(document) cursor.movePosition(QTextCursor.End) elif rows: cursor = QTextCursor(rows[row].firstCursorPosition()) cursor.movePosition(QTextCursor.PreviousBlock) cursor.insertFrame(QtReduceRowFormat()) cursor.insertFrame(QtReduceInput().frameFormat) position = cursor.position() cursor.clearSelection() cursor.setBlockFormat(QtReduceInput().blockFormat) cursor.setBlockCharFormat(QtReduceInput().charFormat) cursor.movePosition(QTextCursor.NextBlock) cursor.insertFrame(QtReduceNoResult().frameFormat) cursor.setBlockFormat(QtReduceNoResult().blockFormat) cursor.setBlockCharFormat(QtReduceNoResult().charFormat) cursor.insertText(QtReduceFrameView.NotEvaluated) cursor.setPosition(position) self.insertingFrames = False
def insertRow(self,row): self.insertingFrames = True document = self.document() rootFrame = document.rootFrame() rows = rootFrame.childFrames() if row > len(rows): traceLogger.critical("invalid row %d > %d" % (row,len(rows))) row = len(rows) if row == len(rows): cursor = QTextCursor(document) cursor.movePosition(QTextCursor.End) elif rows: cursor = QTextCursor(rows[row].firstCursorPosition()) cursor.movePosition(QTextCursor.PreviousBlock) cursor.insertFrame(QtReduceRowFormat()) cursor.insertFrame(QtReduceInput().frameFormat) position = cursor.position() cursor.clearSelection() cursor.setBlockFormat(QtReduceInput().blockFormat) cursor.setBlockCharFormat(QtReduceInput().charFormat) cursor.movePosition(QTextCursor.NextBlock) cursor.insertFrame(QtReduceNoResult().frameFormat) cursor.setBlockFormat(QtReduceNoResult().blockFormat) cursor.setBlockCharFormat(QtReduceNoResult().charFormat) cursor.insertText(QtReduceFrameView.NotEvaluated) cursor.setPosition(position) self.insertingFrames = False
def goToLine(self, line): block = self.editor.document().findBlockByLNumber(line) cursor = QTextCursor(self.editor.document()) cursor.setPosition(block.position()) self.editor.setTextCursor(cursor)
def cursorForPosition(codeEdit, line, column, selectEndOfLine=False, selection=None, selectWordUnderCursor=False): """ Return a QTextCursor set to line and column with the specified selection :param line: :param column: """ tc = QTextCursor(codeEdit.document()) tc.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) tc.movePosition(QTextCursor.Down, QTextCursor.MoveAnchor, line - 1) tc.setPosition(tc.position() + column - 1) if selectEndOfLine is True: tc.movePosition(QTextCursor.EndOfLine, QTextCursor.KeepAnchor) elif isinstance(selection, int): tc.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, selection) elif selectWordUnderCursor is True: tc.select(QTextCursor.WordUnderCursor) codeEdit.setTextCursor(tc) return tc
class TextFormat(): def __init__(self, selection, button): self.selection = selection self.cursor = QTextCursor(self.selection.textEdit.textCursor()) self.format = QTextCharFormat() self.button = button def bold_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.bold_selection() if self.selection.textEdit.fontWeight() == QFont.Bold: self.button.setDown(False) return self.selection.textEdit.setFontWeight(QFont.Normal) self.button.setDown(True) return self.selection.textEdit.setFontWeight(QFont.Bold) def bold_selection(self): if self.selection.bold_button.isDown(): self.selection.bold_button.setDown(False) return self.selection.textEdit.setFontWeight(QFont.Normal) if not self.selection.textEdit.textCursor().charFormat().fontWeight() == QFont.Bold: self.format.setFontWeight(QFont.Bold) self.selection.bold_button.setDown(True) return self.cursor.mergeCharFormat(self.format) return self.selection.textEdit.setFontWeight(QFont.Normal) def italic_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.italic_selection() if self.selection.textEdit.fontItalic(): self.button.setDown(False) return self.selection.textEdit.setFontItalic(False) self.button.setDown(True) return self.selection.textEdit.setFontItalic(True) def italic_selection(self): if self.selection.italic_button.isDown(): self.selection.italic_button.setDown(False) return self.selection.textEdit.setFontItalic() if not self.selection.textEdit.textCursor().charFormat().fontItalic(): self.format.setFontItalic(True) return self.cursor.mergeCharFormat(self.format) self.selection.italic_button.setDown(False) return self.selection.textEdit.setFontItalic(False) def underline_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.underline_selection() if self.selection.textEdit.fontUnderline(): self.button.setDown(False) return self.selection.textEdit.setFontUnderline(False) self.button.setDown(True) return self.selection.textEdit.setFontUnderline(True) def underline_selection(self): if self.selection.underline_button.isDown(): self.selection.underline_button.setDown(False) return self.selection.textEdit.setFontUnderline(False) if not self.selection.textEdit.textCursor().charFormat().fontUnderline(): self.format.setFontUnderline(True) return self.cursor.mergeCharFormat(self.format) return self.selection.textEdit.setFontUnderline(False) def strikeout_button_behavior(self): if self.selection.textEdit.textCursor().hasSelection(): return self.strikeout_selection() if self.selection.textEdit.textCursor().charFormat().fontStrikeOut(): self.button.setDown(False) return self.selection.textEdit.textCursor().charFormat().setFontStrikeOut(False) self.button.setDown(True) formatter = QTextCharFormat() formatter.setFontStrikeOut(True) return self.selection.textEdit.setCurrentCharFormat(formatter) def strikeout_selection(self): if self.selection.textEdit.textCursor().charFormat().fontStrikeOut(): self.selection.strikeout_button.setDown(False) self.format.setFontStrikeOut(False) return self.cursor.mergeCharFormat(self.format) if not self.selection.textEdit.textCursor().charFormat().fontStrikeOut(): self.format.setFontStrikeOut(True) return self.cursor.mergeCharFormat(self.format) return self.selection.textEdit.textCursor().charFormat()
def __init__(self, selection, button): self.selection = selection self.cursor = QTextCursor(self.selection.textEdit.textCursor()) self.format = QTextCharFormat() self.button = button
def _setBlockText(blockIndex, text): cursor = QTextCursor(self._doc.findBlockByNumber(blockIndex)) cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor) cursor.insertText(text)
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 _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 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