Page 140 - DCAP408_WEB_PROGRAMMING
P. 140
Windows Programming
Notes StyleConstants.setBold(style, true);
StyleConstants.setItalic(style, false);
styles.put(“tag”, style);
...
The section of text in the document is then colored according to the style retrieved from the
look-up table.
document.setCharacterAttributes(
t.getCharBegin(),
t.getCharEnd()-t.getCharBegin(),
getStyle(t.getDescription()),
true
);
Coloring Parts of the Document
The entire document is colored and it looks good in the editor. You might think that this is the
end of the story. Sadly, its not. Editors are meant to edit documents. The documents change. The
obvious approach is to re-color the document when the text changes. This may work for small
documents, but as the document size gets larger it will quickly become unwieldy. For a 1000 line
document, it could take as much as a few seconds to color the entire document. Waiting a few
seconds each time a character is typed does not make for a good text editor.
Notes The trick is that not all of the document needs to be re-colored when something
changes. But how much really needs to be re-colored? Not many editors do this part right.
We have seen editors that re-color the previous three lines and the next three lines. That
approach works most of the time, but it is pretty easy to fool.
Initial State
Every so often the syntax lexer returns to what are known as the initial state. At these times, the
lexer returns a token and continues lexing as if it were at the beginning of the document again.
Since the lexer acts as if it were at the beginning of the document from an initial state, the lexer
could be restarted from this point without effecting the coloring of what comes afterwards. It
can be determined from the last token returned if the lexer is in the initial state after returning
that token.
So that solves half the problem. Just re-color the document from the last initial state. If the user
is only going to append to the end of the document, this solves the problem. We can just keep
track of the last initial state and re-color from there to the end of the document. But what if
something in the middle of the document changes? We really need to keep track of all initial
states so that we can restart the lexer from near anywhere in the document. Then we won’t need
to color the entire rest of the document either. If the lexer returns to an initial state at the same
point that it returned to an initial state the last time, the rest of the document is already colored
correctly.
134 LOVELY PROFESSIONAL UNIVERSITY