highlight.js
repository·main·Indexed 12 days ago
https://github.com/highlightjs/highlight.jsA JavaScript syntax highlighter with automatic language detection that works in both the browser and on the server. Version 11.12.0 supports a wide variety of markup and languages, offering flexible import options including full library, common subsets, or core-only builds for optimized bundle sizes. Key APIs include hljs.highlightAll(), hljs.highlightAuto(), and hljs.highlightElement().
What's inside highlight.js
- Contributors are responsible for ensuring they have the legal right to contribute all material under the project's license. Using an AI tool to regenerate copyrighted material does not grant a right to relicense it. Do not submit content that violates copyright or licensing restrictions.
Understand Highlight.js attribute data types
mainWhen defining grammars or modes, Highlight.js uses specific data types for attribute values. Understanding these is critical for correct grammar definition:
mode: A valid Highlight.js Mode definition.scope: A grammar scope string (e.g.,title.class.inherited).regexp: A JavaScript regexp literal (recommended) or a string representing a regexp (requires careful escaping).boolean:trueorfalse.string: A JavaScript string.number: A JavaScript number.object: A JavaScript object{ ... }.array: A JavaScript array[ ... ].
Switch between Safe Mode and Debug Mode
mainHighlight.js operates in two modes:
- Safe Mode (Default): Provides a reliable experience for production. If a language highlighting fails, it simply renders as plaintext without breaking other languages.
- Debug Mode: Enabled via
hljs.debugMode(). This is intended for development and testing. In this mode, if a language highlighting error occurs, it will throw a JavaScript error and stop all highlighting, making it easier to catch bugs in language definitions.
Understand the concept of Modes in Highlight.js
mainIn Highlight.js, a language is defined as a tree of modes. A mode represents a specific part of the code with its own parsing rules (e.g., a string, a comment, or a keyword block).
Each mode consists of:
- A starting condition (
begin) - An ending condition (
end) - A list of sub-modes (
contains) - Lexing rules and keywords
The parser identifies these modes and wraps them in HTML
<span>elements. The class name of the span is determined by the mode'sscope(e.g.,class="string") or the keyword group name (e.g.,class="keyword").- A starting condition (
Understanding line number support in Highlight.js
mainHighlight.js does not include native support for line numbers as part of its core library. This design choice prioritizes simplicity and avoids visual bloat in highlighted snippets.
If you require line numbers, the library's maintainers suggest that you either:
- Use comments within the code itself to reference specific lines.
- Break larger code snippets into smaller, more manageable blocks.
- Fork the library or maintain a separate plugin to implement line number functionality.
Prohibited AI usage
mainThe following uses of AI are strictly prohibited:
- Unattended bots: Using bots to open or update PRs, issues, or review comments without a human approving every individual action.
- Automated 'good first issue' farming: Using AI to claim and complete
good first issuetasks end-to-end without learning the codebase. These issues are intended for human learning and growth.
Understand the core principle of Highlight.js themes
mainHighlight.js themes are language agnostic. Instead of providing a massive set of classes for every possible language feature, Highlight.js uses a limited set of classes designed to work across many different languages.
Because of this design:
- Themes tend to be minimalistic.
- It is not always possible to exactly replicate the look of themes from other highlighting engines that use more granular or language-specific class sets.
Understand how sub-scopes generate HTML classes
mainHighlight.js uses dot notation (e.g.,
title.class.other) to represent sub-scopes. When these are rendered in HTML, they generate multiple computed class names. The depth of nesting determines the number of underscores appended to the sub-scope names. The top-level scope always receives the configured prefix (usuallyhljs-).For a scope named
title.class.other, the generated HTML classes are:hljs-title(the top-level scope)class_(the first sub-scope)other__(the second sub-scope)
Example HTML Output:
<span class="hljs-title class_ other__">Render</span>Example CSS Targeting: To target this specific nested scope, use:
.hljs-title.class_.other__ { color: blue; }/* If the scope is title.class.other */ <span class="hljs-title class_ other__">Render</span> /* Target it in CSS */ .hljs-title.class_.other__ { color: blue; }Publish a new 3rd party language grammar
mainFollow these steps to finalize your language module:
- Develop the grammar as a standalone project.
- Request hosting (optional): If you want your grammar hosted under the
highlightjsGitHub organization, open a new issue with the type**Issue: Request a new 3rd party grammar repository**. - Submit a Pull Request: Once your module is ready, submit a PR to add your language to the
SUPPORTED_LANGUAGES.mdfile in the mainhighlight.jsrepository.
Import highlight.js in Node.js (ES6 Modules)
mainIn Node.js environments using
import, you can optimize your bundle size by importing only the core library and registering specific languages. You can also import CSS themes directly if your build tool supports CSS imports.// Efficient: Import core and register specific languages import hljs from 'highlight.js/lib/core'; import javascript from 'highlight.js/lib/languages/javascript'; hljs.registerLanguage('javascript', javascript); // Full library: Registers all languages import hljs from 'highlight.js'; // Import theme (if build tool supports CSS imports) import 'highlight.js/styles/github.css';Define a Highlight.js theme
mainA theme is a single CSS file that defines styles for the scopes (CSS classes) used by the highlighter.
Guidelines:
- Focus on styling the core/common set of classes. You can choose to exclude certain classes (e.g.,
.attris often left unstyled). - You do not need a unique style for every single class; you can group multiple classes together to simplify your CSS.
- Important: Always style
.subst. This class is used for parsed sections within strings and should almost always be reset to the default text color to avoid unexpected highlighting inside strings.
Example of grouping classes:
.hljs-string, .hljs-section, .hljs-selector-class, .hljs-template-variable, .hljs-deletion { color: #800; }Example of styling
.subst:.hljs, .hljs-subst { color: black; }- Focus on styling the core/common set of classes. You can choose to exclude certain classes (e.g.,
Use Subresource Integrity (SRI) with Highlight.js CDN
mainWhen loading Highlight.js via a CDN, you can use Subresource Integrity (SRI) to ensure the files have not been tampered with. To implement this, add the
integrityattribute to your<script>tags. The value of theintegrityattribute must match the specific digest for the version and file you are loading.Note: The digests used for the
integrityattribute are provided in the project's digest list.<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/<!-- $VERSION -->/highlight.min.js" integrity="<!-- $MIN_JS_DIGEST -->"></script> <!-- including any other grammars you might need to load --> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/<!-- $VERSION -->/languages/go.min.js" integrity="<!-- $GO_SHA -->"></script>