Create An AppleScript From the Frontmost Application – Using AppleScript

When the inspiration for a new AppleScript strikes, I’m often working in the application that I want to automate. Nevertheless, if the target task is minor, those few moments that it takes to open Script Editor and enter in the skeleton of tell blocks occasionally dissuades me from creating the script at all. Thankfully, the solution is simple – create an AppleScript to automate the task of creating AppleScripts!
The below script will open a new Script Editor document and populate it with the text shown in the image to the right (substituting, of course, “MarsEdit” for whatever your frontmost application is at the time the script is run). The --do some stuff is pre-selected so you can start typing right away without reaching for the mouse or deleting any text. Really fast.
set NL to ASCII character 10 tell application "System Events" set thisApp to name of first process whose frontmost is true tell process thisApp set appName to (name of menu 2) of menu bar 1 end tell end tell tell application "Script Editor" launch make new document set paragraph 1 of contents of document 1 to "tell application¬ \"" & appName & "\"" & NL & "--do some stuff" & NL & "end tell" try compile document 1 end try activate set selection to (characters 2 thru 16 of paragraph 2) of ¬ document 1 end tell
About the script:
Firstly, this script uses some GUI foo, so you’ll need to enable GUI Scripting in AppleScript Utility (Applications/AppleScript/AppleScript Utility) by ticking the check box. The name of most applications (for use in tell application "appName") can be extracted without resorting to the menu bar trickery, but some, like Firefox or Azureus, return strange values using only the name of first process whose frontmost is true command. So this is a workaround.
If you like the script or see any way it can be improved, let me know it the comments!
January 19th, 2009 at 2:40 am
Hi, looking at your script I thought it could be simplified. So I made a revision of yours and came with a script that does exactly the same thing but the syntax is simpler, that is:
–this only will get the name of the front application for us:
tell application “System Events” to set frontApp to name of first process whose frontmost is true
tell application “Script Editor”
–might as well go here:
activate
set a to make new document
–in case Script Editor has already one or several documents opened:
set a to the frontmost
–simple and straightforward:
set contents of document a to “tell application \”" & frontApp & “\”" & return & return & “end tell”
try
compile document a
end try
end tell
–and that’s it :), it should return true
–best of luck!
Regards,