CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-highlightjs--cdn-assets

Pre-compiled CDN assets for highlight.js syntax highlighting with language autodetection and theme support.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

language-management.mddocs/

Language Management

Functions for managing available languages, registering custom languages, working with language aliases, and controlling language detection behavior.

Capabilities

registerLanguage()

Registers a new language definition for use with highlighting functions.

/**
 * Registers a new language definition
 * @param languageName - Name to register the language under
 * @param language - Language definition function
 */
function registerLanguage(languageName: string, language: LanguageFn): void;

/**
 * Language definition function that returns a Language object
 * @param hljs - The hljs API object with utilities
 * @returns Language definition with syntax rules
 */
type LanguageFn = (hljs: HLJSApi) => Language;

interface Language extends LanguageDetail, Partial<Mode> {
  /** Human-readable name of the language */
  name?: string;
  /** Whether to use Unicode-aware regex patterns */
  unicodeRegex?: boolean;
  /** Array of alternative names for the language */
  aliases?: string[];
  /** Whether to disable automatic language detection */
  disableAutodetect?: boolean;
  /** Array of syntax mode definitions */
  contains: Mode[];
  /** Whether language keywords are case-insensitive */
  case_insensitive?: boolean;
  /** Keywords definition - string, array, or object mapping */
  keywords?: string | string[] | Record<string, string | string[] | RegExp>;
  /** Whether the language has been compiled */
  isCompiled?: boolean;
  /** Exported utilities from the language */
  exports?: any;
  /** Mapping of CSS class name aliases */
  classNameAliases?: Record<string, string>;
}

Usage Examples:

import hljs from '@highlightjs/cdn-assets/es/highlight.js';

// Register a language from a CDN asset file
import pythonLang from '@highlightjs/cdn-assets/es/languages/python.min.js';
hljs.registerLanguage('python', pythonLang);

// Define a simple custom language
hljs.registerLanguage('mylang', function(hljs) {
  return {
    name: 'MyLanguage',
    aliases: ['my', 'custom'],
    keywords: 'if else while for function',
    contains: [
      hljs.QUOTE_STRING_MODE,
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_NUMBER_MODE
    ]
  };
});

// Use the registered language
const result = hljs.highlight('if x > 0 then "positive"', { language: 'mylang' });

unregisterLanguage()

Removes a previously registered language definition.

/**
 * Unregisters a language definition
 * @param languageName - Name of the language to remove
 */
function unregisterLanguage(languageName: string): void;

Usage Examples:

// Unregister a language
hljs.unregisterLanguage('python');

// Verify it's gone
console.log(hljs.getLanguage('python')); // undefined

// Unregister a custom language
hljs.unregisterLanguage('mylang');

listLanguages()

Returns an array of all currently registered language names.

/**
 * Lists all registered language names
 * @returns Array of language names currently available
 */
function listLanguages(): string[];

Usage Examples:

// Get all available languages
const languages = hljs.listLanguages();
console.log(languages); // ['javascript', 'python', 'java', ...]

// Check if a language is available
const hasTypeScript = hljs.listLanguages().includes('typescript');

// Load languages dynamically based on availability
const requiredLanguages = ['python', 'rust', 'go'];
const missingLanguages = requiredLanguages.filter(lang => 
  !hljs.listLanguages().includes(lang)
);

// Conditionally register missing languages
if (missingLanguages.includes('rust')) {
  const rustLang = await import('@highlightjs/cdn-assets/languages/rust.min.js');
  hljs.registerLanguage('rust', rustLang.default);
}

getLanguage()

Retrieves a language definition object by name.

/**
 * Gets a language definition by name
 * @param languageName - Name of the language to retrieve
 * @returns Language definition object or undefined if not found
 */
function getLanguage(languageName: string): Language | undefined;

Usage Examples:

// Get language definition
const jsLang = hljs.getLanguage('javascript');
if (jsLang) {
  console.log(jsLang.name); // 'JavaScript'
  console.log(jsLang.aliases); // ['js', 'jsx']
}

// Check if language exists before using
const pythonLang = hljs.getLanguage('python');
if (pythonLang) {
  const result = hljs.highlight('print("hello")', { language: 'python' });
} else {
  console.warn('Python language not available');
}

// Inspect language properties
const cppLang = hljs.getLanguage('cpp');
if (cppLang) {
  console.log('Case sensitive:', !cppLang.case_insensitive);
  console.log('Auto-detection enabled:', !cppLang.disableAutodetect);
}

registerAliases()

Registers alternative names for an existing language.

/**
 * Registers aliases for an existing language
 * @param aliasList - Single alias string or array of aliases
 * @param options - Object containing the target language name
 */
function registerAliases(
  aliasList: string | string[], 
  { languageName }: { languageName: string }
): void;

Usage Examples:

// Register single alias
hljs.registerAliases('js', { languageName: 'javascript' });

// Register multiple aliases
hljs.registerAliases(['py', 'python3'], { languageName: 'python' });

// Use aliases for highlighting
const result1 = hljs.highlight('console.log("hi")', { language: 'js' });
const result2 = hljs.highlight('print("hi")', { language: 'py' });

// Aliases work with auto-detection too
const autoResult = hljs.highlightAuto('print("hello world")');
// Could detect as 'python', 'py', or 'python3'

autoDetection()

Checks whether a language supports automatic detection.

/**
 * Checks if a language supports auto-detection
 * @param languageName - Name of the language to check
 * @returns True if language can be auto-detected, false otherwise
 */
function autoDetection(languageName: string): boolean;

Usage Examples:

// Check if languages support auto-detection
console.log(hljs.autoDetection('javascript')); // true
console.log(hljs.autoDetection('xml')); // true
console.log(hljs.autoDetection('plaintext')); // false

// Build list of auto-detectable languages
const allLanguages = hljs.listLanguages();
const autoDetectableLanguages = allLanguages.filter(lang => 
  hljs.autoDetection(lang)
);
console.log('Auto-detectable:', autoDetectableLanguages);

// Conditional auto-detection
function smartHighlight(code, preferredLanguage) {
  if (hljs.autoDetection(preferredLanguage)) {
    return hljs.highlightAuto(code, [preferredLanguage]);
  }
  return hljs.highlight(code, { language: preferredLanguage });
}

Dynamic Language Loading

// Load languages on demand
async function loadLanguage(languageName) {
  // Check if already loaded
  if (hljs.getLanguage(languageName)) {
    return true;
  }
  
  try {
    // Dynamic import of language definition
    const langModule = await import(`@highlightjs/cdn-assets/languages/${languageName}.min.js`);
    hljs.registerLanguage(languageName, langModule.default);
    return true;
  } catch (error) {
    console.error(`Failed to load language ${languageName}:`, error);
    return false;
  }
}

// Usage
await loadLanguage('rust');
const rustCode = hljs.highlight('fn main() {}', { language: 'rust' });

Language Definition Structure

// Example custom language definition
hljs.registerLanguage('config', function(hljs) {
  return {
    name: 'Configuration',
    aliases: ['conf', 'cfg'],
    case_insensitive: true,
    keywords: 'true false yes no on off',
    contains: [
      {
        className: 'section',
        begin: /^\s*\[.*\]$/
      },
      {
        className: 'variable',
        begin: /^[a-zA-Z][a-zA-Z0-9_]*(?=\s*=)/
      },
      hljs.HASH_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE
    ]
  };
});

docs

configuration.md

core-highlighting.md

index.md

language-assets.md

language-management.md

plugins.md

utilities.md

tile.json