or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdcore-highlighting.mdindex.mdlanguage-management.mdmodes-patterns.mdplugin-system.mdutilities.md
tile.json

core-highlighting.mddocs/

Core Highlighting

Core highlighting functionality providing manual and automatic code highlighting with language detection and customizable options. These are the primary functions for highlighting code in both browser and server environments.

Capabilities

Highlight Function

Primary highlighting function with support for both old and new API styles. Highlights code using a specified language with optional error handling.

/**
 * Highlights code using a specified language
 * 
 * Old API: highlight(languageName, code, ignoreIllegals, continuation)
 * New API: highlight(code, {language, ignoreIllegals})
 * 
 * @param codeOrLanguageName - Code to highlight (new API) or language name (old API)
 * @param optionsOrCode - Options object (new API) or code string (old API)
 * @param ignoreIllegals - Whether to ignore illegal syntax (old API only)
 * @param continuation - Continuation state for multi-part highlighting (old API only)
 * @returns HighlightResult with highlighted HTML and metadata
 */
function highlight(
  codeOrLanguageName: string, 
  optionsOrCode: string | HighlightOptions, 
  ignoreIllegals?: boolean, 
  continuation?: Mode
): HighlightResult;

interface HighlightOptions {
  /** Language name to use for highlighting */
  language: string;
  /** Whether to ignore illegal syntax and continue highlighting */
  ignoreIllegals?: boolean;
}

interface HighlightResult {
  /** Relevance score for the highlighting result */
  relevance: number;
  /** Highlighted HTML string */
  value: string;
  /** Detected or specified language name */
  language?: string;
  /** Internal emitter used for highlighting */
  emitter: Emitter;
  /** Whether illegal syntax was encountered */
  illegal: boolean;
  /** Top-level language or compiled mode */
  top?: Language | CompiledMode;
  /** Information about illegal syntax encountered */
  illegalBy?: illegalData;
  /** Processed code so far (internal) */
  sofar?: string;
  /** Error information if highlighting failed */
  errorRaised?: Error;
  /** Second best language match for auto-detection */
  second_best?: Omit<HighlightResult, 'second_best'>;
  /** Original code string */
  code?: string;
}

Usage Examples:

import hljs from "highlight.js";

// New API - recommended
const result = hljs.highlight('console.log("Hello");', {language: 'javascript'});
console.log(result.value); // '<span class="hljs-built_in">console</span>...'
console.log(result.relevance); // Relevance score

// New API with ignoreIllegals
const result2 = hljs.highlight('float # invalid java', {
  language: 'java', 
  ignoreIllegals: true
});

// Old API - still supported
const result3 = hljs.highlight('javascript', 'console.log("Hello");');
const result4 = hljs.highlight('java', 'float # invalid', true); // ignore illegals

Highlight Auto

Automatically detects the programming language and highlights code. Uses statistical analysis of syntax patterns to determine the most likely language.

/**
 * Automatically detects language and highlights code
 * @param code - Code string to analyze and highlight
 * @param languageSubset - Optional array of language names to consider
 * @returns AutoHighlightResult with detected language and highlighted HTML
 */
function highlightAuto(code: string, languageSubset?: string[]): AutoHighlightResult;

interface AutoHighlightResult extends HighlightResult {
  /** Second best language match for comparison */
  second_best?: Omit<HighlightResult, 'second_best'>;
}

Usage Examples:

import hljs from "highlight.js";

// Basic auto-detection
const result = hljs.highlightAuto('def hello():\n    print("Hello")');
console.log(result.language); // 'python'
console.log(result.relevance); // Confidence score
console.log(result.value); // Highlighted HTML

// Restrict to subset of languages for better performance
const webResult = hljs.highlightAuto('<div>Hello</div>', ['html', 'xml']);
console.log(webResult.language); // 'html'

// Check second-best match
if (result.second_best) {
  console.log(`Second choice: ${result.second_best.language}`);
}

Highlight All

Automatically finds and highlights all code blocks on the current page. Scans for

<pre><code>
elements and applies highlighting based on class names or auto-detection.

/**
 * Highlights all code blocks on the page automatically
 * Finds <pre><code> elements and highlights them based on class names or auto-detection
 */
function highlightAll(): void;

Usage Examples:

import hljs from "highlight.js";

// Highlight all code blocks after page load
document.addEventListener('DOMContentLoaded', () => {
  hljs.highlightAll();
});

