Tom Copeland's Recent Posts

RSS Feeds

« A shortcut for PMD XPath rules | Main | A Java to HTML converter »

Syntax highlighting and JavaCC

A recent post to the javacc-users list asked about using the token definitions in JavaCC for syntax highlighting language elements.  In response I put together a small JNLP-launched example app that builds a little Map of colors to use for each kind of token.   This example is just using a JTextPane, getting each token, and calling setSelection and setSelectionColor in turn to highlight each different token type.

How would we do this for real?  I haven't fiddled with the more advanced JEditorPane usage, but it looks like StyledDocument and AttributeSets with the various colors would do the trick.  You would need to have two modes - one, when a new file was opened, to add the proper colors to all the keywords, and another, as the user was typing, to analyze the text and hopefully make the color change without having to retokenize the entire document.  It seems like JTextComponent supports this sort of thing pretty well since it uses MVC; you could implement highlighting in the background without blocking the user's input.  Actually, JavaCC's tokenizers are fast enough that you could retokenize all but the largest documents without the user noticing, I bet.

Along these same lines, over on the Netbeans project they're doing interesting stuff with Schliemann.  It's sort of like a DSL for language highlighting/folding/indentation;  very nifty!

My JavaCC book should be in stock in less than ten days... huzzah!

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d83451d3c069e200e550803c798834

Listed below are links to weblogs that reference Syntax highlighting and JavaCC:

Comments

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been saved. Comments are moderated and will not appear until approved by the author. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment

Comments are moderated, and will not appear until the author has approved them.