hluk / CopyQ

Clipboard manager with advanced features
GNU General Public License v3.0
8.23k stars 429 forks source link

Custom command to capture six digit numbers #2707

Closed realchrisolin closed 1 month ago

realchrisolin commented 1 month ago

I've been trying since last week to come up with a custom command that will automatically fire when text with a six digit number is copied and copy only the six digit number to a separate tab. Through a lot of trial and error, I've gotten close but am having ongoing issues getting this to perform correctly. At this point, I'm not sure if the issue is a bug in CopyQ, Qt, or something wrong with my code (although I think this is a bug).

Specifically, the two major issues I've had is getting CopyQ to keep copying text regardless if a six digit number is in the copied string and getting it to parse out just the six digit number into the separate tab.. If I create a new command where Advanced > Content is set to \b\d{6}\b, the command will fire on any string with a six digit number. However, the %1 expression contains the entire copied string, not the matched text.

The closest I've got to sanitizing copied text that matches on that regex is the following command, but I can't get the regex to capture the six digit number correctly either as a match or with a capture group in the expression. Both match[0] and match[1] return the fully copied string instead of just the six digit number.

copyq popup match
var clipboardText = %1;
var regex = /\b(\d{6})\b/;
var match = regex.exec(clipboardText);
if (match) {
  setClipboard(match[1]);
  write("recent tickets", match[1]);
}
realchrisolin commented 1 month ago

Ended up getting this working with the following code after more trial and error. Even if I correct the original code to use str(clipboard()), the right regex string, and copy/write in the if loop, I still can't get this to work without the while loop and matches array. Not sure why, but hopefully this will help someone else in the future.

copyq:
var selectedText = str(clipboard());
var regex = /\b(\d{6})\b/g;
var match;
var matches = [];

while ((match = regex.exec(selectedText)) !== null) {
  matches.push(match[1]);
}

if (matches.length > 0) {
  copy(matches[0]);
  tab("recent tickets");
  write(0, "text/plain", matches[0]);
  popup("captured ticket number: " + matches[0]);
}
hluk commented 1 month ago

Fixing in #2718. It should be possible to use argument[1] and up for the captured texts from Content field in the Automatic commands. I'm not even sure if it worked well before or it silently broke at some point (I've added tests now).

Thanks for the report!