### Install lowlight Source: https://github.com/wooorm/lowlight/blob/main/readme.md Installation commands for Node.js, Deno, and browser environments. ```sh npm install lowlight ``` ```js import {all, common, createLowlight} from 'https://esm.sh/lowlight@3' ``` ```html ``` -------------------------------- ### Install Lowlight Source: https://context7.com/wooorm/lowlight/llms.txt Install the lowlight package using npm. ```bash npm install lowlight ``` -------------------------------- ### Regex Syntax Examples Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-regex/output.txt Demonstrates various ways to define and use regular expressions in JavaScript. ```javascript x = /\// x = /\n/ x = /ab\/ ab/ x = f /6 * 2/ - 3 x = f /foo * 2/gm x = if true then /\n/ else /[.,]+/ x = ///^key-#{key}-\d+/// ``` -------------------------------- ### JSX Syntax Examples Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-jsx/input.txt Illustrates various ways to define JSX elements, including self-closing, with children, and with attributes. ```jsx var jsx = ; ``` ```jsx var jsx = ; ``` ```jsx var jsx = ......; ``` ```jsx var jsx =

; ``` ```jsx return (); ``` -------------------------------- ### Division and Regex Syntax Patterns Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/output.txt These examples illustrate how the parser handles division operators and regex literals in different contexts. ```javascript x = 6/foo/i x = 6 /foo x = 6 / foo x = 6 /foo * 2/gm x = f /foo x = f / foo / gm x = f /foo * 2/6 ``` -------------------------------- ### Highlight specific language Source: https://github.com/wooorm/lowlight/blob/main/readme.md Example of highlighting CSS code using a lowlight instance. ```js import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) console.log(lowlight.highlight('css', 'em { color: red }')) ``` ```js {type: 'root', children: [Array], data: {language: 'css', relevance: 3}} ``` -------------------------------- ### Variable Declaration Example Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-jsx/input.txt A simple example of declaring a variable with a numeric value. ```javascript var x = 5; ``` -------------------------------- ### Return JSX with attributes Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-jsx/output.txt Example of returning a JSX element containing an attribute. ```javascript return (); ``` -------------------------------- ### Importing from Underscore.js in Main.js Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-modules/input.txt Imports default and named exports from the 'underscore' module, aliasing one import. Ensure 'underscore' is installed and exported correctly. ```javascript import _, { each, something as otherthing } from 'underscore'; ``` -------------------------------- ### Define JSX elements Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-jsx/output.txt Examples of declaring JSX variables with various nesting and self-closing tag structures. ```javascript var jsx = ; ``` ```javascript var jsx = ; ``` ```javascript var jsx = ......; ``` ```javascript var jsx =

