ericbn ericbn - 4 months ago 14
AppleScript Question

Applescript keystrokes in a Input Source independent way

I want to write an Applescript that does multiple copy-and-paste between other keystrokes. So this is a sample of what I've done:

tell application "System Events"
set the clipboard to "^"
keystroke "v" using command down
keystroke "a"
set the clipboard to "~"
keystroke "v" using command down
keystroke "a"
end tell


I'm expecting to get
^a~a
typed when running the above script with
osascript
, but I'm getting
~a~a
instead. Looks like the keystrokes are executed after all the "set the clipboard" instructions.

How can I have a sequence of copy-and-paste instructions in the same script?

EDIT: the main reason I'm doing this is to be able to auto-type characters in a way that works independently of the Input Source enabled. So I would get the expected sequence of characters with U.S. or with some other Input Source that otherwise would result in
âã
if we just had the four symbols above typed in sequence. Adding spaces after the accent characters would work for this kind of Input Source, but would give me
^ a~ a
with U.S., so that is not the general solution I'm looking for.

Answer

Adding a delay solves the issue. In script bellow, it types in TextEdit :

tell application "TextEdit" to activate
tell application "System Events"
set the clipboard to "^"
keystroke "v" using command down
keystroke "a"
delay 0.05
set the clipboard to "~"
keystroke "v" using command down
keystroke "a"
end tell

I assume that you have good reasons, not explained here, to not just do :

tell application "System Events" to keystroke "^ a~ a"
Comments