Highlight.js - Documentation

Getting Started

Installation

Highlight.js can be installed via several methods, depending on your project’s needs and preferences.

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>

Replace default.min.css with the name of your preferred style. See the styles gallery for options. You might also want to include a specific language:

<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script>
npm install highlight.js
yarn add highlight.js

Basic Usage

After installation, you need to initialize Highlight.js to highlight your code. This typically involves calling the hljs.highlightAll() method after the Highlight.js library and your code have been loaded. Alternatively, you can highlight specific elements individually using hljs.highlightBlock(element) or hljs.highlightElement(element).

First Example

Let’s create a simple HTML file to showcase Highlight.js:

<!DOCTYPE html>
<html>
<head>
<title>Highlight.js Example</title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/languages/javascript.min.js"></script>
</head>
<body>

<pre><code class="language-javascript">
function myFunction() {
  console.log("Hello, world!");
}
</code></pre>

<script>hljs.highlightAll();</script>
</body>
</html>

This code includes the Highlight.js CSS and JavaScript files, specifies the JavaScript language for the code block using the language-javascript class, and then calls hljs.highlightAll() to highlight the code.

Including Highlight.js in your project

The method for including Highlight.js depends on your chosen installation method.

import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';

hljs.registerLanguage('javascript', javascript);
hljs.highlightAll();

Core Concepts

Languages

Highlight.js supports a vast number of programming and markup languages. Each language is defined by a separate language definition file (typically found in the languages directory of the Highlight.js distribution). These files contain regular expressions and other logic that dictate how the code should be parsed and styled. You can register additional languages using the hljs.registerLanguage method or by simply including the necessary language file in your HTML <script> tags via a CDN or file path. A list of supported languages is available on the Highlight.js website.

Highlighting Process

The highlighting process in Highlight.js generally follows these steps:

  1. Language Detection: If not explicitly specified using the language-XXX class attribute on the <pre> or <code> element, Highlight.js attempts to auto-detect the language based on the code content (see the section on Auto-detection).

  2. Parsing: The code is parsed according to the rules defined in the selected language definition file. This involves breaking the code into meaningful segments (tokens) based on syntax rules (keywords, comments, strings, etc.).

  3. Tokenization: Each segment is assigned a token type, indicating its semantic meaning within the language.

  4. Styling: Based on the token types, the corresponding CSS classes are applied to each segment, resulting in the visually highlighted code. These classes are defined in the chosen theme’s stylesheet.

  5. Rendering: The highlighted code is then rendered in the browser.

Configuration Options

While Highlight.js offers a default configuration, it can be customized through several options. These options can affect various aspects of the highlighting process, such as language detection behavior, the use of case-insensitive matching, and more. Consult the Highlight.js documentation and API for a comprehensive list of available configuration options and their usage. Configuration options can typically be set using the hljs.configure() method.

Themes

Highlight.js themes control the visual appearance of highlighted code. Themes are provided as CSS files that define styles for the various token types. Many pre-built themes are available, and you can create your own custom themes by modifying existing ones or creating new CSS files. The theme is typically specified by the CSS file included in your HTML, or potentially through a configuration option. A gallery of available themes can often be found on the Highlight.js website.

Auto-detection

Highlight.js can attempt to automatically detect the language of a code snippet if the language-XXX class is not explicitly provided. This auto-detection relies on heuristics and analyzing the code’s content to identify patterns and keywords associated with different languages. However, auto-detection is not always perfect and might not be reliable in all cases, especially for ambiguous code snippets. For best results, it’s often recommended to explicitly specify the language using the language-XXX class attribute. The effectiveness of auto-detection can also be influenced by configuration options.

Language Support

Supported Languages

Highlight.js boasts support for a wide array of programming languages, markup languages, and more. The complete list of supported languages is available on the Highlight.js website and usually dynamically updated. The availability of a language often depends on the version of Highlight.js you’re using; newer versions frequently add support for more languages. To use a specific language, you typically need to include its corresponding language definition file, either via a CDN, by importing it from a package (if using npm or yarn), or by including it directly.

Adding New Languages

Adding support for a new language involves creating a language definition file. This file describes the syntax and structure of the language using regular expressions and other descriptive metadata. The file should follow the structure outlined in the next section (“Language Definition Structure”). Once created, you’ll need to register this new language definition with Highlight.js. See the Highlight.js documentation for details on registering custom languages. Typically, this involves using the hljs.registerLanguage('languageName', languageDefinition) function, where languageName is the identifier for your language (e.g., ‘mylang’) and languageDefinition is the object you created.

Language Definition Structure

A Highlight.js language definition is a JavaScript object with several key properties. The exact structure can be complex, but typically includes:

The structure often involves nested objects and regular expressions to handle complex grammatical structures. Examining existing language definition files is the best way to understand the intricacies of constructing one.

