Use Spotlight to Get and Replace Selected Text with a Shortcut

It’s always been the case that a shortcut could get and replace selected text in the frontmost app, but the shortcut had to be run as a Quick Action or Service. In macOS Tahoe, the same thing can be done with a shortcut that is run by way of Spotlight.

My test shortcut:

The steps that will get, edit, and replace the selected text:

  1. Select the text in the frontmost app window.

  2. Run the shortcut by way of Spotlight.

  3. The selected text will be shown in a dialog. Either click on the selected text and press the Enter key, or double-click on the selected text.

  4. The edited text will be shown in a dialog. Either click on the edited text and press the Enter key, or double-click on the edited text. The text selected in the frontmost app will be replaced with the edited text.

The following is a screenshot at step 3 above.

This all seems cumbersome, but it’s actually fairly quick with a little repetition. And, if not, a Quick Action or Service can be used.

1 Like

Here’s a working example that counts words and characters in the selected text. Step 4 in the above post doesn’t apply in this instance. The text editor was frontmost when I ran the shortcut.

Word and Character Count.shortcut (21.9 KB)

There are a few issues that I’ve encountered. First, there is sometimes a delay before the selected text appears in the Spotlight dialog. Second, blank lines or lines with whitespace only are removed, and lines with characters are sometimes combined. Hopefully this is a bug that will be fixed soon.

1 Like

I did some additional testing on these issues.

When first run by Spotlight, it will often take up to 5 seconds for selected text to appear in the Spotlight dialog. This happens with all apps, including standard macOS apps like TextEdit. There’s no fix or workaround, other than patience.

As to the second issue, lines that are blank or that contain whitespace only are deleted. However, this only happens when the shortcut outputs edited text to replace selected text. The only workaround is to use a Quick Action, which does not exhibit this behavior.

A third issue, which is related to the above, occurs when separate lines of the selected text are combined. In the following example, the second and third test lines are combined in the Spotlight dialog and in the replaced text after the shortcut finishes. This behavior is very intermittant and is often difficult to replicate, so it’s not a major issue for me.