highlight.js

repository·main·Indexed 12 days ago

https://github.com/highlightjs/highlight.js

A 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().

Tokens
17K
Snippets
52
Records
90
Agent score
97%

What's inside highlight.js

  1. License and copyright for AI-generated content

    main
    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.
  2. Understand Highlight.js attribute data types

    main

    When 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: true or false.
    • string: A JavaScript string.
    • number: A JavaScript number.
    • object: A JavaScript object { ... }.
    • array: A JavaScript array [ ... ].
  3. Switch between Safe Mode and Debug Mode

    main

    Highlight.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.
  4. Understand the concept of Modes in Highlight.js

    main

    In 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's scope (e.g., class="string") or the keyword group name (e.g., class="keyword").

  5. Understanding line number support in Highlight.js

    main

    Highlight.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:

    1. Use comments within the code itself to reference specific lines.
    2. Break larger code snippets into smaller, more manageable blocks.
    3. Fork the library or maintain a separate plugin to implement line number functionality.
  6. Prohibited AI usage

    main

    The 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 issue tasks end-to-end without learning the codebase. These issues are intended for human learning and growth.
  7. Understand the core principle of Highlight.js themes

    main

    Highlight.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.
  8. Understand how sub-scopes generate HTML classes

    main

    Highlight.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 (usually hljs-).

    For a scope named title.class.other, the generated HTML classes are:

    1. hljs-title (the top-level scope)
    2. class_ (the first sub-scope)
    3. 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;
    }
  9. Publish a new 3rd party language grammar

    main

    Follow these steps to finalize your language module:

    1. Develop the grammar as a standalone project.
    2. Request hosting (optional): If you want your grammar hosted under the highlightjs GitHub organization, open a new issue with the type **Issue: Request a new 3rd party grammar repository**.
    3. Submit a Pull Request: Once your module is ready, submit a PR to add your language to the SUPPORTED_LANGUAGES.md file in the main highlight.js repository.
  10. Import highlight.js in Node.js (ES6 Modules)

    main

    In 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';
  11. Define a Highlight.js theme

    main

    A 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., .attr is 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;
    }
  12. Use Subresource Integrity (SRI) with Highlight.js CDN

    main

    When 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 integrity attribute to your <script> tags. The value of the integrity attribute must match the specific digest for the version and file you are loading.

    Note: The digests used for the integrity attribute 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>