// Manual call after dynamic content is added
document.getElementById('load-code').addEventListener('click', () => {
  // ... load dynamic content with code blocks ...
  hljs.highlightAll(); // Highlight newly added blocks
});

HTML Structure:

<!-- Language specified in class -->
<pre><code class="language-javascript">
console.log("This will be highlighted as JavaScript");
</code></pre>

<!-- Auto-detection -->
<pre><code>
def hello():
    print("This will be auto-detected as Python")
</code></pre>

<!-- Disable highlighting -->
<pre><code class="nohighlight">
This code will not be highlighted
</code></pre>

<!-- Plain text styling -->
<pre><code class="plaintext">
This will be styled as code but not highlighted
</code></pre>

Highlight Element

Highlights a specific HTML element containing code. Provides fine-grained control over individual code blocks.

/**
 * Highlights a specific HTML element containing code
 * @param element - HTMLElement (typically <code>) to highlight
 */
function highlightElement(element: HTMLElement): void;

Usage Examples:

import hljs from "highlight.js";

// Highlight specific elements
document.querySelectorAll('pre code').forEach((block) => {
  hljs.highlightElement(block);
});

// Highlight dynamically created elements
const codeBlock = document.createElement('code');
codeBlock.textContent = 'console.log("Hello");';
codeBlock.className = 'language-javascript';
document.body.appendChild(codeBlock);
hljs.highlightElement(codeBlock);

// Manual highlighting with error handling
try {
  const element = document.querySelector('#my-code');
  if (element) {
    hljs.highlightElement(element);
  }
} catch (error) {
  console.error('Highlighting failed:', error);
}

Highlight Block (Deprecated)

Legacy function for highlighting individual code blocks. Deprecated in v10.7.0 in favor of

highlightElement
.

Note: This function is deprecated as of v10.7.0 and will be removed in v12.0. Use

highlightElement()
instead.

/**
 * Legacy function for highlighting individual code blocks
 * @deprecated Since v10.7.0, will be removed in v12.0. Use highlightElement() instead.
 * @param element - HTMLElement to highlight
 */
function highlightBlock(element: HTMLElement): void;

Migration Example:

// Old approach (deprecated)
hljs.highlightBlock(codeElement);

// New approach (recommended)
hljs.highlightElement(codeElement);

Manual Initialization

Functions for manual control over when highlighting is initialized, useful for custom loading scenarios.

/**
 * Manually initializes highlighting (alternative to auto-init)
 * Sets up highlighting without automatically processing existing code blocks
 */
function initHighlighting(): void;

/**
 * Sets up highlighting to run automatically when DOM is loaded
 * Equivalent to calling highlightAll() on DOMContentLoaded
 */
function initHighlightingOnLoad(): void;

Usage Examples:

import hljs from "highlight.js";

// Manual initialization for custom control
hljs.initHighlighting();
// ... your custom logic ...
hljs.highlightAll();

// Auto-initialization (traditional approach)
hljs.initHighlightingOnLoad(); // Will highlight when DOM loads

// Custom initialization with configuration
hljs.configure({ classPrefix: 'my-hljs-' });
hljs.initHighlightingOnLoad();

Browser Integration

CSS Themes

Highlight.js requires CSS for styling. Import themes as needed:

// With build tools
import 'highlight.js/styles/default.css';
import 'highlight.js/styles/github.css';
import 'highlight.js/styles/monokai.css';
<!-- Direct HTML import -->
<link rel="stylesheet" href="/path/to/styles/default.css">

Web Workers

For large code blocks, use Web Workers to avoid blocking the main thread:

// main.js
const worker = new Worker('highlight-worker.js');
worker.postMessage({ code: largeCodeString, language: 'javascript' });
worker.onmessage = (event) => {
  document.getElementById('result').innerHTML = event.data;
};

// highlight-worker.js
importScripts('/path/to/highlight.min.js');
onmessage = (event) => {
  const result = self.hljs.highlight(event.data.code, {
    language: event.data.language
  });
  postMessage(result.value);
};

Error Handling

import hljs from "highlight.js";

// Handle illegal syntax gracefully
const result = hljs.highlight('float # invalid java syntax', {
  language: 'java',
  ignoreIllegals: true
});

if (result.illegal) {
  console.warn('Illegal syntax found but ignored');
}

// Auto-detection with fallback
const autoResult = hljs.highlightAuto(unknownCode);
if (autoResult.relevance < 5) {
  console.warn('Low confidence in language detection');
  // Maybe try with specific language or show as plain text
}