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

modes-patterns.mddocs/

Modes and Syntax Patterns

Pre-built syntax pattern definitions and utilities for creating language definitions and custom highlighting rules. These modes and patterns are the building blocks used to define how different programming languages are highlighted.

Capabilities

Mode Functions

Functions that create reusable syntax pattern definitions for common programming language constructs.

SHEBANG Function

Creates a mode for matching shebang lines at the beginning of script files.

/**
 * Creates a shebang mode for script files
 * @param mode - Optional mode configuration with binary pattern
 * @returns Mode object for shebang matching
 */
function SHEBANG(mode?: Partial<Mode> & {binary?: string | RegExp}): Mode;

Usage Examples:

import hljs from "highlight.js/lib/core";

// Basic shebang mode
const shebangMode = hljs.SHEBANG();
// Matches: #!/bin/bash, #!/usr/bin/env python, etc.

// Specific binary pattern
const pythonShebang = hljs.SHEBANG({binary: 'python'});
// Matches: #!/usr/bin/python, #!/usr/bin/env python

const nodeShebang = hljs.SHEBANG({binary: /node|nodejs/});
// Matches: #!/usr/bin/node, #!/usr/bin/env nodejs

// In a language definition
function myLanguage(hljs) {
  return {
    name: 'MyScript',
    contains: [
      hljs.SHEBANG({binary: 'myscript'}),
      // ... other modes
    ]
  };
}

COMMENT Function

Creates comment modes for single-line, multi-line, or custom comment patterns.

/**
 * Creates a comment mode
 * @param begin - Comment start pattern (string or regex)
 * @param end - Comment end pattern (string or regex)
 * @param modeOpts - Optional additional mode configuration
 * @returns Mode object for comment matching
 */
function COMMENT(begin: string | RegExp, end: string | RegExp, modeOpts?: Mode): Mode;

Usage Examples:

import hljs from "highlight.js/lib/core";

// Custom comment styles
const poundComment = hljs.COMMENT('#', '$');           // Shell-style
const slashComment = hljs.COMMENT('//', '$');          // C++ style  
const blockComment = hljs.COMMENT('/\\*', '\\*/');     // C-style blocks
const htmlComment = hljs.COMMENT('<!--', '-->');       // HTML comments
const sqlComment = hljs.COMMENT('--', '$');            // SQL comments

// Comment with additional options
const docComment = hljs.COMMENT('/**', '*/', {
  relevance: 10,
  contains: [
    {
      className: 'doctag',
      begin: '@\\w+'
    }
  ]
});

// Custom comment patterns
const customComment = hljs.COMMENT('REM ', '$', {
  case_insensitive: true  // For BASIC-style comments
});

END_SAME_AS_BEGIN Function

Creates a mode where the end pattern must match the begin pattern exactly.

/**
 * Creates a mode where end pattern matches begin pattern
 * @param mode - Mode with begin pattern containing capture group
 * @returns Enhanced mode with matching begin/end logic
 */
function END_SAME_AS_BEGIN(mode: Mode): Mode;

Usage Examples:

import hljs from "highlight.js/lib/core";

// Heredoc strings (matching delimiter)
const heredoc = hljs.END_SAME_AS_BEGIN({
  begin: /<<(\w+)/,  // <<EOF, <<HTML, etc.
  end: /^\1$/m,      // Must match the captured delimiter
  className: 'string'
});

// Matching quote styles
const matchingQuotes = hljs.END_SAME_AS_BEGIN({
  begin: /(['"`])/, // Single, double, or backtick quotes
  end: /\1/,        // Must match the same quote type
  className: 'string',
  contains: [hljs.BACKSLASH_ESCAPE]
});

// Template literals with custom delimiters
const templateLiteral = hljs.END_SAME_AS_BEGIN({
  begin: /(\$\{)([^}]*)/,
  end: /\}/,
  className: 'template-literal'
});

Pre-built Mode Constants

Ready-to-use mode definitions for common syntax patterns.

String Modes

/** Mode for backslash escape sequences */
const BACKSLASH_ESCAPE: Mode;

/** Mode for double-quoted strings */
const QUOTE_STRING_MODE: Mode;

/** Mode for single-quoted strings */
const APOS_STRING_MODE: Mode;

Usage Examples:

// Basic string modes
const stringModes = [
  hljs.QUOTE_STRING_MODE,  // "double quotes"
  hljs.APOS_STRING_MODE    // 'single quotes'
];

// Enhanced string mode with escapes
const enhancedString = {
  className: 'string',
  begin: '"',
  end: '"',
  contains: [hljs.BACKSLASH_ESCAPE]
};

// Language using string modes
function myLanguage(hljs) {
  return {
    contains: [
      hljs.QUOTE_STRING_MODE,
      hljs.APOS_STRING_MODE,
      // ... other modes
    ]
  };
}

Comment Modes

/** Mode for C-style line comments (//) */
const C_LINE_COMMENT_MODE: Mode;

/** Mode for C-style block comments (/* */) */
const C_BLOCK_COMMENT_MODE: Mode;

