Skip to content

Commit a383022

Browse files
committed
editor: Reimplement copying and cutting to copy only text/plain
This way pasting text back does not mangle it, e.g. double backslashes.
1 parent a6cf14d commit a383022

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

ReText/editor.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
)
2929
from PyQt6.QtCore import (
3030
QFileInfo,
31+
QMimeData,
3132
QMimeDatabase,
3233
QPoint,
3334
QPointF,
@@ -42,6 +43,7 @@
4243
QGuiApplication,
4344
QImage,
4445
QKeyEvent,
46+
QKeySequence,
4547
QMouseEvent,
4648
QPainter,
4749
QPalette,
@@ -256,6 +258,14 @@ def contextMenuEvent(self, event):
256258
actionNextAfterPaste = actions[actions.index(actionPaste) + 1]
257259
menu.insertAction(actionNextAfterPaste, self.parent.actionPasteImage)
258260

261+
actionCopy = menu.findChild(QAction, "edit-copy")
262+
actionCopy.triggered.disconnect()
263+
actionCopy.triggered.connect(self.copy)
264+
265+
actionCut = menu.findChild(QAction, "edit-cut")
266+
actionCut.triggered.disconnect()
267+
actionCut.triggered.connect(self.cut)
268+
259269
text = self.toPlainText()
260270
if not text:
261271
menu.exec(event.globalPos())
@@ -372,6 +382,10 @@ def keyPressEvent(self, event):
372382
self.moveCursor(QTextCursor.MoveOperation.Down, mode)
373383
if self.textCursor().position() == oldPos:
374384
self.moveCursor(QTextCursor.MoveOperation.End, mode)
385+
elif event.matches(QKeySequence.StandardKey.Copy):
386+
self.copy()
387+
elif event.matches(QKeySequence.StandardKey.Cut):
388+
self.cut()
375389
elif cursor.selectedText() and self.isSurroundKey(key):
376390
self.surroundText(cursor, event, key)
377391
else:
@@ -646,6 +660,18 @@ def insertFromMimeData(self, source):
646660
return
647661
return super().insertFromMimeData(source)
648662

663+
def copy(self):
664+
"""Copy only text, not html, to make sure it is inserted back verbatim."""
665+
if text := self.textCursor().selectedText():
666+
text = text.replace("\u2029", "\n")
667+
data = QMimeData()
668+
data.setText(text)
669+
QGuiApplication.clipboard().setMimeData(data)
670+
671+
def cut(self):
672+
self.copy()
673+
self.textCursor().removeSelectedText()
674+
649675

650676
class LineNumberArea(QWidget):
651677
def __init__(self, editor):

0 commit comments

Comments
 (0)