I've researched methods on how to get the selection as a text variable in an AppleScript. But these methods rely on copying the selection to the clipboard (for example, by keystroking the copy command at the top of the script) in order to introduce this text to the AppleScript (by using the clipboard
).
This is less than ideal, of course, because the actual clipboard text is overwritten.
Is there another way to get the selected text, system-wide, in AppleScript, without disturbing the clipboard?
Obviously, one can easily get the selected text without touching the clipboard in Automator. However, in this case, I don't want to use Automator; I need a pure AppleScript solution.
Best Answer
Here is a recent blog post that focuses on this very mission:
Michael Tsai - Blog - Processing the Selected Text via Script
One way to get the currently selected text into an AppleScript, without overwriting the clipboard contents, is to simply save
the clipboard
contents to a new variable before the selected text is copied. Then, at the end of the script, place the original clipboard contents back ontothe clipboard
.Here is what this might look like:
But, this method is imperfect, as Michael notes:
However, Shane Stanley left a comment on the blog post with a method to retain the original formatting of the clipboard contents.
If using the previous example, replace the first line with:
Replace the last line with:
And add the following code to the end:
I've tested this solution provided by Shane, and it does indeed retain all of the original formatting of the clipboard contents if you have rich text on the clipboard.
Shane later left a second comment, this time with the intent of minimizing the runtime of the script.
Replace this code:
with this code:
I tested this new code and I did find that the script was in fact noticeably faster, just by a hair.
Overall, this is not a bad workaround. The contents of the clipboard are preserved and the delay is much less noticeable if you employ the code provided in Shane's second comment.
I tested the solution against a Service created in Automator.app that receives the selected text as the
input
. The Service and the pure AppleScript solution pretty much took equal amounts of time to complete (i.e, about one second).If one wants a method to get and replace the selected text without having to touch the clipboard, Michael suggests in his blog post that one can utilize a piece of third-party software entitled LaunchBar. However, this is "cheating," because, at that point, we have moved beyond the scope of my original question, which is strictly concerned about AppleScript.