0

I have the following AppleScript code in a Textedit file:

set the clipboard to (do shell script "date +%d/%m/%y")
tell application "System Events"
    keystroke tab using command down
    keystroke "v" using command down
end tell

How can I execute this code?

2
  • I've edited the question some more to also make sure the title matches the content. – nohillside Aug 24 '19 at 14:53
  • Can you please clarify what is is you're trying to do? Are you really just trying to insert the date in your TextEdit document at the cursor? – user3439894 Aug 26 '19 at 13:14
4

You can't execute AppleScript directly from TextEdit. Apple provides an AppleScript editor though in /Applications/Utilities/Script\ Editor.app which makes it easy to create and run AppleScript code.

Just navigate to /Applications/Utilities in Finder, run Script Editor and copy/paste your code into it.

2

If this is something you find yourself needing to do fairly often (and, for some reason, don't wish to have to use Script Editor), then one way to do this is to create a systemwide Service (or Quick Action) in Automator:

Run As AppleScript Service

It will be set to receive text in any application and ensure that the Output replaces selected text.

Once saved, you can select the text in TextEdit (or, indeed, any application), and have it execute the AppleScript in situ, returning the result, which will appear below the selection.

AppleScript code:

on run {{input}}
    local input

    try
        return {input, run script input}
    on error E
        return {input, E}
    end try
end run
3
  • Sorry, I had to make an edit in order to retract my up-vote. The reason I did this is because while your answer works in some cases, it also fails in some cases. I can cause the Automator service hang with simple basic AppleScript code. Therefore, this is not a viable answer. – user3439894 Aug 26 '19 at 13:11
  • @user3439894 Can you be more specific? – CJK Aug 26 '19 at 13:15
  • 1
    Take the code in the OP as an example. As is, run by your Service it fails as TextEdit would not have focus when System Events runs the keystrokes. Add a tell application "TextEdit" to activate after the set the clipboard ... and the Automator service just keeps running in the menu bar and never gets above 0% complete. Even just selecting tell application "TextEdit" to activate by itself hangs the Automator service. – user3439894 Aug 26 '19 at 13:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .