Extending Prism ▲ Prism

# Language definitions

Every language is defined as a set of tokens, which are expressed as regular expressions. For example, this is the language definition for CSS:

A regular expression literal is the simplest way to express a token. An alternative way, with more options, is by using an object literal. With that notation, the regular expression describing the token would be the `pattern` attribute:

    ...
    'tokenname': {
    	pattern: /regex/
    }
    ...

So far the functionality is exactly the same between the short and extended notations. However, the extended notation allows for additional options:

inside
  This property accepts another object literal, with tokens that are allowed to be nested in this token. This makes it easier to define certain languages. However, keep in mind that they’re slower and if coded poorly, can even result in infinite recursion. For an example of nested tokens, check out the Markup language definition:

lookbehind
  This option mitigates JavaScript’s lack of lookbehind. When set to `true`, the first capturing group in the regex `pattern` is discarded when matching this token, so it effectively behaves as if it was lookbehind. For an example of this, check out the C-like language definition, in particular the comment and class-name tokens:

rest
  Accepts an object literal with tokens and appends them to the end of the current object literal. Useful for referring to tokens defined elsewhere. For an example where `rest` is useful, check the Markup definitions above.
alias
  This option can be used to define one or more aliases for the matched token. The result will be, that the styles of the token and its aliases are combined. This can be useful, to combine the styling of a standard token, which is already supported by most of the themes, with a semantically correct token name. The option can be set to a string literal or an array of string literals. In the following example the token name `latex-equation` is not supported by any theme, but it will be highlighted the same as a string.

      {
      	'latex-equation': {
      		pattern: /\$(\\?.)*?\$/g,
      		alias: 'string'
      	}
      }

