Automator Service that works with and without selection

applescriptautomator

I have an AppleScript that I want to run with a keyboard shortcut. The script uses the current selection of text if it is available, but will also work without it. I have created an Automator Service for this.

If I select "Service receives selected text", it works if I have text selected, but will not run if I don't have text selected. I can change to "Service receives no input", but then I won't get the selection even if I have something selected before.

What I am looking for is some way to launch the script and pass in the selection is available, and launch the script with no (or empty) input if nothing is selected. But it should work with the same keyboard shortcut in both cases. Is this possible? Thanks!

Best Answer

I don't have an exact answer to your problem but you could perhaps consider a normal applescript that sends the COPY command and checks the contents of the clipboard before and after. Like this...

# For testing only; Delay so we can switch to the app with text
delay 2

# Clear the clipboard so we have a clean state
set the clipboard to ""


    tell application "System Events"

    # Send the 'Copy' command
    keystroke "c" using command down
    delay 0.2

    # Grub the clipboard contents
    set the_sel to the clipboard

    # Is it empty? We either failed or no selection present
    if the_sel is equal to "" then
        display dialog "No Text selected"
    else
        display dialog "Text was: " & the_sel
    end if
end tell