In the past, we have shown you how to change the color of certain words in your document. Take a look at the Syntax highlighting sample application in the source code library.
In this newsletter, we are going to show you how to analyze the last word before the current input position and check whether it is a keyword or not. If you want to implement something like AutoFormat, which is able to recognize a typed URL, the algorithm that we presented in the above sample application is inefficient, as every typed word must be checked.
The solution to this problem is to start checking only when the user types a specific character, such as 'w' ('w'- symbolizing the beginning of a URL, like 'www.textcontrol.com.development').
When the user types 'w' for the first time, a counter is initialized to count the inserted characters. If the user now types 'w' three times, followed by a dot, we can assume that s/he wants to insert a URL. Naturally, the next string is followed by another dot to separate it from the suffix.
Therefore, we wait for the next delimiter that marks the end of a word. This is usually a space or a return. Generally, the URL should be complete and we can format it - i.e. turn it into a marked text field.
So that we can reuse the code for other keywords, we put all the checking code into a class called AutoFormatItem. This class is initialized with a keyword when an instance is created.
When a key is pressed, the method NextChar is called, passing the character as a parameter. Now the class automatically tracks whether the entered character sequence is a keyword. This can be queried with the "StartsWithKeyWord" method. It returns true as long as the word is a keyword and false, if a character has been entered that breaks the sequence.
Now, if a delimiter is entered, StartsWithKeyword is called and a URL is inserted, if the StartsWithKeyWord method returns true. After that, Start is called to reset the class internal counter.
The Newsletter Team