How to enclose selected text in tags

Viewed 23

I need to tag the selected text.

text -> <tag>text</tag>

cursor = self.textEdit.textCursor()
If cursor.hasSelection():
    len_text = len(cursor.selectedText())
    cursor.movePosition(QTextCursor.Left, QTextCursor.MoveAnchor, len_text)
    cursor.insertText(tag)
    cursor.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, len_text)
    cursor.insertText(f'{tag[:1]}/{tag[1:]}')
    cursor.clearSelection()
    self.textEdit.setTextCursor(cursor)

Of course this will only work if the cursor is at the end of the selection

How do I move the cursor to the end if it is positioned elsewhere? Let's say the text was selected from right to left or by double clicking

Maybe I didn't choose the right approach to solve the problem?

0 Answers
Related