Tuesday Tip: Code snippets, XMenu-style

Sometimes writing AppleScripts is monotonous. You end up typing the same thing over and over again. To this end we can buy a snippet organizer or we could use XMenu to assist. Here are two ideas to speed things up…

1. In XMenu’s Snippets menu you can store bits of code in plain-text files (or even in AppleScript’s text format: .applescript files). Then when you have a new script to write you can choose one of these snippets and the copy will be inserted just like as if you typed it (contrary to e.g. the User-Defined menu which opens the files when you select them in the menu).

For example, I have a bit of text in a file with a common routine.

tell application id “com.devon-technologies.thinkpro2”
set sel to (selection as list)
repeat with thisRecord in sel
— Insert code here
end repeat
end tell

Now when I press compile, it’s resolved and ready for more specific coding. Note: I didn’t type any of that but used the snippets to paste directly into this post! This is also where the .applescript format comes in handy as it can be opened and compiled to make sure it will run correctly whereas typing into TextEdit can’t directly.

2. What if you just want to build some core template scripts? In XMenu’s User-Defined menu, you can add a script (or even link to a .applescript file in the Snippets folder to use it either way) Now instead of inserting code, it opens the file itself. However… you should first duplicate this file or you will save over the original (and if it is linked to the snippet, you will affect it too).

Of course, using plain-text for yours snippets you can apply this to Javascript, Ruby, Python, etc.

A last little hint: In my Snippets folder I have a subfolder called “Applescript” and in that I have one named “DEVONthink”. This way I can keep these snippets organized for easier access. I also gave the files names that made sense to me, like “DT_Tell_core.applescript” (“core” telling me it’s just a reusable snippet). Organize and name as you see fit.