javascriptclipboardcopyq

CopyQ Script: Clipboard Not Restoring After paste() - Potential Timing Issue?


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:

  1. Save the clipboard content: var textBackup = clipboard();
  2. Generate a timestamp: var format = 'yyyy-MMdd-HHmm'; var dateTime = dateString(format);
  3. Copy the timestamp: copy(dateTime); copySelection(dateTime);
  4. Paste the timestamp: paste();
  5. Attempt to restore the clipboard: 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.


Solution

  • 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:

    1. var textBackup = clipboard();: This line saves the original clipboard content into the textBackup variable.
    2. var format = 'yyyy-MMdd-HHmm';: This line defines the desired date/time format.
    3. var dateTime = dateString(format);: This line formats the current date/time according to the specified format.
    4. copy(dateTime);: This line copies the formatted date/time to CopyQ's internal clipboard.
    5. copySelection(dateTime);: This line copies the formatted date/time to the system clipboard (for pasting).
    6. paste();: This line performs the paste operation, inserting the date/time into the target document.
    7. copy(textBackup);: This line restores CopyQ's internal clipboard to the original content. This is the key to the solution.