Word count with On My Command

A few weeks ago, John Gruber posted a short tutorial on ThisService, a utility for turning command-line scripts or AppleScripts into items in the Services menu. The example he gave was a word count utility written in AppleScript. I decided to implement the same idea in On My Command.

A working version was done in about as much time as it took to type. I started with the command

echo __OBJ_TEXT__ | wc  | \
awk '{print "Lines:" $1 "\nWords: "$2 "\n\Chars:" \$3}'


which worked fine, although the aesthetics of the little popup window that displayed the output left something to be desired. I’ll get to how I improved the look in a bit.

(Also, I’ve split the command here into two lines so it will fit this column of the blog. I entered only one line [and no backslash] in the working version.)

The command is one of those great pipelines that Unix devotees love to talk about. It echoes the selected text (__OBJ_TEXT__ is the OMC variable that represents the selected text), and pipes that to the wc (word count) command. With no options, wc analyzes the text and returns the number of lines, words, and characters (bytes), with the numbers separated by whitespace. This line of numbers is then piped to awk, which adds the explanatory text and splits the output over three lines.

By default, the popup window in which the output is displayed uses 9-point Monaco, a font that’s just too small for my middle-aged eyes. Fortunately, OMCEdit, the OMC companion program, has an option for changing the size, style, font, etc. of the output window. (Apparently, you can also design your own dialog window in Interface Builder and OMC will use the resulting NIB file, but I haven’t tried that yet.) I changed to a smaller window and a bigger, nicer-looking font, and rejiggered the whitespace in the output text to get something that looks better to me.

Here’s the OMCEdit command editing window

and the OMCEdit window editing window

The result, here counting the words in a paragraph of Touretzky’s Gentle Introduction to Symbolic Computing , looks like this

Is this better than Gruber’s Services menu item? Not really. ThisService is very much like On My Command in that it does all the heavy lifting for you. I do see two small advantages in making Contextual menu items over Services menu items:

• Contextual menu wil pop up right on the thing you want to act on, while you have to run your mouse up to the top left of the screen to get at the Services menu;
• Contextual menu items can be at the top level, while Services menu items have to be at least one submenu down.

I’m not sure I’ll keep Word Count in my Contextual menu, because I seldom need to count words (or lines, or characters). But the exercise of making it showed me again how fun and easy it is to use On My Command.