Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

lowlight

wooorm8.1mMIT3.3.0TypeScript support: included

Virtual syntax highlighting for virtual DOMs and non-HTML things

syntax, code, ast, virtual, dom, highlight, highlighting

readme

lowlight

Build Coverage Downloads Size

Virtual syntax highlighting for virtual DOMs and non-HTML things based on highlight.js.

Contents

What is this?

This package uses highlight.js for syntax highlighting and outputs objects (ASTs) instead of a string of HTML. It can support 190+ programming languages.

When should I use this?

This package is useful when you want to perform syntax highlighting in a place where serialized HTML wouldn’t work or wouldn’t work well. For example, you can use lowlight when you want to show code in a CLI by rendering to ANSI sequences, when you’re using virtual DOM frameworks (such as React or Preact) so that diffing can be performant, or when you’re working with ASTs (rehype).

You can use the similar refractor if you want to use Prism grammars instead. If you’re looking for a really good (but rather heavy) alternative, use starry-night.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install lowlight

In Deno with esm.sh:

import {all, common, createLowlight} from 'https://esm.sh/lowlight@3'

In browsers with esm.sh:

<script type="module">
  import {all, common, createLowlight} from 'https://esm.sh/lowlight@3?bundle'
</script>

Use

import {common, createLowlight} from 'lowlight'

const lowlight = createLowlight(common)

const tree = lowlight.highlight('js', '"use strict";')

console.dir(tree, {depth: undefined})

Yields:

{
  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}
}

API

This package exports the identifiers all, common, and createLowlight. There is no default export.

all

Map of all (±190) grammars (Record<string, LanguageFn>).

common

Map of common (37) grammars (Record<string, LanguageFn>).

createLowlight([grammars])

Create a lowlight instance.

Parameters
Returns

Lowlight (Lowlight).

lowlight.highlight(language, value[, options])

Highlight value (code) as language (name).

Parameters
  • language (string) — programming language name
  • value (string) — code to highlight
  • options (Options, optional) — configuration
Returns

Tree (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.

Example
import {common, createLowlight} from 'lowlight'

const lowlight = createLowlight(common)

console.log(lowlight.highlight('css', 'em { color: red }'))

Yields:

{type: 'root', children: [Array], data: {language: 'css', relevance: 3}}

lowlight.highlightAuto(value[, options])

Highlight value (code) and guess its programming language.

Parameters
  • value (string) — code to highlight
  • options (AutoOptions, optional) — configuration
Returns

Tree (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.

Example
import {common, createLowlight} from 'lowlight'

const lowlight = createLowlight(common)

console.log(lowlight.highlightAuto('"hello, " + name + "!"'))

Yields:

{type: 'root', children: [Array], data: {language: 'arduino', relevance: 2}}

lowlight.listLanguages()

List registered languages.

Returns

Names of registered language (Array<string>).

Example
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']

lowlight.register(grammars)

Register languages.

Signatures
  • register(name, grammar)
  • register(grammars)
Parameters
Returns

Nothing (undefined).

Example
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', '<em>Emphasis</em>'))

Yields:

{type: 'root', children: [Array], data: {language: 'html', relevance: 2}}

lowlight.registerAlias(aliases)

Register aliases.

Signatures
  • registerAlias(aliases)
  • registerAlias(name, alias)
Parameters
  • aliases (Record<string, Array<string> | string>) — map of programming language names to one or more aliases
  • name (string) — programming language name
  • alias (Array<string> | string) — one or more aliases for the programming language
Returns

Nothing (undefined).

Example
import {createLowlight} from 'lowlight'
import markdown from 'highlight.js/lib/languages/markdown'

const lowlight = createLowlight()

lowlight.register({markdown})

// lowlight.highlight('mdown', '<em>Emphasis</em>')
// ^ would throw: Error: Unknown language: `mdown` is not registered

lowlight.registerAlias({markdown: ['mdown', 'mkdn', 'mdwn', 'ron']})
lowlight.highlight('mdown', '<em>Emphasis</em>')
// ^ Works!

lowlight.registered(aliasOrlanguage)

Check whether an alias or name is registered.

Parameters
  • aliasOrlanguage (string) — name of a language or alias for one
Returns

Whether aliasOrName is registered (boolean).

Example
import {createLowlight} from 'lowlight'
import javascript from 'highlight.js/lib/languages/javascript'

const lowlight = createLowlight({javascript})

console.log(lowlight.registered('funkyscript')) // => `false`

lowlight.registerAlias({javascript: 'funkyscript'})
console.log(lowlight.registered('funkyscript')) // => `true`

AutoOptions

Configuration for highlightAuto (TypeScript type).

Fields
  • prefix (string, default: 'hljs-') — class prefix
  • subset (Array<string>, default: all registered languages) — list of allowed languages

LanguageFn

Highlight.js grammar (TypeScript type).

Type
type {LanguageFn} from 'highlight.js'

Options

Configuration for highlight (TypeScript type).

Fields
  • prefix (string, default: 'hljs-') — class prefix

Examples

Example: serializing hast as html

hast trees as returned by lowlight can be serialized with hast-util-to-html:

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))

