Syntax highlighting with language autodetection for over 190 programming languages and markup formats.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Global configuration options and operational mode controls for customizing highlighting behavior, error handling, and output formatting.
Configure global options that affect all highlighting operations.
/**
* Update global configuration options
* @param options - Partial configuration object
*/
function configure(options: Partial<HLJSOptions>): void;
interface HLJSOptions {
/** RegExp to identify elements to skip highlighting */
noHighlightRe: RegExp;
/** RegExp to detect language from CSS classes */
languageDetectRe: RegExp;
/** CSS class prefix for highlighted tokens */
classPrefix: string;
/** CSS selector for finding code elements */
cssSelector: string;
/** Array of allowed languages (null = all) */
languages?: string[] | null;
/** Internal emitter constructor */
__emitter: EmitterConstructor;
/** Whether to ignore unescaped HTML in code */
ignoreUnescapedHTML?: boolean;
/** Whether to throw errors for unescaped HTML */
throwUnescapedHTML?: boolean;
}Usage Examples:
import hljs from 'highlight.js';
// Basic configuration
hljs.configure({
classPrefix: 'syntax-',
cssSelector: 'pre code, .code-block'
});
// Security settings
hljs.configure({
ignoreUnescapedHTML: false,
throwUnescapedHTML: true
});
// Language restrictions
hljs.configure({
languages: ['javascript', 'python', 'html', 'css']
});
// Custom highlighting rules
hljs.configure({
noHighlightRe: /^(skip|no-syntax|plain)$/i,
languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i
});
// Advanced configuration for specific use cases
hljs.configure({
classPrefix: 'code-',
cssSelector: '.highlight code, pre.code-block',
languages: ['javascript', 'typescript', 'html', 'css', 'json'],
ignoreUnescapedHTML: true
});Enable debug mode for development and troubleshooting.
/**
* Enable debug mode - throws errors instead of catching them
* Useful for development and debugging language definitions
*/
function debugMode(): void;Usage Examples:
// Enable debug mode for development
if (process.env.NODE_ENV === 'development') {
hljs.debugMode();
}
// Debug custom language definitions
hljs.debugMode();
hljs.registerLanguage('test-lang', function(hljs) {
return {
// This will throw detailed errors if there are issues
contains: [
{
begin: /invalid-regex-[/, // This would throw in debug mode
end: '$'
}
]
};
});
// Catch and log errors in debug mode
try {
hljs.highlight('test code', { language: 'test-lang' });
} catch (error) {
console.error('Highlighting error:', error);
console.error('Stack trace:', error.stack);
}Enable safe mode for production environments.
/**
* Enable safe mode - catches and logs errors, tries to continue
* Default mode for production use
*/
function safeMode(): void;Usage Examples:
// Ensure safe mode for production
if (process.env.NODE_ENV === 'production') {
hljs.safeMode();
}
// Safe mode with error monitoring
hljs.safeMode();
// Override error handling if needed
const originalConsoleError = console.error;
console.error = function(...args) {
// Log to monitoring service
if (args[0] && args[0].includes('highlight.js')) {
sendToMonitoring('hljs-error', args);
}
originalConsoleError.apply(console, args);
};Create a new isolated highlighter instance with separate configuration.
/**
* Create a new isolated highlight.js instance
* Useful for different configurations or avoiding global state
* @returns New HLJSApi instance with default settings
*/
function newInstance(): HLJSApi;Usage Examples:
// Create isolated instance
const customHljs = hljs.newInstance();
// Configure separately from global instance
customHljs.configure({
classPrefix: 'custom-',
languages: ['javascript', 'html']
});
hljs.configure({
classPrefix: 'main-',
languages: ['python', 'sql']
});
// Use different instances for different purposes
const webHighlighter = hljs.newInstance();
webHighlighter.configure({
languages: ['html', 'css', 'javascript', 'typescript']
});
const serverHighlighter = hljs.newInstance();
serverHighlighter.configure({
languages: ['python', 'java', 'go', 'rust', 'sql']
});
// Register different languages per instance
webHighlighter.registerLanguage('vue', vueLanguageDefinition);
serverHighlighter.registerLanguage('dockerfile', dockerLanguageDefinition);
// Use instances independently
const webResult = webHighlighter.highlight('const x = 1;', { language: 'javascript' });
const serverResult = serverHighlighter.highlight('print("hello")', { language: 'python' });// Class prefix configuration
hljs.configure({
classPrefix: 'hljs-' // Default
});
// Results in classes like: hljs-keyword, hljs-string, hljs-comment
// Custom prefix
hljs.configure({
classPrefix: 'syntax-'
});
// Results in classes like: syntax-keyword, syntax-string, syntax-comment
// No prefix
hljs.configure({
classPrefix: ''
});
// Results in classes like: keyword, string, comment// Default selector
hljs.configure({
cssSelector: 'pre code'
});
// Multiple selectors
hljs.configure({
cssSelector: 'pre code, .code-block, .highlight code'
});
// Attribute-based selection
hljs.configure({
cssSelector: '[data-highlight="true"]'
});// Default language detection regex
hljs.configure({
languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i
});
// This matches:
// - class="language-javascript"
// - class="lang-python"
// - class="language-html css"
// Custom detection pattern
hljs.configure({
languageDetectRe: /\bcode-([\w-]+)\b/i
});
// This would match: class="code-javascript"// Default skip pattern
hljs.configure({
noHighlightRe: /^(no-?highlight)$/i
});
// This skips elements with classes:
// - "nohighlight"
// - "no-highlight"
// - "NOHIGHLIGHT" (case insensitive)
// Custom skip patterns
hljs.configure({
noHighlightRe: /^(skip|plain|raw|no-syntax)$/i
});// Allow all languages (default)
hljs.configure({
languages: null
});
// Restrict to specific languages
hljs.configure({
languages: ['javascript', 'python', 'html', 'css']
});
// Web development focus
hljs.configure({
languages: [
'html', 'css', 'scss', 'less',
'javascript', 'typescript', 'jsx',
'json', 'xml', 'markdown'
]
});
// Backend development focus
hljs.configure({
languages: [
'python', 'java', 'go', 'rust', 'csharp',
'sql', 'dockerfile', 'yaml', 'ini'
]
});// Strict security (recommended for user content)
hljs.configure({
ignoreUnescapedHTML: false,
throwUnescapedHTML: true
});
// Lenient security (for trusted content)
hljs.configure({
ignoreUnescapedHTML: true,
throwUnescapedHTML: false
});
// Default security
hljs.configure({
ignoreUnescapedHTML: false,
throwUnescapedHTML: false
});Highlight.js operates in different modes that affect error handling:
Mode Switching Examples:
// Environment-based mode switching
if (process.env.NODE_ENV === 'development') {
hljs.debugMode();
console.log('Highlight.js in debug mode');
} else {
hljs.safeMode();
console.log('Highlight.js in safe mode');
}
// Feature flag based switching
const FEATURES = {
debugHighlighting: false,
strictErrorHandling: true
};
if (FEATURES.debugHighlighting) {
hljs.debugMode();
} else {
hljs.safeMode();
}
// Runtime mode switching based on content source
function highlightUserContent(code, language) {
const currentMode = hljs.debugMode; // Save current mode
hljs.safeMode(); // Use safe mode for user content
try {
return hljs.highlight(code, { language, ignoreIllegals: true });
} finally {
if (currentMode) hljs.debugMode(); // Restore previous mode
}
}/** Library version string */
const versionString: string; // "11.11.1"Usage Example:
console.log('Highlight.js version:', hljs.versionString);
// Version-dependent feature detection
const [major, minor, patch] = hljs.versionString.split('.').map(Number);
if (major >= 11) {
console.log('Using modern highlight.js API');
// Use current API
} else {
console.log('Using legacy highlight.js API');
// Fall back to legacy API
}