greedy
  This is a boolean attribute. It is intended to solve a common problem with patterns that match long strings like comments, regex or string literals. For example, comments are parsed first, but if the string `/* foo */` appears inside a string, you would not want it to be highlighted as a comment. The greedy-property allows a pattern to ignore previous matches of other patterns, and overwrite them when necessary. Use this flag with restraint, as it incurs a small performance overhead. The following example demonstrates its usage:

      'string': {
      	pattern: /(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
      	greedy: true
      }

Unless explicitly allowed through the `inside` property, each token cannot contain other tokens, so their order is significant. Although per the ECMAScript specification, objects are not required to have a specific ordering of their properties, in practice they do in every modern browser.

In most languages there are multiple different ways of declaring the same constructs (e.g. comments, strings, ...) and sometimes it is difficult or unpractical to match all of them with one single regular expression. To add multiple regular expressions for one token name an array can be used:

    ...
    'tokenname': [ /regex0/, /regex1/, { pattern: /regex2/ } ]
    ...

## Helper functions

Prism also provides some useful function for creating and modifying language definitions. `Prism.languages.insertBefore` can be used to modify existing languages definitions. `Prism.languages.extend` is useful for when your language is very similar to another existing language.

# Creating a new language definition

This section will explain the usual workflow of creating a new language definition.

As an example, we will create the language definition of the fictional Foo's Binary, Artistic Robots™ language or just Foo Bar for short.

1. Create a new file `components/prism-foo-bar.js`.

   In this example, we choose `foo-bar` as the id of the new language. The language id has to be unique and should work well with the `language-xxxx` CSS class name Prism uses to refer to language definitions. Your language id should ideally match the regular expression `/^[a-z][a-z\d]*(?:-[a-z][a-z\d]*)*$/`.

2. Edit `components.json` to register the new language by adding it to the `languages` object. (Please note that all language entries are sorted alphabetically by title.)
   Our new entry for this example will look like this:

       "foo-bar": {
       	"title": "Foo Bar",
       	"owner": "Your GitHub name"
       }

   If your language definition depends any other languages, you have to specify this here as well by adding a `"require"` property. E.g. `"require": "clike"`, or `"require" : ["markup", "css"]`. For more information on dependencies read the declaring dependencies section.

   Note: Any changes made to `components.json` require a rebuild (see step 3).

3. Rebuild Prism by running `npm run build`.

   This will make your language available to the test page, or more precise: your local version of it. You can open your local `test.html` page in any browser, select your language, and see how your language definition highlights any code you input.

   Note: You have to reload the test page to apply changes made to `prism-foo-bar.js` but you don't have to rebuild Prism itself. However, if you change `components.json` (e.g. because you added a dependency) then these changes will not show up on the test page until you rebuild Prism.

4. Write the language definition.

   The above section already explains the makeup of language definitions.

5. Adding aliases.

   Aliases for are useful if your language is known under more than just one name or there are very common abbreviations for your language (e.g. JS for JavaScript). Keep in mind that aliases are very similar to language ids in that they also have to be unique (i.e. there cannot be an alias which is the same as another alias of language id) and work as CSS class names.

   In this example, we will register the alias `foo` for `foo-bar` because Foo Bar code is stored in `.foo` files.

   To add the alias, we add this line at the end of `prism-foo-bar.js`:

       Prism.languages.foo = Prism.languages['foo-bar'];

   Aliases also have to be registered in `components.json` by adding the `alias` property to the language entry. In this example, the updated entry will look like this:

       "foo-bar": {
       	"title": "Foo Bar",
       	"alias": "foo",
       	"owner": "Your GitHub name"
       }

   Note: `alias` can also be a string array if you need to register multiple aliases.

   Using `aliasTitles`, it's also possible to give aliases specific titles. In this example, this won't be necessary but a good example as to where this is useful is the markup language:

       "markup": {
       	"title": "Markup",
       	"alias": ["html", "xml", "svg", "mathml"],
       	"aliasTitles": {
       		"html": "HTML",
       		"xml": "XML",
       		"svg": "SVG",
       		"mathml": "MathML"
       	},
       	"option": "default"
       }

6. Adding tests.

   Create a folder `tests/languages/foo-bar/`. This is where your test files will live. The test format and how to run tests is described here.

   You should add a test for every major feature of your language. Test files should test the common case and certain edge cases (if any). Good examples are the tests of the JavaScript language.

   You can use this template for new `.test` files:

       The code to test.

       ----------------------------------------------------

       ----------------------------------------------------

       Brief description.

   For every test file:

   1. Add the code to test and a brief description.

   2. Verify that your language definition correctly highlights the test code. This can be done using your local version of the test page.
      Note: Using the Show tokens options, you see the token stream your language definition created.

   3. Once you carefully checked that the test case is handled correctly (i.e. by using the test page), run the following command:

      `npm run test:languages -- --language=foo-bar --accept`

      This command will take the token stream your language definition currently produces and inserted into the test file. The empty space between the two lines separating the code and the description of test case will be replaced with a simplified version of the token stream.

   4. Carefully check that the inserted token stream JSON is what you expect.

   5. Re-run `npm run test:languages -- --language=foo-bar` to verify that the test passes.

7. Add an example page.

   Create a new file `examples/prism-foo-bar.html`. This will be the template containing the example markup. Just look at other examples to see how these files are structured.
   We don't have any rules as to what counts as an example, so a single Full example section where you present the highlighting of the major features of the language is enough.

8. Run `npm test` to check that all tests pass, not just your language tests.
   This will usually pass without problems. If you can't get all the tests to pass, skip this step.

9. Run `npm run build` again.

   Your language definition is now ready!

# Dependencies

Languages and plugins can depend on each other, so Prism has its own dependency system to declare and resolve dependencies.

## Declaring dependencies

You declare a dependency by adding a property to the entry of your language or plugin in the `components.json` file. The name of the property will be dependency kind and its value will be the component id of the dependee. If multiple languages or plugins are depended upon then you can also declare an array of component ids.

In the following example, we will use the `require` dependency kind to declare that a fictional language Foo depends on the JavaScript language and that another fictional language Bar depends on both JavaScript and CSS.

    {
    	"languages": {
    		"javascript": { "title": "JavaScript" },
    		"css": { "title": "CSS" },
    		...,
    		"foo": {
    			"title": "Foo",
    			"require": "javascript"
    		},
    		"bar": {
    			"title": "Bar",
    			"require": ["css", "javascript"]
    		}
    	}
    }

### Dependency kinds

There are 3 kinds of dependencies:

`require`
  Prism will ensure that all dependees are loaded before the depender.
  You are not allowed to modify the dependees unless they are also declared as `modify`.

  This kind of dependency is most useful if you e.g. extend another language or dependee as an embedded language (e.g. like PHP is embedded in HTML).

`optional`
  Prism will ensure that an optional dependee is loaded before the depender if the dependee is loaded. Unlike `require` dependencies which also guarantee that the dependees are loaded, `optional` dependencies only guarantee the order of loaded components.
  You are not allowed to modify the dependees. If you need to modify the optional dependee, declare it as `modify` instead.

  This kind of dependency is useful if you have embedded languages but you want to give the users a choice as to whether they want to include the embedded language. By using `optional` dependencies, users can better control the bundle size of Prism by only including the languages they need.
  E.g. HTTP can highlight JSON and XML payloads but it doesn't force the user to include these languages.

`modify`
  This is an `optional` dependency which also declares that the depender might modify the dependees.

  This kind of dependency is useful if your language modifies another language (e.g. by adding tokens).
  E.g. CSS Extras adds new tokens to the CSS language.

To summarize the properties of the different dependency kinds:

| Non-optional | Optional
--- | --- | ---
Read only | `require` | `optional`
Modifiable |  | `modify`

Note: You can declare a component as both `require` and `modify`

## Resolving dependencies

We consider the dependencies of components an implementation detail, so they may change from release to release. Prism will usually resolve dependencies for you automatically. So you won't have to worry about dependency loading if you download a bundle or use the `loadLanguages` function in NodeJS, the AutoLoader, or our Babel plugin.

If you have to resolve dependencies yourself, use the `getLoader` function exported by `dependencies.js`. Example:

    const getLoader = require('prismjs/dependencies');
    const components = require('prismjs/components');

    const componentsToLoad = ['markup', 'css', 'php'];
    const loadedComponents = ['clike', 'javascript'];

    const loader = getLoader(components, componentsToLoad, loadedComponents);
    loader.load(id => {
    	require(`prismjs/components/prism-${id}.min.js`);
    });

For more details on the `getLoader` API, check out the inline documentation.

# Writing plugins

Prism’s plugin architecture is fairly simple. To add a callback, you use `Prism.hooks.add(hookname, callback)`. `hookname` is a string with the hook id, that uniquely identifies the hook your code should run at. `callback` is a function that accepts one parameter: an object with various variables that can be modified, since objects in JavaScript are passed by reference. For example, here’s a plugin from the Markup language definition that adds a tooltip to entity tokens which shows the actual character encoded:

    Prism.hooks.add('wrap', function(env) {
    	if (env.token === 'entity') {
    		env.attributes['title'] = env.content.replace(/&amp;/, '&');
    	}
    });

Of course, to understand which hooks to use you would have to read Prism’s source. Imagine where you would add your code and then find the appropriate hook. If there is no hook you can use, you may request one to be added, detailing why you need it there.

# API documentation

All public and stable parts of Prism's API are documented here.