johnlindquist / kit

Script Kit. Automate Anything.
https://scriptkit.com
MIT License
3.91k stars 138 forks source link

`getSelectedText()` modifies clipboard contents #1530

Open ianjsikes opened 1 month ago

ianjsikes commented 1 month ago

As the title states, calling getSelectedText() will give you the currently selected text in whatever application is open. However, it also copies that text to the clipboard. This is, in my opinion, an unexpected and undocumented side effect.

Consider this simple script to replace the selected text with a markdown link:

const linkText = await getSelectedText();
const linkTarget = await arg("Link target");
setSelectedText(`[${linkText}](${linkTarget})`);

My intended workflow for this is:

  1. Copy a link to my clipboard
  2. Select some text
  3. Run this script
  4. Paste in the previously copied link to the prompt

But this doesn't work because when I hit cmd+v in the prompt, it just pastes in the text I've already selected, overriding the previous clipboard contents.

Now, it's fairly easy to work around this with a helper like this:

const getTextWithoutModifyingClipboard = async (): Promise<string> => {
  const clipContent = await clipboard.readText();
  const selection = await getSelectedText();
  await clipboard.writeText(clipContent);
  return selection;
};

But I would still argue that either:

  1. Something like this be worked into the internal implementation of getSelectedText(), because this workaround will have unintended effects on clipboard history for those that use it, OR
  2. This behavior be documented in the API (That's a change I'd be happy to contribute myself if the first option is not acceptable)
johnlindquist commented 1 month ago

@ianjsikes great callout, I'll get it sorted internally. Should be a fairly straightforward fix.