Code Highlighting with Prism.JS

I have been using prismjs for a bit now. I like it. I noticed today though that it doesn’t color annotations in Java. My initial attempt at annotation coloring worked.

Prism.languages.java = Prism.languages.extend('clike', {
        'annotation': /(@{1}\w*\(.*?\))|(@{1}\w+)/i,
        'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto...)\b/,
        'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+(?:e[+-]?\d+)?[df]?\b/i,
        'operator': {
                pattern: /(^|[^.])(?:\+[+=]?|-[-=]?|!=?|<<?=?|>>?>?=?|==?|&[&=]?|\|[|=]?|\*=?|\/=?|%=?|\^=?|[?:~])/m,
                lookbehind: true
        }
});

Until but it failed to color annotations with parameters for some reason. A bit of debugging and I discovered that the function attribute was matching before the annotation attribute had a chance to run. At first I tried overriding the function attribute. That was potentially very damaging and made me super nervous. After a lot of hunting I discovered the insertBefore. This allows us to specify order. The first parameter is the language, the second is the attribute that we want to go before, and the following are the attributes we want to define. In this case we are defining annotation to happen before function. This works!

Prism.languages.java = Prism.languages.extend('clike', {
        'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto...)\b/,
        'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+(?:e[+-]?\d+)?[df]?\b/i,
        'operator': {
                pattern: /(^|[^.])(?:\+[+=]?|-[-=]?|!=?|<<?=?|>>?>?=?|==?|&[&=]?|\|[|=]?|\*=?|\/=?|%=?|\^=?|[?:~])/m,
                lookbehind: true
        }
});

Prism.languages.insertBefore('java','function', {
        'annotation': /(@{1}\w*\(.*?\))|(@{1}\w+)/i,
});

You can see my commit here

Slow Annoying Builds?

Sign up for FREE Gradle Tips on faster android builds, and how to make android development easier.

Jim

Android Development

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>