MacOS – faster way to insert text at cursor in AppleScript than “keystroke”

applescriptautomationmacostext;

This is for a .scpt file, triggered by a keyboard combo in FastScripts, entitled "Type As Single Line Plain Text."

The AppleScript code takes the clipboard text, removes all rich text formatting, and then removes all line breaks and indentations, setting this new string to a new variable, theClipboardTextWithoutAnyLineBreaksOrFormatting. Finally, I want the AppleScript to insert this new text at the blinking cursor.

But, I don't want to overwrite the original clipboard with this new, plain text string. I simply want the new string typed out at the blinking cursor, system-wide and in any application. keystroke does accomplish exactly what I want. It is just slow.

Here is the full script:

set theClipboardTextWithoutAnyFormatting to (the clipboard as text)

set AppleScript's text item delimiters to {return & linefeed, return, linefeed, character id 8233, character id 8232}
set theClipboardTextWithoutAnyLineBreaksOrFormatting to text items of (theClipboardTextWithoutAnyFormatting as text)
set AppleScript's text item delimiters to {" "}

tell application "System Events" to keystroke theClipboardTextWithoutAnyLineBreaksOrFormatting

The problem with this method is that if theClipboardTextWithoutAnyLineBreaksOrFormatting contains a very long string, for example 2000 characters, then it will take a while for all of the text to be typed out, since it is being done manually in real time.

Is there a better way?

Best Answer

Yes.

User @jackjr300 has devised an ideal solution to this question here:

This solution works system-wide and does not affect the clipboard.

The provided TypeCharacters Objective-C file is significantly (i.e., exponentially) faster at typing text than AppleScript's native keystroke command.