Language definition guide

Highlighting overview

Programming language code consists of parts with different rules of parsing: keywords like for or ifdon’t make sense inside strings, strings may contain backslash-escaped symbols like \"and comments usually don’t contain anything interesting except the end of the comment.

In highlight.js such parts are called “modes”.

Each mode consists of:

  • starting condition
  • ending condition
  • list of contained sub-modes
  • lexing rules and keywords
  • …exotic stuff like another language inside a language
    The parser’s work is to look for modes and their keywords.Upon finding, it wraps them into the markup <span class="…">…</span>and puts the name of the mode (“string”, “comment”, “number”)or a keyword group name (“keyword”, “literal”, “built-in”) as the span’s class name.

General syntax

A language definition is a JavaScript object describing the default parsing mode for the language.This default mode contains sub-modes which in turn contain other sub-modes, effectively making the language definition a tree of modes.

Here’s an example:

  1. {
  2. case_insensitive: true, // language is case-insensitive
  3. keywords: 'for if while',
  4. contains: [
  5. {
  6. className: 'string',
  7. begin: '"', end: '"'
  8. },
  9. hljs.COMMENT(
  10. '/\\*', // begin
  11. '\\*/', // end
  12. {
  13. contains: [
  14. {
  15. className: 'doc', begin: '@\\w+'
  16. }
  17. ]
  18. }
  19. )
  20. ]
  21. }

Usually the default mode accounts for the majority of the code and describes all language keywords.A notable exception here is XML in which a default mode is just a user text that doesn’t contain any keywords,and most interesting parsing happens inside tags.

Keywords

In the simple case language keywords are defined in a string, separated by space:

  1. {
  2. keywords: 'else for if while'
  3. }

Some languages have different kinds of “keywords” that might not be called as such by the language specbut are very close to them from the point of view of a syntax highlighter. These are all sorts of “literals”, “built-ins”, “symbols” and such.To define such keyword groups the attribute keywords becomes an object each property of which defines its own group of keywords:

  1. {
  2. keywords: {
  3. keyword: 'else for if while',
  4. literal: 'false true null'
  5. }
  6. }

The group name becomes then a class name in a generated markup enabling different styling for different kinds of keywords.

To detect keywords highlight.js breaks the processed chunk of code into separate words — a process called lexing.The “word” here is defined by the regexp [a-zA-Z][a-zA-Z0-9_]* that works for keywords in most languages.Different lexing rules can be defined by the lexemes attribute:

  1. {
  2. lexemes '-[a-z]+',
  3. keywords: '-import -export'
  4. }

Sub-modes

Sub-modes are listed in the contains attribute:

  1. {
  2. keywords: '...',
  3. contains: [
  4. hljs.QUOTE_STRING_MODE,
  5. hljs.C_LINE_COMMENT,
  6. { ... custom mode definition ... }
  7. ]
  8. }

A mode can reference itself in the contains array by using a special keyword 'self‘.This is commonly used to define nested modes:

  1. {
  2. className: 'object',
  3. begin: '{', end: '}',
  4. contains: [hljs.QUOTE_STRING_MODE, 'self']
  5. }

Comments

To define custom comments it is recommended to use a built-in helper function hljs.COMMENT instead of describing the mode directly, as it also defines a few default sub-modes that improve language detection and do other nice things.

Parameters for the function are:

  1. hljs.COMMENT(
  2. begin, // begin regex
  3. end, // end regex
  4. extra // optional object with extra attributes to override defaults
  5. // (for example {relevance: 0})
  6. )

Markup generation

Modes usually generate actual highlighting markup — <span> elements with specific class names that are defined by the className attribute:

  1. {
  2. contains: [
  3. {
  4. className: 'string',
  5. // ... other attributes
  6. },
  7. {
  8. className: 'number',
  9. // ...
  10. }
  11. ]
  12. }

Names are not required to be unique, it’s quite common to have several definitions with the same name.For example, many languages have various syntaxes for strings, comments, etc…

Sometimes modes are defined only to support specific parsing rules and aren’t needed in the final markup.A classic example is an escaping sequence inside strings allowing them to contain an ending quote.

  1. {
  2. className: 'string',
  3. begin: '"', end: '"',
  4. contains: [{begin: '\\\\.'}],
  5. }

For such modes className attribute should be omitted so they won’t generate excessive markup.

Mode attributes

Other useful attributes are defined in the mode reference.

Relevance

Highlight.js tries to automatically detect the language of a code fragment.The heuristics is essentially simple: it tries to highlight a fragment with all the language definitionsand the one that yields most specific modes and keywords wins. The job of a language definitionis to help this heuristics by hinting relative relevance (or irrelevance) of modes.

This is best illustrated by example. Python has special kinds of strings defined by prefix letters before the quotes:r"…", u"…". If a code fragment contains such strings there is a good chance that it’s in Python.So these string modes are given high relevance:

  1. {
  2. className: 'string',
  3. begin: 'r"', end: '"',
  4. relevance: 10
  5. }

On the other hand, conventional strings in plain single or double quotes aren’t specific to any languageand it makes sense to bring their relevance to zero to lessen statistical noise:

  1. {
  2. className: 'string',
  3. begin: '"', end: '"',
  4. relevance: 0
  5. }

The default value for relevance is 1. When setting an explicit value it’s recommended to use either 10 or 0.

Keywords also influence relevance. Each of them usually has a relevance of 1, but there are some unique namesthat aren’t likely to be found outside of their languages, even in the form of variable names.For example just having reinterpret_cast somewhere in the code is a good indicator that we’re looking at C++.It’s worth to set relevance of such keywords a bit higher. This is done with a pipe:

  1. {
  2. keywords: 'for if reinterpret_cast|10'
  3. }

Illegal symbols

Another way to improve language detection is to define illegal symbols for a mode.For example in Python first line of class definition (class MyClass(object):) cannot contain symbol “{” or a newline.Presence of these symbols clearly shows that the language is not Python and the parser can drop this attempt early.

Illegal symbols are defined as a a single regular expression:

  1. {
  2. className: 'class',
  3. illegal: '[${]'
  4. }

Pre-defined modes and regular expressions

Many languages share common modes and regular expressions. Such expressions are defined in core highlight.js codeat the end under “Common regexps” and “Common modes” titles. Use them when possible.

Contributing

Follow the contributor checklist.