/** Mode for hash-style comments (#) */
const HASH_COMMENT_MODE: Mode;

/** Mode for common English words in comments */
const PHRASAL_WORDS_MODE: Mode;

Usage Examples:

// JavaScript-like language
function jsLikeLanguage(hljs) {
  return {
    contains: [
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      // ... other modes
    ]
  };
}

// Shell-like language
function shellLikeLanguage(hljs) {
  return {
    contains: [
      hljs.HASH_COMMENT_MODE,
      // ... other modes
    ]
  };
}

// Enhanced comment with phrasal words
const enhancedComment = {
  ...hljs.C_LINE_COMMENT_MODE,
  contains: [hljs.PHRASAL_WORDS_MODE]
};

Number Modes

/** Basic number mode for integers and decimals */
const NUMBER_MODE: Mode;

/** C-style numbers including hex, octal, scientific notation */
const C_NUMBER_MODE: Mode;

/** Binary number mode (0b...) */
const BINARY_NUMBER_MODE: Mode;

/** CSS number mode with units (px, em, %, etc.) */
const CSS_NUMBER_MODE: Mode;

Usage Examples:

// Basic programming language
function basicLanguage(hljs) {
  return {
    contains: [
      hljs.C_NUMBER_MODE,  // Supports 123, 0xFF, 1.5e10, etc.
      // ... other modes
    ]
  };
}

// Simple calculator language
function calculatorLanguage(hljs) {
  return {
    contains: [
      hljs.NUMBER_MODE,  // Just basic numbers
      // ... operators, etc.
    ]
  };
}

// CSS-like language
function cssLikeLanguage(hljs) {
  return {
    contains: [
      hljs.CSS_NUMBER_MODE,  // 10px, 1.5em, 50%, etc.
      // ... other modes
    ]
  };
}

Special Modes

/** Mode for regular expressions */
const REGEXP_MODE: Mode;

/** Mode for titles/identifiers */
const TITLE_MODE: Mode;

/** Mode for underscore-prefixed titles */
const UNDERSCORE_TITLE_MODE: Mode;

/** Mode to exclude method names from keyword processing */
const METHOD_GUARD: Mode;

Usage Examples:

// JavaScript-like language with regex support
function jsLikeLanguage(hljs) {
  return {
    contains: [
      hljs.REGEXP_MODE,       // /pattern/flags
      hljs.METHOD_GUARD,      // Prevents .methodName from being highlighted as keyword
      // ... other modes
    ]
  };
}

