How to add keywords (and change their colour) to CodeMirror?

Issue

I am currently using Brackets (code editor) to create some C source files.
It uses CodeMirror to handle the syntax highlighting and I have been attempting now for a while to try and add keywords to it.

I managed to add ‘printf’ as a keyword by modifying this code here and adding ‘printf’ to the keywords.
However, I would like to change the colour of it and haven’t been able to do this. How could I do this?

Also, in the same way as line comments such as ‘//’ highlight the whole line, I would like to also do this if the line starts with ‘#’, changing the colour as well.

I am pretty sure I need to modify the ‘clike.js’ file to add the new keywords and some other .css file in order to change the colours but I just can’t seem to work it out.

Thanks for any help.

Solution

Solved it.

Firstly I changed the ‘clike.js’ file adding the following ‘if’ blocks to handle the changes I wanted.

function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == "#") {
      if (stream.eat("i")) {
        stream.skipTo(" ")
        return "include";
      }
      else if (stream.eat("p")) {
        stream.skipToEnd();
        return "pragma";
      }
    }
    ...

So as the file is parsed, the outer block checks for a ‘#’. When one is detected, it then checks if the next letter is ‘i’ or ‘p’.
This was because I wanted to highlight either:

#include ...

or

#pragma ...

If an ‘i’ is found as the next character, I use stream.skipTo(" ") to skip to the next whitespace so that only #include is highlighted.
If a ‘p’ is found, I instead use stream.skipToEnd() so that the entire line is highlighted.

The return statement then returns a string that relates to what has been found and a corresponding style in your themes .css file specifies things such as colour or style.
For example, in my case, the brackets default light theme is located at Brackets.app/Contents/www/extensions/default/LightTheme/main.less.
Within this file I added the following lines:

.cm-pragma {color: #a50000;}
.cm-include {color: #A0522D;}

This then specifies the colour that you wish that text to be, but I assume other things could be specified as well, e.g. bold, italics, maybe font etc.

If you wished to make a new return type ‘test’, you would return "test"; in your javascript file and your corresponding style in your theme file would be named .cm-include {...};.

Hope this can be of assistance to anyone else wanting to do the same thing.

Answered By – myles

Answer Checked By – Cary Denson (AngularFixing Admin)

Leave a Reply

Your email address will not be published.