Geertjan's Blog

  • September 2, 2007

How to Write a Groovy Editor (Part 5)

Geertjan Wielenga
Product Manager
When dealing with Groovy maps, and named parameters, I wanted the parameters to have a distinct color:

However, this is a bit tricky. The parameters occur within strings. So somehow you need to get within a string, identify a parameter, and then give the parameter a specific color. But this is how my string is defined:

[\^ "\\n" "\\r"] \*

So, how am I able to find the parameter within the above declaration? By rewriting it so that 'state' can be handled. As explained in NBS Language Description, "it is hard to describe some languages using a stateless lexical analyser. That is why the NBS language contains support for states". Using the state approach to syntax, you can specify when the parser should switch from one state to another. For example, this is how you can define, for Properties files, the state the parser should move to, depending on the current character:

TOKEN:key:( [\^ "=" "\\n" "\\r"]\* ):<BEFORE_EQUAL>
TOKEN:whitespace:( ["\\n" "\\r"]+ ):<DEFAULT>
TOKEN:operator:( "=" ):<AFTER_EQUAL>
TOKEN:whitespace:( ["\\n" "\\r"]+ ):<DEFAULT>
TOKEN:value:( [\^ "\\n" "\\r"]\* )

The first line declares that the parser is in the 'key' TOKEN, unless an equal sign or a line break is encountered. In these 'unless' cases, the parser switches to the BEFORE_EQUAL state. For line breaks, the parser then switches back to the DEFAULT state (for the next key), while it switches to the AFTER_EQUAL state for equal signs only. Until a line break is reached, everything the parser encounters is part of the 'value' token. Then, if you give the 'key' TOKEN one color, and the 'value' TOKEN a different color, you have syntax coloring that will be useful in distinguising keys from values. (You can also assign a color to the 'operator' TOKEN and then the equal sign will have a distinct color.) And all this without any complex Java coding, but leveraging the power of the Java switch statements in a very simplified way.

Join the discussion

Comments ( 1 )
  • Pan Feng Sunday, September 2, 2007


    I think the codes should support single quote too.

    Because in Groovy

    "" denote groovy.lang.GString

    '' denote java.lang.String

Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.Captcha

Integrated Cloud Applications & Platform Services