Overriding Smart Tag Recognizers

By default, the smart tag recognizes text if any of the strings in the Terms property (or any of the regular expressions in the Expressions property) matches text in the document. You can override the default recognizer by creating your own smart tag recognizer. If you create your own recognizer, you must write code to (1) parse the text in the document or workbook, (2) locate the terms and regular expressions, and (3) attach the smart tag to the recognized term. This gives you much greater control over which terms will have a smart tag attached. For example, you might want to check for specific conditions before adding the smart tag to the document.

The Recognize method is called by Word or Excel whenever text within the document has changed. Therefore, it's important that when you override this method, you optimize your code to perform well—for example, do not make any unnecessary variable declarations and assignments. Also, you should not make any calls into Word's or Excel's object model from the Recognize method.

To show you how you might override the default recognizer, we look at the example we used in Listing 9.11, rewriting it so that it first checks whether the computer has an Internet connection before adding the smart tag. If a network connection is detected, it loops through tokens in the document to see whether any of them matches the words in the Words collection. Only then does it add the smart tag. The code also changes the caption of the action depending on whether or not the computer is offline.

Note that this code searches for tokens (individual words) by looping through the tokenList passed to the Recognize method. Although you could loop through the text string and parse the text until it matches a phrase or regular expression, we want to present the simplest case in our example.

0 0

Post a comment