// Function definition highlighting
const functionMode = {
  begin: /function\s+/,
  end: /\(/,
  contains: [hljs.TITLE_MODE]  // Highlights function name
};

// Class/type definition
const classMode = {
  begin: /class\s+/,
  end: /\s*\{/,
  contains: [hljs.UNDERSCORE_TITLE_MODE]  // Highlights class name
};

Regular Expression Constants

Pre-defined regex patterns for common syntax elements.

/** Regular expression for basic identifiers */
const IDENT_RE: string;

/** Regular expression for underscore-prefixed identifiers */
const UNDERSCORE_IDENT_RE: string;

/** Regular expression that matches nothing */
const MATCH_NOTHING_RE: string;

/** Basic number pattern */
const NUMBER_RE: string;

/** C-style number pattern */
const C_NUMBER_RE: string;

/** Binary number pattern */
const BINARY_NUMBER_RE: string;

/** Regular expression starters pattern */
const RE_STARTERS_RE: string;

Usage Examples:

// Custom modes using regex constants
const customIdentifier = {
  className: 'variable',
  begin: hljs.UNDERSCORE_IDENT_RE
};

const customNumber = {
  className: 'number',
  begin: hljs.C_NUMBER_RE,
  relevance: 0
};

// Building complex patterns
const functionDeclaration = {
  begin: `function\\s+(${hljs.IDENT_RE})`,
  end: '\\(',
  className: 'function'
};

// Variable declaration
const variableDeclaration = {
  begin: `(var|let|const)\\s+(${hljs.IDENT_RE})`,
  className: 'variable'
};

Creating Custom Languages

Basic Language Structure

function myLanguage(hljs) {
  return {
    name: 'MyLanguage',
    aliases: ['mylang', 'ml'],
    case_insensitive: false,
    keywords: {
      keyword: 'if else while for function class',
      built_in: 'print console log error',
      literal: 'true false null undefined'
    },
    contains: [
      // Use pre-built modes
      hljs.C_LINE_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.QUOTE_STRING_MODE,
      hljs.APOS_STRING_MODE,
      hljs.C_NUMBER_MODE,
      
      // Custom modes
      {
        className: 'function',
        begin: /function\s+/,
        end: /\(/,
        contains: [hljs.TITLE_MODE]
      }
    ]
  };
}

// Register the language
hljs.registerLanguage('mylanguage', myLanguage);

Advanced Language Features

function advancedLanguage(hljs) {
  const KEYWORDS = {
    keyword: 'if else elif while for in def class import from',
    built_in: 'len str int float bool list dict set tuple',
    literal: 'True False None'
  };

  const STRING_MODES = [
    hljs.QUOTE_STRING_MODE,
    hljs.APOS_STRING_MODE,
    {
      className: 'string',
      begin: /"""/, end: /"""/,  // Triple-quoted strings
      contains: [hljs.BACKSLASH_ESCAPE]
    }
  ];

  return {
    name: 'Advanced Language',
    aliases: ['advanced', 'adv'],
    keywords: KEYWORDS,
    illegal: /@/,  // @ character is illegal
    contains: [
      hljs.HASH_COMMENT_MODE,
      ...STRING_MODES,
      hljs.C_NUMBER_MODE,
      
      // Function definitions
      {
        className: 'function',
        begin: /def\s+/,
        end: /:/,
        contains: [
          hljs.TITLE_MODE,
          {
            className: 'params',
            begin: /\(/, end: /\)/,
            contains: STRING_MODES.concat([hljs.C_NUMBER_MODE])
          }
        ]
      },
      
      // Class definitions
      {
        className: 'class',
        begin: /class\s+/,
        end: /:/,
        contains: [hljs.UNDERSCORE_TITLE_MODE]
      }
    ]
  };
}

Mode Inheritance and Composition

function languageWithInheritance(hljs) {
  // Base string mode
  const BASE_STRING = {
    className: 'string',
    contains: [hljs.BACKSLASH_ESCAPE]
  };

  // Different string types
  const DOUBLE_QUOTE_STRING = hljs.inherit(BASE_STRING, {
    begin: '"', end: '"'
  });

  const SINGLE_QUOTE_STRING = hljs.inherit(BASE_STRING, {
    begin: "'", end: "'"
  });

  const TEMPLATE_STRING = hljs.inherit(BASE_STRING, {
    begin: '`', end: '`',
    contains: [
      hljs.BACKSLASH_ESCAPE,
      {
        className: 'subst',
        begin: /\${/, end: /}/,
        contains: [] // Will be filled with language modes
      }
    ]
  });

  return {
    name: 'Language with Inheritance',
    contains: [
      DOUBLE_QUOTE_STRING,
      SINGLE_QUOTE_STRING,
      TEMPLATE_STRING,
      // ... other modes
    ]
  };
}

Best Practices

Performance Considerations

// Use specific patterns instead of broad ones
const GOOD_PATTERN = {
  begin: /function\s+\w+/,  // Specific function pattern
  relevance: 5
};

const AVOID_PATTERN = {
  begin: /\w+/,  // Too broad, matches everything
  relevance: 1
};

// Use relevance to prioritize important patterns
const HIGH_RELEVANCE = {
  className: 'keyword',
  begin: /function|class|if|else/,
  relevance: 10
};

Mode Organization

function wellOrganizedLanguage(hljs) {
  // Group related constants
  const KEYWORDS = {
    keyword: 'if else while for',
    built_in: 'print log',
    literal: 'true false'
  };

  // Reusable mode definitions
  const STRINGS = [
    hljs.QUOTE_STRING_MODE,
    hljs.APOS_STRING_MODE
  ];

  const COMMENTS = [
    hljs.C_LINE_COMMENT_MODE,
    hljs.C_BLOCK_COMMENT_MODE
  ];

  // Main language definition
  return {
    name: 'Well Organized',
    keywords: KEYWORDS,
    contains: [
      ...STRINGS,
      ...COMMENTS,
      hljs.C_NUMBER_MODE,
      // ... specific modes
    ]
  };
}