; ``` -------------------------------- ### Split String and Get Character Codes Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-function/input.txt Splits a string by spaces and maps each word to the character code of its first letter. Useful for basic text processing. ```javascript str.split(" ").map((m) -> m.charCodeAt(0)) ``` -------------------------------- ### Create Lowlight with All Syntaxes Source: https://github.com/wooorm/lowlight/blob/main/readme.md Initialize Lowlight with all available syntaxes by importing `all`. This provides comprehensive language support. ```javascript import { createLowlight } from "lowlight" import { all } from "lowlight/lib/common" const lowlight = createLowlight(all) ``` -------------------------------- ### createLowlight - Create a Lowlight Instance Source: https://context7.com/wooorm/lowlight/llms.txt Creates a new lowlight instance, optionally pre-loaded with language grammars for highlighting, registration, and management. ```APIDOC ## createLowlight(languages) ### Description Creates a new lowlight instance. You can pass a bundle of languages (common or all) or a custom object mapping language names to their highlight.js definitions. ### Parameters #### Request Body - **languages** (object) - Optional - An object containing language definitions or a pre-configured bundle (common/all). ``` -------------------------------- ### Use the All Grammar Bundle Source: https://context7.com/wooorm/lowlight/llms.txt Includes over 190 languages supported by highlight.js for comprehensive coverage. ```javascript import {all, createLowlight} from 'lowlight' const lowlight = createLowlight(all) console.log(`Total languages: ${lowlight.listLanguages().length}`) // Output: Total languages: 197 // Highlight esoteric or specialized languages const examples = [ {lang: 'haskell', code: 'quicksort [] = []\nquicksort (x:xs) = quicksort [y | y <- xs, y < x] ++ [x] ++ quicksort [y | y <- xs, y >= x]'}, {lang: 'erlang', code: '-module(hello).\n-export([world/0]).\nworld() -> io:format("Hello World~n").'}, {lang: 'clojure', code: '(defn greet [name] (str "Hello, " name "!"))'}, {lang: 'fortran', code: 'PROGRAM HELLO\n PRINT *, "Hello, World!"\nEND PROGRAM'}, {lang: 'cobol', code: 'IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO-WORLD.'}, {lang: 'brainfuck', code: '++++++++++[>+++++++>++++++++++>+++>+<<<<-]'} ] for (const {lang, code} of examples) { if (lowlight.registered(lang)) { const tree = lowlight.highlight(lang, code) console.log(`${lang}: ${tree.children.length} nodes`) } } ``` -------------------------------- ### Create Lowlight Instance Source: https://context7.com/wooorm/lowlight/llms.txt Create a lowlight instance with pre-loaded or custom language grammars. Use `common` for 37 popular languages, `all` for 190+, or register individual languages. ```javascript import {createLowlight, common, all} from 'lowlight' // Create instance with common languages (37 popular languages) const lowlightCommon = createLowlight(common) // Create instance with all languages (190+ languages) const lowlightAll = createLowlight(all) // Create empty instance and register languages manually const lowlightEmpty = createLowlight() // Create instance with specific languages only import javascript from 'highlight.js/lib/languages/javascript' import typescript from 'highlight.js/lib/languages/typescript' import css from 'highlight.js/lib/languages/css' const lowlightCustom = createLowlight({javascript, typescript, css}) console.log(lowlightCustom.listLanguages()) // Output: ['javascript', 'typescript', 'css'] ``` -------------------------------- ### Create Lowlight with Common Syntaxes Source: https://github.com/wooorm/lowlight/blob/main/readme.md Initialize Lowlight with a common set of syntaxes by importing `common`. This is suitable for most use cases. ```javascript import { createLowlight } from "lowlight" import { common } from "lowlight/lib/common" const lowlight = createLowlight(common) ``` -------------------------------- ### TypeScript Types and Usage Source: https://context7.com/wooorm/lowlight/llms.txt Demonstrates importing and using Lowlight's TypeScript types for configuration, highlighting, and custom grammar registration. Ensure correct types are used for options and returned AST data. ```typescript import type {LanguageFn} from 'highlight.js' import type {Root} from 'hast' import {createLowlight, common} from 'lowlight' import type {AutoOptions, Options} from 'lowlight' // Options for highlight() const highlightOptions: Options = { prefix: 'syntax-' // Custom CSS class prefix } // Options for highlightAuto() const autoOptions: AutoOptions = { prefix: 'syntax-', subset: ['javascript', 'typescript', 'python'] // Limit detection } const lowlight = createLowlight(common) // Return type is hast Root with language data const tree: Root = lowlight.highlight('javascript', 'const x = 42', highlightOptions) // Access typed data fields const language: string | undefined = tree.data?.language const relevance: number | undefined = tree.data?.relevance // Register custom grammar with proper typing const customGrammar: LanguageFn = (hljs) => ({ name: 'custom', contains: [ hljs.QUOTE_STRING_MODE, hljs.C_NUMBER_MODE ] }) lowlight.register('custom', customGrammar) ``` -------------------------------- ### lowlight.listLanguages() Source: https://github.com/wooorm/lowlight/blob/main/readme.md Lists all currently registered programming languages. ```APIDOC ## lowlight.listLanguages() ### Description Returns a list of names of all registered languages. ### Returns - **Array** - List of registered language names. ### Response Example ['markdown', 'javascript'] ``` -------------------------------- ### Initialize Redux Store Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-default-parameters/input.txt Combine multiple reducers into a single root reducer and create the Redux store instance. ```javascript import { combineReducers, createStore } from 'redux'; let reducer = combineReducers({ visibleTodoFilter, todos }); let store = createStore(reducer); ``` -------------------------------- ### Highlighting numeric variables Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/go-numbers/output.txt Demonstrates syntax highlighting for floating point and complex number assignments. ```text float_var := 1.0e10f complex_var := 1.2e5+2.3i ``` -------------------------------- ### Manually Import a Syntax Source: https://github.com/wooorm/lowlight/blob/main/readme.md Import a specific syntax definition manually from `highlight.js/lib/languages/xxx`. Replace `xxx` with the desired language name. ```javascript import { createLowlight } from "lowlight" // Example: Importing the 'wasm' syntax import wasm from "highlight.js/lib/languages/wasm" const lowlight = createLowlight([ wasm ]) ``` -------------------------------- ### SQL Window Functions for Aggregation Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/pgsql-default/input.txt Demonstrates using SUM and AVG window functions with a defined window specification for partitioned and ordered data. ```sql BEGIN; SELECT sum(salary) OVER w, avg(salary) OVER w FROM empsalary WINDOW w AS (PARTITION BY depname ORDER BY salary DESC); END; ``` -------------------------------- ### Use the Common Grammar Bundle Source: https://context7.com/wooorm/lowlight/llms.txt Utilizes a pre-configured set of 37 popular programming languages. ```javascript import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) // Languages included in common bundle: // arduino, bash, c, cpp, csharp, css, diff, go, graphql, ini, // java, javascript, json, kotlin, less, lua, makefile, markdown, // objectivec, perl, php, php-template, plaintext, python, python-repl, // r, ruby, rust, scss, shell, sql, swift, typescript, vbnet, wasm, xml, yaml // Example: Highlight multiple common languages const examples = [ {lang: 'javascript', code: 'const x = 42;'}, {lang: 'python', code: 'x = 42'}, {lang: 'rust', code: 'let x: i32 = 42;'}, {lang: 'go', code: 'var x int = 42'}, {lang: 'sql', code: 'SELECT * FROM users;'}, {lang: 'yaml', code: 'name: lowlight\nversion: 3.0.0'} ] for (const {lang, code} of examples) { const tree = lowlight.highlight(lang, code) console.log(`${lang}: relevance ${tree.data.relevance}`) } ``` -------------------------------- ### Division with function, variable, and flag Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/input.txt Demonstrates division with a function, a variable, and a regex flag. ```javascript x = f / foo / gm ``` -------------------------------- ### Division with function and variable Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/input.txt Demonstrates division with a function and a variable. ```javascript x = f /foo ``` -------------------------------- ### Lowlight Core API Source: https://github.com/wooorm/lowlight/blob/main/readme.md This section details the main functions exported by the lowlight package for creating and using the highlighter. ```APIDOC ## `all` ### Description Map of all (±190) grammars. ### Type `Record` ## `common` ### Description Map of common (37) grammars. ### Type `Record` ## `createLowlight([grammars])` ### Description Create a `lowlight` instance. ### Parameters #### Path Parameters * **grammars** (`Record`) - Optional - grammars to add ### Returns Lowlight (`Lowlight`) ## `lowlight.highlight(language, value[, options])` ### Description Highlight `value` (code) as `language` (name). ### Parameters #### Path Parameters * **language** (`string`) - Required - programming language [name][names] * **value** (`string`) - Required - code to highlight * **options** (`Options`) - Optional - configuration ### Returns Tree ([`Root`][hast-root]); with the following `data` fields: `language` (`string`), detected programming language name; `relevance` (`number`), how sure lowlight is that the given code is in the language. ### Request Example ```js import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) console.log(lowlight.highlight('css', 'em { color: red }')) ``` ### Response Example ```json { "type": "root", "children": [ { "type": "element", "tagName": "span", "properties": {"className": ["hljs-keyword"]}, "children": [{"type": "text", "value": "em"}] }, {"type": "text", "value": " {"} { "type": "element", "tagName": "span", "properties": {"className": ["hljs-attribute"]}, "children": [{"type": "text", "value": "color"}] }, {"type": "text", "value": ": "} { "type": "element", "tagName": "span", "properties": {"className": ["hljs-string"]}, "children": [{"type": "text", "value": "red"}] }, {"type": "text", "value": " "} ], "data": {"language": "css", "relevance": 3} } ``` ## `lowlight.highlightAuto(value[, options])` ### Description Highlight `value` (code) and guess its programming language. ### Parameters #### Path Parameters * **value** (`string`) - Required - code to highlight * **options** (`AutoOptions`) - Optional - configuration ``` -------------------------------- ### Define Swift Protocol Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/swift-functions/output.txt Use this to define a protocol with required methods. ```swift protocol Protocol { func f1() func f2() } ``` -------------------------------- ### Basic Script Tag Usage Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/xml-sublanguages-2/output.txt This snippet shows how to use a script tag to execute a function. ```html ``` -------------------------------- ### Division with variable and flag (space) Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/input.txt Demonstrates division with a variable and a regex flag, with spaces. ```javascript x = 6 /foo ``` -------------------------------- ### lowlight.register - Register Language Grammars Source: https://context7.com/wooorm/lowlight/llms.txt Registers one or more language grammars for syntax highlighting. Supports both single language and batch registration. ```APIDOC ## lowlight.register - Register Language Grammars ### Description Registers one or more language grammars for syntax highlighting. Supports both single language and batch registration. ### Method `register(name: string, grammar: object) | register(grammars: { [name: string]: object }) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the language grammar to register. - **grammar** (object) - Required - The language grammar object. - **grammars** (object) - Required - An object where keys are language names and values are grammar objects. ### Request Example ```javascript import {createLowlight} from 'lowlight' import xml from 'highlight.js/lib/languages/xml' import json from 'highlight.js/lib/languages/json' const lowlight = createLowlight() // Register single language lowlight.register('xml', xml) // Register multiple languages lowlight.register({json}) ``` ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Division with variable and flag Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/input.txt Demonstrates division with a variable and a regex flag. ```javascript x = 6/foo/i ``` -------------------------------- ### Basic CSS Styling Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/xml-sublanguages/output.txt This snippet demonstrates basic CSS styling for an HTML element. It is not directly related to Lowlight's core functionality but shows a common use case for styling within HTML. ```html ``` -------------------------------- ### Import Modules in main.js Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-modules/output.txt Imports default and named exports from the underscore module. ```javascript //------ main.js ------ import _, { each, something as otherthing } from 'underscore'; ``` -------------------------------- ### Division with variable, flag, and multiplication Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/input.txt Demonstrates division with a variable, a regex flag, and multiplication. ```javascript x = 6 /foo * 2/gm ``` -------------------------------- ### Highlight CSS :not pseudo-class Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/css-pseudo-selector/output.txt Demonstrates highlighting for a single :not pseudo-class selector. ```css li:not(.red){} ``` -------------------------------- ### Division with variable and flag (more spaces) Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/input.txt Demonstrates division with a variable and a regex flag, with more spaces. ```javascript x = 6 / foo ``` -------------------------------- ### Include highlight.js CSS theme Source: https://github.com/wooorm/lowlight/blob/main/readme.md Use a standard highlight.js stylesheet from a CDN to style code blocks highlighted by lowlight. ```html ``` -------------------------------- ### Highlight code with lowlight Source: https://github.com/wooorm/lowlight/blob/main/readme.md Basic usage to highlight a string of code and inspect the resulting AST. ```js import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) const tree = lowlight.highlight('js', '"use strict";') console.dir(tree, {depth: undefined}) ``` ```js { type: 'root', children: [ { type: 'element', tagName: 'span', properties: {className: ['hljs-meta']}, children: [{type: 'text', value: '"use strict"'}] }, {type: 'text', value: ';'} ], data: {language: 'js', relevance: 10} } ``` -------------------------------- ### lowlight.register(grammars) Source: https://github.com/wooorm/lowlight/blob/main/readme.md Registers one or more language grammars for use in highlighting. ```APIDOC ## lowlight.register(grammars) ### Description Registers languages to be used by the highlighter. ### Parameters - **name** (string) - Optional - Programming language name. - **grammar** (LanguageFn) - Optional - The language grammar. - **grammars** (Record) - Optional - A map of grammars. ### Returns - **undefined** ``` -------------------------------- ### Initialize Highlight Function Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-keywords/input.txt This function initializes the syntax highlighting process for a given block of code. It checks for a 'no-highlight' class and handles potential exceptions during processing. ```javascript function $initHighlight(block, cls) { try { if (cls.search(/\bno\-highlight\b/) != -1) return process(block, true, 0x0F) + ' class=""'; } catch (e) { /* handle exception */ } for (var i = 0 / 2; i < classes.length; i++) { if (checkCondition(classes[i]) === undefined) return /\d+[\s/]/g; } } ``` -------------------------------- ### lowlight.highlightAuto - Auto-Detect Language and Highlight Source: https://context7.com/wooorm/lowlight/llms.txt Automatically detects the programming language of the provided code and highlights it. ```APIDOC ## lowlight.highlightAuto(value, options) ### Description Detects the language of the input code and highlights it. Detection can be restricted to a subset of languages. ### Parameters #### Path Parameters - **value** (string) - Required - The code string to detect and highlight. #### Request Body - **options** (object) - Optional - Configuration object containing 'subset' (array of strings to restrict detection) and 'prefix' (string for class names). ### Response #### Success Response (200) - **root** (object) - A hast Root node containing the highlighted elements and metadata (language, relevance). ``` -------------------------------- ### Division with function, variable, multiplication, and number Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-division/input.txt Demonstrates division with a function, a variable, multiplication, and a number. ```javascript x = f /foo * 2/6 ``` -------------------------------- ### Raw String Literals Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/rust-strings/output.txt Illustrates raw strings, which treat backslashes literally, and raw f-strings with custom delimiters. ```string r"hello"; ``` ```string r###"world"###; ``` ```string r##" "### " # "##; ``` -------------------------------- ### Highlight chained CSS :not pseudo-classes Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/css-pseudo-selector/output.txt Demonstrates highlighting for multiple chained :not pseudo-class selectors. ```css li:not(.red):not(.green){} ``` -------------------------------- ### Read and Parse Package.json Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-function/input.txt Reads the package.json file, parses its content as JSON, and accesses the version property. Requires the 'fs' module. ```javascript fs.readFile("package.json", "utf-8", (err, content) -> data = JSON.parse(content) data.version ) ``` -------------------------------- ### Rust Numeric Literals Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/rust-numbers/output.txt Demonstrates integer and floating-point literal syntax including base prefixes and type suffixes. ```rust 123; 123usize; 123_usize; 0xff00; 0xff_u8; 0b1111111110010000; 0b1111_1111_1001_0000_i32; 0o764317; 0o764317_u16; 123.0; 0.1; 0.1f32; 12E+99_f64; ``` -------------------------------- ### Double-Quoted and Byte String Literals Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/rust-strings/output.txt Shows standard double-quoted strings and their byte string equivalents. ```string "hello"; ``` ```string b"hello"; ``` -------------------------------- ### Register Language Grammars with lowlight.register Source: https://context7.com/wooorm/lowlight/llms.txt Registers language grammars individually or in batches. The registered languages can then be used for syntax highlighting. ```javascript import {createLowlight} from 'lowlight' import xml from 'highlight.js/lib/languages/xml' import json from 'highlight.js/lib/languages/json' import markdown from 'highlight.js/lib/languages/markdown' import dockerfile from 'highlight.js/lib/languages/dockerfile' const lowlight = createLowlight() // Register single language with name and grammar lowlight.register('xml', xml) // Register multiple languages as an object lowlight.register({json, markdown, dockerfile}) // Note: xml grammar includes 'html' alias automatically console.log(lowlight.listLanguages()) // Output: ['xml', 'json', 'markdown', 'dockerfile'] // Now you can highlight these languages const htmlTree = lowlight.highlight('html', '
Content
') console.log(htmlTree.data) // Output: { language: 'html', relevance: 2 } const jsonTree = lowlight.highlight('json', '{"name": "lowlight", "version": "3.0.0"}') console.log(jsonTree.data) // Output: { language: 'json', relevance: 6 } ``` -------------------------------- ### Check Language Registration with lowlight.registered Source: https://context7.com/wooorm/lowlight/llms.txt Verifies if a language name or alias is currently registered. Useful for implementing conditional highlighting logic. ```javascript import {createLowlight} from 'lowlight' import javascript from 'highlight.js/lib/languages/javascript' import python from 'highlight.js/lib/languages/python' const lowlight = createLowlight({javascript, python}) // Check registered languages console.log(lowlight.registered('javascript')) // Output: true console.log(lowlight.registered('python')) // Output: true console.log(lowlight.registered('ruby')) // Output: false // Check built-in aliases (js is an alias for javascript) console.log(lowlight.registered('js')) // Output: true console.log(lowlight.registered('py')) // Output: true // Register custom alias and verify lowlight.registerAlias('javascript', 'ecmascript') console.log(lowlight.registered('ecmascript')) // Output: true // Useful for conditional highlighting function safeHighlight(lowlight, language, code) { if (lowlight.registered(language)) { return lowlight.highlight(language, code) } // Fallback to plaintext or auto-detection return lowlight.highlightAuto(code) } ``` -------------------------------- ### lowlight.highlight - Highlight Code with Known Language Source: https://context7.com/wooorm/lowlight/llms.txt Highlights code when the programming language is known, returning a hast Root node. ```APIDOC ## lowlight.highlight(language, value, options) ### Description Highlights the provided code string using the specified language grammar. ### Parameters #### Path Parameters - **language** (string) - Required - The name of the language to use for highlighting. - **value** (string) - Required - The code string to highlight. #### Request Body - **options** (object) - Optional - Configuration options such as 'prefix' to change the default class prefix (e.g., 'hljs-'). ### Response #### Success Response (200) - **root** (object) - A hast Root node containing the highlighted elements and metadata (language, relevance). ``` -------------------------------- ### Serialize to HTML with hast-util-to-html Source: https://context7.com/wooorm/lowlight/llms.txt Converts a hast tree into an HTML string. Requires the hast-util-to-html package. ```javascript import {common, createLowlight} from 'lowlight' import {toHtml} from 'hast-util-to-html' const lowlight = createLowlight(common) // Highlight and serialize to HTML const tree = lowlight.highlight('javascript', ` function greet(name) { return 'Hello, ' + name + '!'; } `) const html = toHtml(tree) console.log(html) // Output: // function greet(name) { // return 'Hello, ' + name + '!'; // } // Use in a complete HTML document const fullHtml = `
${toHtml(lowlight.highlight('python', 'print("Hello, World!")'))}
` ``` -------------------------------- ### Define basic CoffeeScript functions Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-function/output.txt Simple function definitions returning null, true, or the square of an input. ```coffeescript returnNull = -> null returnTrue = () -> true square = (x) -> x * x ``` -------------------------------- ### lowlight.registerAlias - Register Language Aliases Source: https://context7.com/wooorm/lowlight/llms.txt Creates alternative names for registered languages, allowing you to use custom or abbreviated names. ```APIDOC ## lowlight.registerAlias - Register Language Aliases ### Description Creates alternative names for registered languages, allowing you to use custom or abbreviated names. ### Method `registerAlias(name: string, aliases: string | string[]) | registerAlias(aliases: { [name: string]: string | string[] }) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (string) - Required - The name of the language to register aliases for. - **aliases** (string | string[]) - Required - A single alias or an array of aliases. - **aliases** (object) - Required - An object where keys are language names and values are single aliases or arrays of aliases. ### Request Example ```javascript import {createLowlight} from 'lowlight' import javascript from 'highlight.js/lib/languages/javascript' const lowlight = createLowlight({javascript}) // Register single alias lowlight.registerAlias('javascript', 'es6') // Register multiple aliases lowlight.registerAlias('javascript', ['js', 'jsx']) // Register aliases for multiple languages lowlight.registerAlias({ javascript: ['js', 'jsx'], typescript: ['ts', 'tsx'] }) ``` ### Response None #### Success Response (200) None #### Response Example None ``` -------------------------------- ### lowlight.registerAlias(aliases) Source: https://github.com/wooorm/lowlight/blob/main/readme.md Registers aliases for existing programming languages. ```APIDOC ## lowlight.registerAlias(aliases) ### Description Maps language names to one or more aliases. ### Parameters - **aliases** (Record | string>) - Required - Map of language names to aliases. - **name** (string) - Optional - Language name. - **alias** (Array | string) - Optional - Alias(es) for the language. ### Returns - **undefined** ``` -------------------------------- ### Basic String Literals Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/rust-strings/output.txt Demonstrates single-quoted strings with escaped characters like newlines and hex/unicode escapes. ```string 'a'; ``` ```string '\n'; ``` ```string '\x1A'; ``` ```string '\u12AS'; ``` ```string '\U1234ASDF'; ``` ```string b'a'; ``` -------------------------------- ### List Registered Languages Source: https://github.com/wooorm/lowlight/blob/main/readme.md Lists all programming languages currently registered with the lowlight instance. Initially empty, languages can be registered using `lowlight.register()`. ```javascript import {createLowlight} from 'lowlight' import markdown from 'highlight.js/lib/languages/markdown' const lowlight = createLowlight() console.log(lowlight.listLanguages()) // => [] lowlight.register({markdown}) console.log(lowlight.listLanguages()) // => ['markdown'] ``` -------------------------------- ### Convert to React/JSX with hast-util-to-jsx-runtime Source: https://context7.com/wooorm/lowlight/llms.txt Transforms a hast tree into React components. Compatible with Preact, Solid, Vue, and Svelte by adjusting the runtime imports. ```javascript import {toJsxRuntime} from 'hast-util-to-jsx-runtime' import {Fragment, jsx, jsxs} from 'react/jsx-runtime' import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) // Highlight code const tree = lowlight.highlight('typescript', ` interface User { id: number; name: string; } const user: User = { id: 1, name: 'Alice' }; `) // Convert to React element const reactElement = toJsxRuntime(tree, {Fragment, jsx, jsxs}) // Use in a React component function CodeBlock({language, code}) { const tree = lowlight.highlight(language, code) return (
      
        {toJsxRuntime(tree, {Fragment, jsx, jsxs})}
      
    
) } // For Preact, use preact/jsx-runtime instead // import {Fragment, jsx, jsxs} from 'preact/jsx-runtime' // Example component usage // ``` -------------------------------- ### Declare variables in lowlight Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/rust-variables/output.txt Syntax for declaring various variable types. ```javascript let foo; let mut bar; let _foo_bar; ``` -------------------------------- ### Serialize HAST as HTML Source: https://github.com/wooorm/lowlight/blob/main/readme.md Serializes a HAST (Hypertext Abstract Syntax Tree) generated by lowlight into an HTML string using `hast-util-to-html`. This is useful for rendering highlighted code in web pages. ```javascript import {common, createLowlight} from 'lowlight' import {toHtml} from 'hast-util-to-html' const lowlight = createLowlight(common) const tree = lowlight.highlight('js', '"use strict";') console.log(toHtml(tree)) ``` -------------------------------- ### Register Language Grammar Source: https://github.com/wooorm/lowlight/blob/main/readme.md Registers a new programming language grammar with the lowlight instance. This allows highlighting code in that language. Can register a single grammar or multiple grammars. ```javascript import {createLowlight} from 'lowlight' import xml from 'highlight.js/lib/languages/xml' const lowlight = createLowlight() lowlight.register({xml}) // Note: `html` is an alias for `xml`. console.log(lowlight.highlight('html', 'Emphasis')) ``` -------------------------------- ### Define a standard heredoc in Ruby Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/ruby-heredoc/input.txt Uses the <<-HTML syntax to define a multi-line string that preserves indentation. ```ruby def foo() msg = <<-HTML