Customizing Existing Languages

Instead of creating a completely new language definition, you might only need to modify an existing one. This is useful for extending the functionality of an existing language or adapting it to a specific dialect or framework. You can accomplish this by copying the existing language definition, modifying the relevant parts (e.g., adding or changing keywords, regular expressions, or modes), and then registering the modified definition using a new name. Avoid directly modifying the original language definition files to maintain clean and reusable code. The process will involve creating a new object that extends the functionality of the original and then registering it.

Themes

Available Themes

Highlight.js offers a variety of pre-built themes, each providing a distinct visual style for highlighted code. These themes are typically distributed as CSS files. A gallery of available themes is often found on the official Highlight.js website or in the documentation. The selection of themes can vary depending on the version of Highlight.js. Each theme alters the colors and styles applied to the different code tokens (keywords, comments, strings, etc.), giving you control over the visual presentation of your highlighted code.

Creating Custom Themes

Creating a custom theme is relatively straightforward. It involves creating a new CSS file and defining styles for the various classes used by Highlight.js to represent different code elements. These classes often follow a consistent naming convention (e.g., .hljs-keyword, .hljs-string, .hljs-comment). You will style these classes to achieve your desired visual effect. Refer to an existing theme file as a template or guide to understand the structure and naming conventions. You can start with a copy of an existing theme and modify it to your needs.

Theme Structure

A Highlight.js theme is essentially a CSS file. The structure is simple: it consists of CSS selectors that target the classes applied by Highlight.js to the different code elements. For example:

.hljs {
  background: #f8f8f8;
}

.hljs-keyword {
  color: #008000; /* Green keywords */
}

.hljs-string {
  color: #a31515; /* Red strings */
}

.hljs-comment {
  color: #808080; /* Gray comments */
}

This example shows basic styling; more complex themes might use more sophisticated CSS to handle different situations, such as nested elements or specific language constructs.

Applying Themes

Applying a theme involves linking the theme’s CSS file in your HTML document. This should be done using a <link> tag within the <head> section of your HTML. Ensure that the CSS file is loaded before the Highlight.js JavaScript code is executed. For example:

<link rel="stylesheet" href="path/to/your/theme.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>

Replace "path/to/your/theme.css" with the actual path to your theme’s CSS file. If using a CDN or a packaged version, you’ll need to locate the appropriate CSS file for your chosen theme and adjust the path accordingly. If using a theme packaged with Highlight.js, the path will be relative to the Highlight.js files.

Advanced Usage

Working with Pre-formatted Code

Highlight.js is primarily designed to work with code enclosed within <pre> and <code> tags. However, you might encounter situations where code is already pre-formatted, perhaps within a larger text block. In such cases, you’ll need to select the appropriate elements containing the code and then apply highlighting using hljs.highlightBlock(element) or hljs.highlightElement(element). This allows you to target and highlight specific code sections without relying solely on class-based detection.

Inline Code Highlighting

While Highlight.js excels at highlighting larger code blocks, it can also be used for highlighting smaller snippets of code within a paragraph of text. This is often achieved using the <code> tag. Ensure that the <code> tag contains the code you want to highlight, and that Highlight.js is properly initialized. If hljs.highlightAll() is used, inline code will also be automatically highlighted. If you are highlighting individual elements, remember to use hljs.highlightElement() or hljs.highlightBlock() on the relevant <code> tags.

Using with Frameworks (React, Vue, Angular, etc.)

Integrating Highlight.js with popular JavaScript frameworks like React, Vue, and Angular typically involves using the framework’s component model or lifecycle methods. You might create a custom component that wraps the Highlight.js functionality, allowing you to easily embed highlighted code within your application’s components. The specific implementation will vary depending on the chosen framework. Often, you’ll need to handle the lifecycle of the highlighting process, ensuring that the highlighting happens after the code has been rendered into the DOM. Look for community-contributed components or integrations if available, as they might streamline the process.

Programmatic Highlighting

Instead of relying on automatic highlighting via hljs.highlightAll(), you can programmatically highlight specific code blocks using hljs.highlightBlock(element) or hljs.highlightElement(element). This approach offers more control, especially when dealing with dynamically generated content. You can use these functions to highlight elements after they’ve been added to the DOM, making it ideal for situations where code is rendered asynchronously or updated frequently. It allows precise targeting and avoids unnecessary highlighting of non-code elements.

Customizing the Highlighting Process

Highlight.js offers several points for customization beyond themes. You can modify language definitions to account for specific syntax variations, adjust the auto-detection logic, and change the way tokens are classified. This requires a deeper understanding of the Highlight.js internal workings, particularly the language definition structure and highlighting process. For advanced customization, consider exploring the source code and the available configuration options to tailor the library to your particular requirements.

