I'm having trouble restoring the clipboard content in a CopyQ script after a paste()
operation. My goal is to insert a timestamp, but the original clipboard data gets lost.
Here's what I'm doing:
var textBackup = clipboard();
var format = 'yyyy-MMdd-HHmm'; var dateTime = dateString(format);
copy(dateTime); copySelection(dateTime);
paste();
copySelection(textBackup); clipboard(textBackup);
The problem is that the original clipboard content is not restored after the paste()
operation.
I suspect a timing issue, so I tried adding a 50ms delay using this busy-wait loop:
copyq:
var textBackup = clipboard();
// Simulate a delay to allow copy to complete
var startTime = new Date().getTime();
while (new Date().getTime() - startTime < 150) {
}
var format = 'yyyy-MMdd-HHmm';
var dateTime = dateString(format);
copy(dateTime);
copySelection(dateTime);
paste();
copySelection(textBackup);
clipboard(textBackup);
However, the issue still occurs intermittently, even with the delay.
Specific Question:
Why is the clipboard not being reliably restored, and what can I do to ensure the original clipboard content is preserved after the paste()
operation in this CopyQ script? Is there a race condition, or some other factor I'm overlooking?
My CopyQ version is 10.0.0.
The solution is to restore CopyQ's internal clipboard after the paste()
operation using the copy(textBackup)
command.
Here's the working script:
copyq:
// http://doc.qt.io/qt-5/qdatetime.html#toString
var textBackup = clipboard();
var format = 'yyyy-MMdd-HHmm';
var dateTime = dateString(format);
copy(dateTime);
copySelection(dateTime);
paste();
copy(textBackup);
Explanation:
var textBackup = clipboard();
: This line saves the original clipboard content into the textBackup
variable.var format = 'yyyy-MMdd-HHmm';
: This line defines the desired date/time format.var dateTime = dateString(format);
: This line formats the current date/time according to the specified format.copy(dateTime);
: This line copies the formatted date/time to CopyQ's internal clipboard.copySelection(dateTime);
: This line copies the formatted date/time to the system clipboard (for pasting).paste();
: This line performs the paste operation, inserting the date/time into the target document.copy(textBackup);
: This line restores CopyQ's internal clipboard to the original content. This is the key to the solution.