#{bar}

HTML end ``` -------------------------------- ### Define Functions Returning Null or True Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/coffee-function/input.txt Simple function definitions that return null or true. Useful for basic test cases or placeholder functions. ```javascript returnNull = -> null ``` ```javascript returnTrue = () -> true ``` -------------------------------- ### Define a squiggly heredoc in Ruby Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/ruby-heredoc/input.txt Uses the <<~FOO syntax to define a multi-line string that strips leading whitespace based on the indentation of the closing delimiter. ```ruby def baz() msg = <<~FOO

#{bar}

FOO end ``` -------------------------------- ### POST /task Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/http-default/input.txt Creates or updates a task with the specified ID and status. The extended field can be used for additional options. ```APIDOC ## POST /task ### Description Creates or updates a task with the specified ID and status. The extended field can be used for additional options. ### Method POST ### Endpoint /task ### Query Parameters - **id** (integer) - Required - The unique identifier for the task. ### Request Body - **status** (string) - Required - The current status of the task (e.g., "ok"). - **extended** (boolean) - Optional - Indicates if extended options should be applied. ### Request Example ```json { "status": "ok", "extended": true } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the task was updated. #### Response Example ```json { "message": "Task updated successfully." } ``` ``` -------------------------------- ### Register Language Aliases with lowlight.registerAlias Source: https://context7.com/wooorm/lowlight/llms.txt Defines alternative names for registered languages. Aliases can be used interchangeably with the primary language name during highlighting. ```javascript import {createLowlight} from 'lowlight' import javascript from 'highlight.js/lib/languages/javascript' import markdown from 'highlight.js/lib/languages/markdown' import typescript from 'highlight.js/lib/languages/typescript' const lowlight = createLowlight({javascript, markdown, typescript}) // Register single alias lowlight.registerAlias('javascript', 'es6') // Register multiple aliases for one language lowlight.registerAlias('markdown', ['mdown', 'mkdn', 'mdwn', 'md']) // Register aliases for multiple languages at once lowlight.registerAlias({ typescript: ['ts', 'tsx'], javascript: ['js', 'jsx', 'node'] }) // All aliases now work for highlighting const tree1 = lowlight.highlight('es6', 'const x = 42') console.log(tree1.data.language) // Output: 'es6' const tree2 = lowlight.highlight('mdown', '# Heading') console.log(tree2.data.language) // Output: 'mdown' const tree3 = lowlight.highlight('ts', 'const x: number = 42') console.log(tree3.data.language) // Output: 'ts' ``` -------------------------------- ### lowlight.registered - Check If Language Is Registered Source: https://context7.com/wooorm/lowlight/llms.txt Checks whether a language name or alias is registered in the lowlight instance. ```APIDOC ## lowlight.registered - Check If Language Is Registered ### Description Checks whether a language name or alias is registered in the lowlight instance. ### Method `registered(name: string): boolean ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import {createLowlight} from 'lowlight' import javascript from 'highlight.js/lib/languages/javascript' const lowlight = createLowlight({javascript}) console.log(lowlight.registered('javascript')) // Output: true console.log(lowlight.registered('js')) // Output: true (if 'js' is an alias) console.log(lowlight.registered('python')) // Output: false ``` ### Response - **boolean** (boolean) - Returns `true` if the language or alias is registered, `false` otherwise. #### Success Response (200) - **boolean** (boolean) - `true` or `false` #### Response Example ```json true ``` ``` -------------------------------- ### Auto-Detect Language and Highlight Code Source: https://context7.com/wooorm/lowlight/llms.txt Automatically detect the programming language and highlight the code. Useful when the language is unknown. Detection can be restricted to a subset of languages, and custom class prefixes can be used. ```javascript import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) // Auto-detect language const result = lowlight.highlightAuto('console.log("Hello, World!");') console.log(result.data) // Output: { language: 'javascript', relevance: 5 } // Restrict detection to specific languages const restrictedResult = lowlight.highlightAuto( 'SELECT * FROM users WHERE id = 1', {subset: ['sql', 'javascript', 'python']} ) console.log(restrictedResult.data) // Output: { language: 'sql', relevance: 2 } // Use custom class prefix with auto-detection const customResult = lowlight.highlightAuto( 'fn main() { println!("Hello"); }', {prefix: 'syntax-', subset: ['rust', 'go', 'c']} ) console.log(customResult.data.language) // Output: 'rust' ``` -------------------------------- ### Convert HAST to JSX Runtime Source: https://github.com/wooorm/lowlight/blob/main/readme.md Converts a HAST tree generated by lowlight into nodes compatible with JSX runtimes (like React, Preact, etc.) using `hast-util-to-jsx-runtime`. This enables rendering highlighted code within JSX applications. ```javascript import {toJsxRuntime} from 'hast-util-to-jsx-runtime' // @ts-expect-error: react types don’t type these. import {Fragment, jsx, jsxs} from 'react/jsx-runtime' import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) const tree = lowlight.highlight('js', '"use strict";') console.log(toJsxRuntime(tree, {Fragment, jsx, jsxs})) ``` -------------------------------- ### Define Multi-line Strings with Ruby Heredocs Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/ruby-heredoc/output.txt Uses standard and squiggly heredoc syntax to define multi-line strings containing interpolated variables. ```ruby def foo() msg = <<-HTML

