MacOS – AppleScript: Is it possible to have an unselected “default answer” in an input dialog

applescriptdialogmacos

When one uses the default answer parameter in display dialog in AppleScript, whatever text is set to default answer is automatically highlighted upon display of the dialog.

Is it possible to specify a default answer without the answer highlighted?

I would ideally like the cursor to be placed after the last character of the default answer, so that the user can append text to this answer without first pressing the key (or, worse, accidentally overwriting the default answer).

Best Answer

I figured it out.

If one presses the right arrow key just milliseconds before the dialog is displayed, then the default answer will not be selected and the blinking cursor will be placed after the default text.

You can perform this action in AppleScript like so:

-- Unselect the “default answer” in an input dialog:
tell application "System Events"
        key code 124 -- right arrow key
end tell

display dialog "Enter a keyword:" default answer "I do not want this text to be highlighted. "

In theory, the above solution should not work. In theory, the key press should commence and complete before the display dialog command initiates. But, this method does work, for whatever reason.


Note: This method will not work if you insert key code 124 before the very first dialog of your AppleScript file. In this case, my above code will fail to behave as desired and the default answer text will remain selected. (It may misleadingly appear to work correctly if you are simply running the AppleScript code from within Script Editor.app or Automator.app, but it will not work correctly if you run the .scpt file via Fast Scripts, osascript in Terminal.app, or any other method.)

However, if the display dialog in question is the second, third, or fiftieth dialog in an AppleScript file, my solution works correctly. Don't ask me why it won't work on the first dialog (because I don't know).

So, you have no choice but to rearrange the dialogs of the AppleScript file so that the first dialog does not need to have a default answer.

One workaround, if your initial dialog must have a default answer that is unselected, is to insert a dialog that automatically proceeds after a brief amount of time has elapsed. This dialog should be inserted immediately before the above tell block. It's not an elegant solution, but here is some code that will work:

display alert "Please wait..." message "..." buttons ("") giving up after 1
-- I think that "1" is the minimum for "giving up after." I tried "0.5" and the dialog completely stalled.

As long as it does not precede the initial dialog of a script, I have personally found my method to be reliable; it works 100% of the time on my computer.