Create An AppleScript From the Frontmost Application - Using AppleScript

tell-block.jpg

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:

scripteditor-icon.jpgFirstly, 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!

* * *

Think different?