#{bar}

HTML end ``` ```ruby def baz() msg = <<~FOO

#{bar}

FOO end ``` -------------------------------- ### Define Infix Operators Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/haskell-infix/output.txt Define custom infix operators with specified precedence and associativity. Useful for creating domain-specific languages or extending existing ones. ```rust infix 3 `foo` infixl 6 `bar` infixr 9 `baz` ``` -------------------------------- ### List Registered Languages with lowlight.listLanguages Source: https://context7.com/wooorm/lowlight/llms.txt Retrieves an array of all registered language names. Note that this method does not include aliases in the returned list. ```javascript import {createLowlight, common, all} from 'lowlight' // Empty instance has no languages const emptyLowlight = createLowlight() console.log(emptyLowlight.listLanguages()) // Output: [] // Common bundle includes 37 languages const commonLowlight = createLowlight(common) console.log(commonLowlight.listLanguages().length) // Output: 37 console.log(commonLowlight.listLanguages().slice(0, 10)) // Output: ['arduino', 'bash', 'c', 'cpp', 'csharp', 'css', 'diff', 'go', 'graphql', 'ini'] // All bundle includes 190+ languages const allLowlight = createLowlight(all) console.log(allLowlight.listLanguages().length) // Output: 197 (or similar, depends on highlight.js version) // Custom instance import javascript from 'highlight.js/lib/languages/javascript' import css from 'highlight.js/lib/languages/css' const customLowlight = createLowlight({javascript, css}) console.log(customLowlight.listLanguages()) // Output: ['javascript', 'css'] ``` -------------------------------- ### POST /task Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/http-default/output.txt Updates or creates a task status based on the provided ID. ```APIDOC ## POST /task ### Description Updates the status of a task identified by the provided query parameter. ### Method POST ### Endpoint /task ### Parameters #### Query Parameters - **id** (string) - Required - The unique identifier of the task. ### Request Body - **status** (string) - Required - The status of the task. - **extended** (boolean) - Required - Flag indicating if the task is extended. ### Request Example { "status": "ok", "extended": true } ### Response #### Success Response (200) - **status** (string) - The status of the operation. - **extended** (boolean) - The extended status of the task. ``` -------------------------------- ### Define Swift Class Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/swift-functions/output.txt Use this to define a class with a method that returns a boolean. ```swift class MyClass { func f() { return true } } ``` -------------------------------- ### PL/pgSQL Function to Generate Day Abbreviations Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/pgsql-default/input.txt A PL/pgSQL function that returns a set of text, generating day abbreviations for a specified range of Julian days. ```plpgsql CREATE FUNCTION days_of_week() RETURNS SETOF text AS $$ BEGIN FOR i IN 7 .. 13 LOOP RETURN NEXT to_char(to_date(i::text,'J'),'TMDy'); END LOOP; END; $$ STABLE LANGUAGE plpgsql; ``` -------------------------------- ### Define Module Exports in underscore.js Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-modules/output.txt Defines default and named exports for utility functions. ```javascript //------ underscore.js ------ export default function (obj) {}; export function each(obj, iterator, context) {}; export { each as forEach }; export function something() {}; ``` -------------------------------- ### Highlight.js Multiple Escape Characters Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/haskell-nested-comments/lisp-mec/output.txt Demonstrates the use of multiple escape characters in Highlight.js, as discussed in issue 615. This pattern handles spaces and newlines within quoted strings. ```regex ; MEC: Multiple Escape Characters. See https://github.com/isagalaev/highlight.js/issues/615 (|spaces and newlines|) x ``` ```regex (x) '|quoted|' ``` -------------------------------- ### Highlight Auto Code Source: https://github.com/wooorm/lowlight/blob/main/readme.md Automatically detects and highlights the programming language of a given string. Requires common languages to be loaded. ```javascript import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) console.log(lowlight.highlightAuto('"hello, " + name + "!"')) ``` -------------------------------- ### Highlight Code with Known Language Source: https://context7.com/wooorm/lowlight/llms.txt Highlight code when the programming language is known. Returns a HAST root node with language and relevance data. Custom class prefixes can be used. ```javascript import {common, createLowlight} from 'lowlight' const lowlight = createLowlight(common) // Highlight JavaScript code const jsTree = lowlight.highlight('javascript', 'const greeting = "Hello, World!";') console.dir(jsTree, {depth: null}) // Output: // { // type: 'root', // children: [ // { // type: 'element', // tagName: 'span', // properties: { className: ['hljs-keyword'] }, // children: [{ type: 'text', value: 'const' }] // }, // { type: 'text', value: ' greeting = ' }, // { // type: 'element', // tagName: 'span', // properties: { className: ['hljs-string'] }, // children: [{ type: 'text', value: '"Hello, World!"' }] // }, // { type: 'text', value: ';' } // ], // data: { language: 'javascript', relevance: 2 } // } // Highlight CSS code const cssTree = lowlight.highlight('css', 'em { color: red }') console.log(cssTree.data) // Output: { language: 'css', relevance: 3 } // Use custom class prefix instead of default 'hljs-' const customTree = lowlight.highlight('python', 'print("Hello")', {prefix: 'code-'}) // Classes will be 'code-built_in' instead of 'hljs-built_in' ``` -------------------------------- ### Default and Named Exports in Underscore.js Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/js-modules/input.txt Defines default and named exports for utility functions in a JavaScript module. Use this for defining module interfaces. ```javascript export default function (obj) {}; ``` ```javascript export function each(obj, iterator, context) {}; ``` ```javascript export { each as forEach }; ``` ```javascript export function something() {}; ``` -------------------------------- ### Bash command to view last 10 lines of a log file Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/bash-no-numbers/input.txt This command is used to display the last 10 lines of the access.log file. Numbers are not highlighted in bash as their semantics are not strictly defined for command line parameters. ```bash $ tail -10 access.log ``` -------------------------------- ### HTTP POST Request with JSON Body Source: https://github.com/wooorm/lowlight/blob/main/test/fixture/http-default/output.txt A standard HTTP POST request structure including headers and a JSON-formatted body. ```http POST /task?id=1 HTTP/1.1 Host: example.org Content-Type: application/json; charset=utf-8 Content-Length: 19 {"status": "ok", "extended": true} ``` -------------------------------- ### lowlight.listLanguages - List Registered Languages Source: https://context7.com/wooorm/lowlight/llms.txt Returns an array of all registered language names (not including aliases). ```APIDOC ## lowlight.listLanguages - List Registered Languages ### Description Returns an array of all registered language names (not including aliases). ### Method `listLanguages(): string[] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import {createLowlight, common} from 'lowlight' const lowlight = createLowlight(common) console.log(lowlight.listLanguages()) // Output: ['arduino', 'bash', 'c', 'cpp', ...] ``` ### Response - **array** (string[]) - An array of registered language names. #### Success Response (200) - **array** (string[]) - Array of language names. #### Response Example ```json ["javascript", "css", "xml"] ``` ```