Yields:

<span class="hljs-meta">"use strict"</span>;

Example: turning hast into preact, react, etc

hast trees as returned by lowlight can be turned into nodes of any framework that supports JSX, such as preact, react, solid, svelte, vue, and more, with hast-util-to-jsx-runtime:

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}))

Yields:

{
  $$typeof: Symbol(react.element),
  type: Symbol(react.fragment),
  key: null,
  ref: null,
  props: {children: [[Object], ';']},
  _owner: null,
  _store: {}
}

Types

This package is fully typed with TypeScript. It exports the additional types AutoOptions, LanguageFn, and Options.

It also registers root.data with @types/hast. If you’re working with the data fields, make sure to import this package somewhere in your types, as that registers the new fields on the file.

/**
 * @import {Root} from 'hast'
 * @import {} from 'lowlight'
 */

import {VFile} from 'vfile'

/** @type {Root} */
const root = {type: 'root', children: []}

console.log(root.data?.language) //=> TS now knows that this is a `string?`.

Data

If you’re using createLowlight(), no syntaxes are included yet. You can import all or common and pass them, such as with createLowlight(all). Checked syntaxes are included in common. All syntaxes are included in all.

You can also manually import syntaxes from highlight.js/lib/languages/xxx, where xxx is the name, such as 'highlight.js/lib/languages/wasm'.

  • <input disabled="" type="checkbox"> 1c — 1C:Enterprise
  • <input disabled="" type="checkbox"> abnf — Augmented Backus-Naur Form
  • <input disabled="" type="checkbox"> accesslog — Apache Access Log
  • <input disabled="" type="checkbox"> actionscript (as) — ActionScript
  • <input disabled="" type="checkbox"> ada — Ada
  • <input disabled="" type="checkbox"> angelscript (asc) — AngelScript
  • <input disabled="" type="checkbox"> apache (apacheconf) — Apache config
  • <input disabled="" type="checkbox"> applescript (osascript) — AppleScript
  • <input disabled="" type="checkbox"> arcade — ArcGIS Arcade
  • <input checked="" disabled="" type="checkbox"> arduino (ino) — Arduino
  • <input disabled="" type="checkbox"> armasm (arm) — ARM Assembly
  • <input disabled="" type="checkbox"> asciidoc (adoc) — AsciiDoc
  • <input disabled="" type="checkbox"> aspectj — AspectJ
  • <input disabled="" type="checkbox"> autohotkey (ahk) — AutoHotkey
  • <input disabled="" type="checkbox"> autoit — AutoIt
  • <input disabled="" type="checkbox"> avrasm — AVR Assembly
  • <input disabled="" type="checkbox"> awk — Awk
  • <input disabled="" type="checkbox"> axapta (x++) — X++
  • <input checked="" disabled="" type="checkbox"> bash (sh, zsh) — Bash
  • <input disabled="" type="checkbox"> basic — BASIC
  • <input disabled="" type="checkbox"> bnf — Backus–Naur Form
  • <input disabled="" type="checkbox"> brainfuck (bf) — Brainfuck
  • <input checked="" disabled="" type="checkbox"> c (h) — C
  • <input disabled="" type="checkbox"> cal — C/AL
  • <input disabled="" type="checkbox"> capnproto (capnp) — Cap’n Proto
  • <input disabled="" type="checkbox"> ceylon — Ceylon
  • <input disabled="" type="checkbox"> clean (icl, dcl) — Clean
  • <input disabled="" type="checkbox"> clojure (clj, edn) — Clojure
  • <input disabled="" type="checkbox"> clojure-repl — Clojure REPL
  • <input disabled="" type="checkbox"> cmake (cmake.in) — CMake
  • <input disabled="" type="checkbox"> coffeescript (coffee, cson, iced) — CoffeeScript
  • <input disabled="" type="checkbox"> coq — Coq
  • <input disabled="" type="checkbox"> cos (cls) — Caché Object Script
  • <input checked="" disabled="" type="checkbox"> cpp (cc, c++, h++, hpp, hh, hxx, cxx) — C++
  • <input disabled="" type="checkbox"> crmsh (crm, pcmk) — crmsh
  • <input disabled="" type="checkbox"> crystal (cr) — Crystal
  • <input checked="" disabled="" type="checkbox"> csharp (cs, c#) — C#
  • <input disabled="" type="checkbox"> csp — CSP
  • <input checked="" disabled="" type="checkbox"> css — CSS
  • <input disabled="" type="checkbox"> d — D
  • <input disabled="" type="checkbox"> dart — Dart
  • <input disabled="" type="checkbox"> delphi (dpr, dfm, pas, pascal) — Delphi
  • <input checked="" disabled="" type="checkbox"> diff (patch) — Diff
  • <input disabled="" type="checkbox"> django (jinja) — Django
  • <input disabled="" type="checkbox"> dns (bind, zone) — DNS Zone
  • <input disabled="" type="checkbox"> dockerfile (docker) — Dockerfile
  • <input disabled="" type="checkbox"> dos (bat, cmd) — Batch file (DOS)
  • <input disabled="" type="checkbox"> dsconfig — undefined
  • <input disabled="" type="checkbox"> dts — Device Tree
  • <input disabled="" type="checkbox"> dust (dst) — Dust
  • <input disabled="" type="checkbox"> ebnf — Extended Backus-Naur Form
  • <input disabled="" type="checkbox"> elixir (ex, exs) — Elixir
  • <input disabled="" type="checkbox"> elm — Elm
  • <input disabled="" type="checkbox"> erb — ERB
  • <input disabled="" type="checkbox"> erlang (erl) — Erlang
  • <input disabled="" type="checkbox"> erlang-repl — Erlang REPL
  • <input disabled="" type="checkbox"> excel (xlsx, xls) — Excel formulae
  • <input disabled="" type="checkbox"> fix — FIX
  • <input disabled="" type="checkbox"> flix — Flix
  • <input disabled="" type="checkbox"> fortran (f90, f95) — Fortran
  • <input disabled="" type="checkbox"> fsharp (fs, f#) — F#
  • <input disabled="" type="checkbox"> gams (gms) — GAMS
  • <input disabled="" type="checkbox"> gauss (gss) — GAUSS
  • <input disabled="" type="checkbox"> gcode (nc) — G-code (ISO 6983)
  • <input disabled="" type="checkbox"> gherkin (feature) — Gherkin
  • <input disabled="" type="checkbox"> glsl — GLSL
  • <input disabled="" type="checkbox"> gml — GML
  • <input checked="" disabled="" type="checkbox"> go (golang) — Go
  • <input disabled="" type="checkbox"> golo — Golo
  • <input disabled="" type="checkbox"> gradle — Gradle
  • <input checked="" disabled="" type="checkbox"> graphql (gql) — GraphQL
  • <input disabled="" type="checkbox"> groovy — Groovy
  • <input disabled="" type="checkbox"> haml — HAML
  • <input disabled="" type="checkbox"> handlebars (hbs, html.hbs, html.handlebars, htmlbars) — Handlebars
  • <input disabled="" type="checkbox"> haskell (hs) — Haskell
  • <input disabled="" type="checkbox"> haxe (hx) — Haxe
  • <input disabled="" type="checkbox"> hsp — HSP
  • <input disabled="" type="checkbox"> http (https) — HTTP
  • <input disabled="" type="checkbox"> hy (hylang) — Hy
  • <input disabled="" type="checkbox"> inform7 (i7) — Inform 7
  • <input checked="" disabled="" type="checkbox"> ini (toml) — TOML, also INI
  • <input disabled="" type="checkbox"> irpf90 — IRPF90
  • <input disabled="" type="checkbox"> isbl — ISBL
  • <input checked="" disabled="" type="checkbox"> java (jsp) — Java
  • <input checked="" disabled="" type="checkbox"> javascript (js, jsx, mjs, cjs) — JavaScript
  • <input disabled="" type="checkbox"> jboss-cli (wildfly-cli) — JBoss CLI
  • <input checked="" disabled="" type="checkbox"> json (jsonc) — JSON
  • <input disabled="" type="checkbox"> julia — Julia
  • <input disabled="" type="checkbox"> julia-repl (jldoctest) — Julia REPL
  • <input checked="" disabled="" type="checkbox"> kotlin (kt, kts) — Kotlin
  • <input disabled="" type="checkbox"> lasso (ls, lassoscript) — Lasso
  • <input disabled="" type="checkbox"> latex (tex) — LaTeX
  • <input disabled="" type="checkbox"> ldif — LDIF
  • <input disabled="" type="checkbox"> leaf — Leaf
  • <input checked="" disabled="" type="checkbox"> less — Less
  • <input disabled="" type="checkbox"> lisp — Lisp
  • <input disabled="" type="checkbox"> livecodeserver — LiveCode
  • <input disabled="" type="checkbox"> livescript (ls) — LiveScript
  • <input disabled="" type="checkbox"> llvm — LLVM IR
  • <input disabled="" type="checkbox"> lsl — LSL (Linden Scripting Language)
  • <input checked="" disabled="" type="checkbox"> lua (pluto) — Lua
  • <input checked="" disabled="" type="checkbox"> makefile (mk, mak, make) — Makefile
  • <input checked="" disabled="" type="checkbox"> markdown (md, mkdown, mkd) — Markdown
  • <input disabled="" type="checkbox"> mathematica (mma, wl) — Mathematica
  • <input disabled="" type="checkbox"> matlab — Matlab
  • <input disabled="" type="checkbox"> maxima — Maxima
  • <input disabled="" type="checkbox"> mel — MEL
  • <input disabled="" type="checkbox"> mercury (m, moo) — Mercury
  • <input disabled="" type="checkbox"> mipsasm (mips) — MIPS Assembly
  • <input disabled="" type="checkbox"> mizar — Mizar
  • <input disabled="" type="checkbox"> mojolicious — Mojolicious
  • <input disabled="" type="checkbox"> monkey — Monkey
  • <input disabled="" type="checkbox"> moonscript (moon) — MoonScript
  • <input disabled="" type="checkbox"> n1ql — N1QL
  • <input disabled="" type="checkbox"> nestedtext (nt) — Nested Text
  • <input disabled="" type="checkbox"> nginx (nginxconf) — Nginx config
  • <input disabled="" type="checkbox"> nim — Nim
  • <input disabled="" type="checkbox"> nix (nixos) — Nix
  • <input disabled="" type="checkbox"> node-repl — Node REPL
  • <input disabled="" type="checkbox"> nsis — NSIS
  • <input checked="" disabled="" type="checkbox"> objectivec (mm, objc, obj-c, obj-c++, objective-c++) — Objective-C
  • <input disabled="" type="checkbox"> ocaml (ml) — OCaml
  • <input disabled="" type="checkbox"> openscad (scad) — OpenSCAD
  • <input disabled="" type="checkbox"> oxygene — Oxygene
  • <input disabled="" type="checkbox"> parser3 — Parser3
  • <input checked="" disabled="" type="checkbox"> perl (pl, pm) — Perl
  • <input disabled="" type="checkbox"> pf (pf.conf) — Packet Filter config
  • <input disabled="" type="checkbox"> pgsql (postgres, postgresql) — PostgreSQL
  • <input checked="" disabled="" type="checkbox"> php — undefined
  • <input checked="" disabled="" type="checkbox"> php-template — PHP template
  • <input checked="" disabled="" type="checkbox"> plaintext (text, txt) — Plain text
  • <input disabled="" type="checkbox"> pony — Pony
  • <input disabled="" type="checkbox"> powershell (pwsh, ps, ps1) — PowerShell
  • <input disabled="" type="checkbox"> processing (pde) — Processing
  • <input disabled="" type="checkbox"> profile — Python profiler
  • <input disabled="" type="checkbox"> prolog — Prolog
  • <input disabled="" type="checkbox"> properties — .properties
  • <input disabled="" type="checkbox"> protobuf (proto) — Protocol Buffers
  • <input disabled="" type="checkbox"> puppet (pp) — Puppet
  • <input disabled="" type="checkbox"> purebasic (pb, pbi) — PureBASIC
  • <input checked="" disabled="" type="checkbox"> python (py, gyp, ipython) — Python
  • <input checked="" disabled="" type="checkbox"> python-repl (pycon) — undefined
  • <input disabled="" type="checkbox"> q (k, kdb) — Q
  • <input disabled="" type="checkbox"> qml (qt) — QML
  • <input checked="" disabled="" type="checkbox"> r — R
  • <input disabled="" type="checkbox"> reasonml (re) — ReasonML
  • <input disabled="" type="checkbox"> rib — RenderMan RIB
  • <input disabled="" type="checkbox"> roboconf (graph, instances) — Roboconf
  • <input disabled="" type="checkbox"> routeros (mikrotik) — MikroTik RouterOS script
  • <input disabled="" type="checkbox"> rsl — RenderMan RSL
  • <input checked="" disabled="" type="checkbox"> ruby (rb, gemspec, podspec, thor, irb) — Ruby
  • <input disabled="" type="checkbox"> ruleslanguage — Oracle Rules Language
  • <input checked="" disabled="" type="checkbox"> rust (rs) — Rust
  • <input disabled="" type="checkbox"> sas — SAS
  • <input disabled="" type="checkbox"> scala — Scala
  • <input disabled="" type="checkbox"> scheme (scm) — Scheme
  • <input disabled="" type="checkbox"> scilab (sci) — Scilab
  • <input checked="" disabled="" type="checkbox"> scss — SCSS
  • <input checked="" disabled="" type="checkbox"> shell (console, shellsession) — Shell Session
  • <input disabled="" type="checkbox"> smali — Smali
  • <input disabled="" type="checkbox"> smalltalk (st) — Smalltalk
  • <input disabled="" type="checkbox"> sml (ml) — SML (Standard ML)
  • <input disabled="" type="checkbox"> sqf — SQF
  • <input checked="" disabled="" type="checkbox"> sql — SQL
  • <input disabled="" type="checkbox"> stan (stanfuncs) — Stan
  • <input disabled="" type="checkbox"> stata (do, ado) — Stata
  • <input disabled="" type="checkbox"> step21 (p21, step, stp) — STEP Part 21
  • <input disabled="" type="checkbox"> stylus (styl) — Stylus
  • <input disabled="" type="checkbox"> subunit — SubUnit
  • <input checked="" disabled="" type="checkbox"> swift — Swift
  • <input disabled="" type="checkbox"> taggerscript — Tagger Script
  • <input disabled="" type="checkbox"> tap — Test Anything Protocol
  • <input disabled="" type="checkbox"> tcl (tk) — Tcl
  • <input disabled="" type="checkbox"> thrift — Thrift
  • <input disabled="" type="checkbox"> tp — TP
  • <input disabled="" type="checkbox"> twig (craftcms) — Twig
  • <input checked="" disabled="" type="checkbox"> typescript (ts, tsx, mts, cts) — TypeScript
  • <input disabled="" type="checkbox"> vala — Vala
  • <input checked="" disabled="" type="checkbox"> vbnet (vb) — Visual Basic .NET
  • <input disabled="" type="checkbox"> vbscript (vbs) — VBScript
  • <input disabled="" type="checkbox"> vbscript-html — VBScript in HTML
  • <input disabled="" type="checkbox"> verilog (v, sv, svh) — Verilog
  • <input disabled="" type="checkbox"> vhdl — VHDL
  • <input disabled="" type="checkbox"> vim — Vim Script
  • <input checked="" disabled="" type="checkbox"> wasm — WebAssembly
  • <input disabled="" type="checkbox"> wren — Wren
  • <input disabled="" type="checkbox"> x86asm — Intel x86 Assembly
  • <input disabled="" type="checkbox"> xl (tao) — XL
  • <input checked="" disabled="" type="checkbox"> xml (html, xhtml, rss, atom, xjb, xsd, xsl, plist, wsf, svg) — HTML, XML
  • <input disabled="" type="checkbox"> xquery (xpath, xq, xqm) — XQuery
  • <input checked="" disabled="" type="checkbox"> yaml (yml) — YAML
  • <input disabled="" type="checkbox"> zephir (zep) — Zephir

CSS

lowlight does not inject CSS for the syntax highlighted code (because well, lowlight doesn’t have to be turned into HTML and might not run in a browser!). If you are in a browser, you can use any highlight.js theme. For example, to get GitHub Dark from cdnjs:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.0/styles/github-dark.min.css">

Compatibility

This package is compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, lowlight@^3, compatible with Node.js 16.

Security

This package is safe.

Projects

Contribute

Yes please! See How to Contribute to Open Source.

License

MIT © Titus Wormer

changelog