CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-prismjs

Lightweight, robust, elegant syntax highlighting library with support for 280+ languages and multiple themes

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-highlighting.mddocs/

Core Highlighting

The core highlighting functionality provides both automatic and manual syntax highlighting capabilities. These functions form the primary API for highlighting code in web pages and applications.

Capabilities

Automatic Highlighting

highlightAll

Automatically highlights all code elements on the page that have language-specific CSS classes.

/**
 * Highlight all code elements on the page automatically
 * @param {boolean} [async=false] - Whether to use Web Workers for highlighting
 * @param {function} [callback] - Callback function invoked after each element is highlighted
 */
Prism.highlightAll(async, callback);

Usage Examples:

// Basic automatic highlighting
Prism.highlightAll();

// Asynchronous highlighting with callback
Prism.highlightAll(true, function(element) {
    console.log('Highlighted:', element);
});

HTML Setup:

<pre><code class="language-javascript">
const message = "Hello, World!";
console.log(message);
</code></pre>

<script>
// Call after DOM is loaded
Prism.highlightAll();
</script>

highlightAllUnder

Highlights all code elements under a specific container element.

/**
 * Highlight all descendants of container that have language-* classes
 * @param {Element} container - Root element to search under
 * @param {boolean} [async=false] - Whether to use Web Workers
 * @param {function} [callback] - Callback function invoked after each element
 */
Prism.highlightAllUnder(container, async, callback);

Usage Examples:

// Highlight only within a specific container
const codeContainer = document.getElementById('code-examples');
Prism.highlightAllUnder(codeContainer);

// With async and callback
Prism.highlightAllUnder(container, true, (element) => {
    element.classList.add('highlighted');
});

Element Highlighting

highlightElement

Highlights code inside a single element with fine-grained control.

/**
 * Highlight code inside a single element
 * @param {Element} element - Element containing code with language-* class
 * @param {boolean} [async=false] - Whether to use Web Workers for highlighting
 * @param {function} [callback] - Optional callback function after highlighting
 */
Prism.highlightElement(element, async, callback);

Usage Examples:

// Highlight single element
const codeBlock = document.querySelector('code.language-python');
Prism.highlightElement(codeBlock);

// With callback for post-processing
Prism.highlightElement(codeBlock, false, function(element) {
    // Add line numbers or other enhancements
    console.log('Element highlighted:', element);
});

// Asynchronous highlighting
Prism.highlightElement(codeBlock, true);

Requirements:

  • Element must have language-* class (e.g., language-javascript)
  • Element should contain text content to highlight
  • Language grammar must be loaded

Manual String Highlighting

highlight

Low-level function for highlighting code strings directly without DOM manipulation.

/**
 * Highlight a code string using specified grammar
 * @param {string} text - Code string to highlight
 * @param {object} grammar - Language grammar object from Prism.languages
 * @param {string} language - Language identifier for CSS classes
 * @returns {string} HTML string with syntax highlighting markup
 */
Prism.highlight(text, grammar, language);

Usage Examples:

// Basic string highlighting
const code = 'const greeting = "Hello, World!";';
const grammar = Prism.languages.javascript;
const highlighted = Prism.highlight(code, grammar, 'javascript');
console.log(highlighted);
// Output: '<span class="token keyword">const</span> greeting <span class="token operator">=</span> <span class="token string">"Hello, World!"</span><span class="token punctuation">;</span>'

// Dynamic highlighting with different languages
function highlightCode(code, lang) {
    if (Prism.languages[lang]) {
        return Prism.highlight(code, Prism.languages[lang], lang);
    } else {
        throw new Error(`Language "${lang}" not loaded`);
    }
}

const pythonCode = 'print("Hello, Python!")';
const highlighted = highlightCode(pythonCode, 'python');
document.getElementById('output').innerHTML = highlighted;

tokenize

Core tokenization function that parses code into structured token objects.

/**
 * Tokenize code string into structured token stream
 * @param {string} text - Code string to tokenize
 * @param {object} grammar - Language grammar object from Prism.languages
 * @returns {Array} Array of strings and Token objects (TokenStream)
 */
Prism.tokenize(text, grammar);

Usage Examples:

// Basic tokenization
const code = 'let count = 42;';
const tokens = Prism.tokenize(code, Prism.languages.javascript);

// Analyze tokens
tokens.forEach(token => {
    if (token instanceof Prism.Token) {
        console.log(`Token: ${token.type} = "${token.content}"`);
    } else {
        console.log(`Text: "${token}"`);
    }
});

// Advanced token processing
function extractIdentifiers(code, language) {
    const tokens = Prism.tokenize(code, Prism.languages[language]);
    const identifiers = [];
    
    function processTokens(tokens) {
        tokens.forEach(token => {
            if (token instanceof Prism.Token) {
                if (token.type === 'function' || token.type === 'variable') {
                    identifiers.push(token.content);
                }
                if (Array.isArray(token.content)) {
                    processTokens(token.content);
                }
            }
        });
    }
    
    processTokens(tokens);
    return identifiers;
}

Hooks Integration

The highlighting process integrates with the hook system to allow plugins to modify behavior:

// Available hooks during highlighting
Prism.hooks.add('before-highlightall', function(env) {
    // Modify elements before highlighting starts
    console.log('Starting to highlight:', env.selector);
});

Prism.hooks.add('before-sanity-check', function(env) {
    // Modify element/code before processing
    console.log('Processing element:', env.element);
});

Prism.hooks.add('before-highlight', function(env) {
    // Modify code/grammar before highlighting
    env.code = env.code.trim(); // Remove whitespace
});

Prism.hooks.add('after-highlight', function(env) {
    // Modify highlighted HTML
    console.log('Highlighted code:', env.highlightedCode);
});

Prism.hooks.add('complete', function(env) {
    // Final processing after DOM insertion
    console.log('Highlighting complete:', env.element);
});

Error Handling

// Check if language is available
function safeHighlight(code, language) {
    if (!Prism.languages[language]) {
        console.warn(`Language "${language}" not loaded`);
        return code; // Return original code
    }
    
    try {
        return Prism.highlight(code, Prism.languages[language], language);
    } catch (error) {
        console.error('Highlighting failed:', error);
        return code; // Fallback to original
    }
}

// Error handling with element highlighting
function highlightWithFallback(element) {
    try {
        Prism.highlightElement(element);
    } catch (error) {
        console.error('Failed to highlight element:', error);
        // Element remains unhighlighted but functional
    }
}

Web Worker Support

PrismJS supports asynchronous highlighting using Web Workers to prevent blocking the main thread:

// Enable async highlighting
Prism.highlightAll(true);

// Web Workers require all language definitions in main prism.js
// Components loaded separately won't be available in workers

// Check worker support
if (typeof Worker !== 'undefined') {
    console.log('Web Workers supported');
} else {
    console.log('Falling back to synchronous highlighting');
}

Performance Considerations

// For large code blocks, use async highlighting
const largeCodeBlock = document.querySelector('.large-code');
if (largeCodeBlock.textContent.length > 10000) {
    Prism.highlightElement(largeCodeBlock, true);
}

// Batch highlighting for better performance
const codeBlocks = document.querySelectorAll('code[class*="language-"]');
if (codeBlocks.length > 50) {
    // Use async for many elements
    Prism.highlightAll(true);
} else {
    // Sync is fine for few elements
    Prism.highlightAll(false);
}

Install with Tessl CLI

npx tessl i tessl/npm-prismjs

docs

core-highlighting.md

index.md

language-system.md

plugin-system.md

token-system.md

utilities.md

tile.json