Highlight.js can be installed via several methods, depending on your project’s needs and preferences.
<script>
tag in your HTML <head>
:<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
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)
.
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.
The method for including Highlight.js depends on your chosen installation method.
CDN: Simply include the <link>
and <script>
tags as shown in the “First Example.”
npm/yarn: Require the library in your JavaScript code (e.g., using import
or require
depending on your module system), then use the methods described in the “Basic Usage” section. Remember to also include the CSS stylesheet. For example (using ES modules):
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
.registerLanguage('javascript', javascript);
hljs.highlightAll(); hljs
css
and js
folders (or equivalent), and then link to them in your HTML using <link>
and <script>
tags, similarly to the CDN approach. Remember to adjust file paths accordingly.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.
The highlighting process in Highlight.js generally follows these steps:
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).
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.).
Tokenization: Each segment is assigned a token type, indicating its semantic meaning within the language.
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.
Rendering: The highlighted code is then rendered in the browser.
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.
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.
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.
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 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.
A Highlight.js language definition is a JavaScript object with several key properties. The exact structure can be complex, but typically includes:
name
: A string specifying the language name (e.g., ‘JavaScript’).aliases
: An array of alternative names or abbreviations for the language.keywords
: An object or array defining keywords of the language. This often includes sub-categories (e.g., keyword
, built_in
, literal
).contains
: An array defining the various “modes” or lexemes of the language. These are rules to match different parts of the code (e.g., comments, strings, numbers). Each mode is typically an object with properties like className
(the CSS class to apply) and begin
and end
(regular expressions defining the start and end of the mode).illegal
: A regular expression defining illegal characters or sequences that will result in parsing failure for the language.vs
: (Optional) Specific configuration for Visual Studio Code-style highlighting.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.
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.
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 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.
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 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.
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.
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.
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.
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.
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.
For large codebases or applications with many code blocks, performance optimization is important. Consider using techniques such as:
hljs.highlightAll()
for large numbers of elements. Instead, highlight individual blocks as needed using hljs.highlightBlock()
or hljs.highlightElement()
.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.
This method registers a new language definition with Highlight.js. It takes two arguments:
languageName
: A string representing the unique name of the language (e.g., ‘javascript’, ‘python’).languageDefinition
: An object containing the language definition (see “Language Definition Structure” in the Language Support section).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:
.registerLanguage('mylang', {
hljsname: 'My Language',
keywords: {
keyword: ['foo', 'bar', 'baz']
}// ... rest of the language definition
; })
This method highlights a given code snippet and returns a highlighted HTML string. It takes two arguments:
code
: The code snippet to highlight (as a string).language
: The name of the language to use for highlighting (optional; if omitted, auto-detection is attempted).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;
This method highlights a code block within the DOM. It takes one argument:
block
: A DOM element representing the <pre>
or <code>
block containing the code.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');
.highlightBlock(codeBlock); hljs
This method retrieves the language definition object for a given language name. It takes one argument:
languageName
: A string representing the language name.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.
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:
html
: The HTML string containing the code.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.
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.
No highlighting: Ensure that both the CSS and JavaScript files for Highlight.js are correctly included in your HTML, and that the JavaScript is loaded after the CSS. Double-check file paths and ensure there are no typos in the <link>
and <script>
tags. Also verify that hljs.highlightAll()
(or a similar highlighting method) is called after the Highlight.js files have loaded and the code is present in the DOM.
Incorrect language highlighting: Verify that the language-XXX
class is correctly assigned to the <pre>
or <code>
tags, using the correct language name. If using auto-detection, ensure the code snippet is sufficiently unambiguous to allow accurate detection. Review the supported languages and ensure the language you’re using is included in your build.
CSS conflicts: If the highlighting styles are not applied correctly, there might be a conflict with other CSS styles in your project. Use your browser’s developer tools to inspect the highlighted code elements and identify potential CSS conflicts that override the Highlight.js styles.
JavaScript errors: Check your browser’s developer console (usually accessed by pressing F12) for any JavaScript errors that might be preventing Highlight.js from working correctly. These errors often pinpoint the source of the problem.
Inspect elements: Use your browser’s developer tools to inspect the HTML structure of the code blocks you are trying to highlight. This will allow you to verify if the necessary classes are added correctly and to check the CSS styles applied to those classes.
Simplify the code: If you’re experiencing issues with a complex code snippet, try simplifying it to a smaller, minimal example to see if the problem persists. This can help in isolating the source of the problem.
Check the console: Regularly check your browser’s console for any errors or warnings that might be related to Highlight.js. Error messages can provide valuable clues to diagnose issues.
Test with a minimal setup: Create a minimal HTML file that includes only the necessary Highlight.js files and a small code snippet. If the highlighting works in this simplified environment, the problem lies in the interaction with other parts of your project.
Language not supported: Ensure that the language you’re attempting to highlight is actually supported by the version of Highlight.js you’re using. Check the list of supported languages. If it’s not supported, you’ll have to add support yourself by creating a language definition file.
Incorrect language definition: If you are using a custom language definition, double-check the syntax and ensure it adheres to the correct structure and uses valid regular expressions.
Missing language file: If you’ve included a custom language file, ensure it’s correctly loaded and registered using hljs.registerLanguage()
. Verify that the file is correctly included using the correct path.
Large code blocks: Highlighting very large code blocks can impact performance. Consider using lazy loading or highlighting on demand to improve performance, especially for blocks that are not initially visible.
Many code blocks: If your application includes many code blocks, highlighting all of them at once might slow things down. Consider using hljs.highlightBlock()
or hljs.highlightElement()
on individual blocks as needed instead of hljs.highlightAll()
.
Inefficient language definitions: Poorly written language definitions can significantly affect performance. If you’ve created a custom language definition, review its efficiency; overly complex regular expressions can be particularly problematic. Avoid unnecessary backtracking or redundant patterns.
Unminified files: Always use the minified versions of the Highlight.js files and any included language definitions for better performance in a production environment.
To contribute to Highlight.js, you’ll need to set up a development environment. This generally involves:
Forking the repository: Create a fork of the official Highlight.js repository on GitHub.
Cloning your fork: Clone your forked repository to your local machine using Git: git clone <your-fork-url>
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
.
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.
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
.
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.
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.
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.
Make your changes: Implement your changes, adhering to the coding style guide and ensuring all tests pass.
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).
Push your branch: Push your branch to your forked repository: git push origin <your-branch-name>
.
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.