Custom Syntax Highlighting

time to read 5 min | 872 words

Just using the Boo syntax isn't really enough in many cases, you want to handle your own custom keywords, behaviors, etc.

#Develop make this a piece of cake, since it defines the syntax highlighting using an XML file, and handles the actual parsing and coloring on its on. Here is the overall structure of such a file:

<?xml version="1.0"?>
<SyntaxDefinition name="Boo" 
                  extensions=".boo">
  <Environment>
    <Default bold="false"
             italic="false"
             color="SystemColors.WindowText"
             bgcolor="SystemColors.Window" />
    <Selection bold="false"
               italic="false"
               color="SystemColors.HighlightText"
               bgcolor="SystemColors.Highlight" />
  </Environment>

  <Digits name="Digits"
          bold="false"
          italic="false"
          color="DarkBlue" />

  <RuleSets>
    <RuleSet ignorecase="false" >
      <Delimiters>&amp;&lt;&gt;~!@$%^*()-+=|\#/{}[]:;"' ,	.?</Delimiters>

      <Span name="LineComment"
            stopateol="true"
            bold="false"
            italic="false"
            color="Gray" >
        <Begin >#</Begin>
      </Span>

      <KeyWords name="JumpStatements"
                bold="false"
                italic="false"
                color="Navy" >
        <Key word="break"/>
        <Key word="continue"/>
        <Key word="return"/>
        <Key word="yield"/>
        <Key word="goto" />
      </KeyWords>

    </RuleSet>
  </RuleSets>
</SyntaxDefinition>

As you can see, this is pretty easy to work with. Now let us add our own keywords:

<KeyWords name="DslKeywords"
          bold="false"
          italic="false"
          color="DarkOrange" >
  <Key word="specification"/>
  <Key word="users_per_machine"/>
  <Key word="requires"/>
  <Key word="same_machine_as"/>
</KeyWords>

Now we need to load the new language definition (don't forget to change the name, I changed it to "dsl") to the editor an select it:

HighlightingManager.Manager.AddSyntaxModeFileProvider(
    new FileSyntaxModeProvider(@"C:\Path\to\language\definition"));
//.. setup text editor
editorControl.SetHighlighting("dsl");

The result?

image