Performance Optimization

For large codebases or applications with many code blocks, performance optimization is important. Consider using techniques such as:

API Reference

highlight.js Object

The core hljs object (often accessed as hljs in your code) provides the main interface to Highlight.js. It’s not a constructor; instead, it contains various methods and properties for interacting with the library. Key properties and methods are described in the sections below. The hljs object is the primary entry point for all Highlight.js functionality. You’ll use its methods to register languages, highlight code, configure options and more.

highlight.registerLanguage() method

This method registers a new language definition with Highlight.js. It takes two arguments:

This function extends Highlight.js to support a language not already included by default. Once registered, the language can be used for highlighting. For example:

hljs.registerLanguage('mylang', {
  name: 'My Language',
  keywords: {
    keyword: ['foo', 'bar', 'baz']
  }
  // ... rest of the language definition
});

highlight.highlight() method

This method highlights a given code snippet and returns a highlighted HTML string. It takes two arguments:

This function highlights code directly; it doesn’t modify the DOM. The returned string can then be inserted into the HTML. For example:

let highlightedCode = hljs.highlight('javascript', `console.log("Hello");`);
document.getElementById('my-code').innerHTML = highlightedCode.value;

highlight.highlightBlock() method

This method highlights a code block within the DOM. It takes one argument:

This method directly modifies the DOM, highlighting the code within the given element. This is often preferred for highlighting elements already in the page, as it updates the element itself rather than returning a string.

let codeBlock = document.getElementById('my-code-block');
hljs.highlightBlock(codeBlock);

highlight.getLanguage() method

This method retrieves the language definition object for a given language name. It takes one argument:

It returns the language definition object if found; otherwise, it returns null. This can be helpful when you need to programmatically access the properties of a specific language definition.

highlight.fixMarkup() method

This method attempts to correct potential issues in the HTML markup of a code block before highlighting. This can be useful for handling code snippets that contain malformed HTML. It takes one argument:

The method returns the corrected HTML string. It is intended to assist in handling unusual or problematic input but shouldn’t be relied upon to repair severe markup issues.

Language Objects

Each registered language is represented internally by a language object. This object contains the definition and metadata for a specific language. You can access some information from this object, but it’s generally not necessary to directly interact with these objects in typical usage; they are mostly used internally by hljs methods. Accessing them directly is usually handled implicitly via hljs.highlight and similar functions.

Troubleshooting

Common Issues

Debugging Tips

Troubleshooting Language Issues

Performance Problems

Contributing

Setting up Development Environment

To contribute to Highlight.js, you’ll need to set up a development environment. This generally involves:

  1. Forking the repository: Create a fork of the official Highlight.js repository on GitHub.

  2. Cloning your fork: Clone your forked repository to your local machine using Git: git clone <your-fork-url>

  3. Installing dependencies: Navigate to the cloned directory and install the necessary Node.js packages using npm or yarn. The package.json file in the root directory will list the required dependencies. Typically, this involves running npm install or yarn install.

  4. Building the project: Highlight.js uses a build process to create the distributable files. The build process is typically defined in a script within package.json. This might involve commands like npm run build or similar. Familiarize yourself with the build process described in the project’s documentation.

  5. Running tests: Before making any changes, ensure the test suite is passing. The project likely contains instructions for running tests; it’s typically a command like npm test or yarn test.

Coding Style Guide

Adhere to the existing coding style used in the Highlight.js project. This will typically involve consistent indentation, naming conventions, and commenting practices. Review the existing codebase to familiarize yourself with the style guide. The project might have a .editorconfig file or other style guide documentation to aid you. Maintaining consistency ensures a clean and readable codebase.

Testing Procedures

Highlight.js has a comprehensive test suite. Before submitting any pull request, ensure your changes do not break existing functionality and that all tests pass. The testing process is usually described in the project’s documentation, possibly including instructions on running unit tests and potentially integration tests. Writing new tests for any new features or bug fixes is crucial to ensure that the changes work correctly and maintain the quality of the project.

Submitting Pull Requests

  1. Create a branch: Create a new branch for your changes using git checkout -b <your-branch-name>. Use descriptive branch names that reflect the purpose of your changes.

  2. Make your changes: Implement your changes, adhering to the coding style guide and ensuring all tests pass.

  3. Commit your changes: Commit your changes with clear and concise commit messages. Follow a consistent commit message style (e.g., using imperative mood for the subject line).

  4. Push your branch: Push your branch to your forked repository: git push origin <your-branch-name>.

  5. Create a pull request: On GitHub, create a pull request from your branch to the main branch of the original Highlight.js repository. Provide a clear description of your changes and address any comments or suggestions made by the maintainers. Ensure your pull request follows any guidelines outlined by the project maintainers.