4.6. Adding Word CountIf there's one feature that TextEdit lacks over its competitors, it's the ability to count the number of words in a document. With all the powerful searching, typographical, and speech tools TextEdit has, it almost makes you wonder whether an Apple programmer was just sick the day he was supposed to program that feature. Thankfully, AppleScript comes to your aidagain. You can write a short script that not only counts the number of words in your document but also counts the paragraphs and even the number of characters in your documentgreat for tricking people into thinking you've written a lot for your term paper. The key to all this text-based power is the Text Suite, a section of many programs' dictionaries that deals exclusively with the nitty-gritty of text (like counting individual characters). You'll find the Text Suite in the dictionaries of professional programs like Microsoft Word (Section 4.7)but more immediately, you'll also find the Text Suite in TextEdit's dictionary. By employing the Text Suite as described in the following pages, you can write a script to count the number of words in any TextEdit document 4.6.1. Employing the Text SuiteIf you open TextEdit's dictionary and browse the lefthand pane, you'll find that the Text Suite already includes entries for word, character, and paragraph. These are the fundamental nouns (or classes) of AppleScript's text handling. By using those keywords as follows, you can create a script to add a basic word count feature to TextEdit: tell application "TextEdit" activate --Count the characters: set allCharacters to every character of the front document set numberOfCharacters to (count allCharacters) set characterText to "Characters: " & numberOfCharacters --Count the words: set allWords to every word of the front document set numberOfWords to (count allWords) set wordText to "Words: " & numberOfWords --Count the paragraphs: set allParagraphs to every paragraph of the front document set numberOfParagraphs to (count allParagraphs) set paragraphText to "Paragraphs: " & numberOfParagraphs --Assemble the text for the dialog box: set dialogText to characterText & return & wordText & return ¬ & paragraphText display dialog dialogText end tell Here's how the script breaks down:
|