Virtual syntax highlighting for virtual DOMs and non-HTML things
npm install lowlight[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
Virtual syntax highlighting for virtual DOMs and non-HTML things based on
[highlight.js][highlight-js].
* What is this?
* When should I use this?
* Install
* Use
* API
* all
* common
* [createLowlight([grammars])](#createlowlightgrammars)
* [lowlight.highlight(language, value[, options])](#lowlighthighlightlanguage-value-options)
* [lowlight.highlightAuto(value[, options])](#lowlighthighlightautovalue-options)
* lowlight.listLanguages()
* lowlight.register(grammars)
* lowlight.registerAlias(aliases)
* lowlight.registered(aliasOrlanguage)
* AutoOptions
* LanguageFn
* Options
* Examples
* Example: serializing hast as html
* Example: turning hast into preact, react, etc
* Types
* Data
* CSS
* Compatibility
* Security
* Related
* Projects
* Contribute
* License
This package uses [highlight.js][highlight-js] for syntax highlighting and
outputs objects (ASTs) instead of a string of HTML.
It can support 190+ programming languages.
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][refractor] if you want to use [Prism][]
grammars instead.
If you’re looking for a really good (but rather heavy) alternative, use
[starry-night][starry-night].
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
``sh`
npm install lowlight
In Deno with [esm.sh][esmsh]:
`js`
import {all, common, createLowlight} from 'https://esm.sh/lowlight@3'
In browsers with [esm.sh][esmsh]:
`html`
`js
import {common, createLowlight} from 'lowlight'
const lowlight = createLowlight(common)
const tree = lowlight.highlight('js', '"use strict";')
console.dir(tree, {depth: undefined})
`
Yields:
`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}
}
This package exports the identifiers [all][api-all],common
[][api-common], andcreateLowlight
[][api-create-lowlight].
There is no default export.
Map of all (±190) grammars ([Record][api-language-fn]).
Map of common (37) grammars ([Record][api-language-fn]).
Create a lowlight instance.
###### Parameters
* grammars ([Record][api-language-fn], optional)
— grammars to add
###### Returns
Lowlight (Lowlight).
Highlight value (code) as language (name).
###### Parameters
* language (string)value
— programming language [name][names]
* (string)options
— code to highlight
* ([Options][api-options], optional)
— configuration
###### Returns
Tree ([Root][hast-root]); with the following data fields: languagestring
(), detected programming language name; relevance (number), how
sure lowlight is that the given code is in the language.
###### Example
`js
import {common, createLowlight} from 'lowlight'
const lowlight = createLowlight(common)
console.log(lowlight.highlight('css', 'em { color: red }'))
`
Yields:
`js`
{type: 'root', children: [Array], data: {language: 'css', relevance: 3}}
Highlight value (code) and guess its programming language.
###### Parameters
* value (string)options
— code to highlight
* ([AutoOptions][api-auto-options], optional)
— configuration
###### Returns
Tree ([Root][hast-root]); with the following data fields: languagestring
(), detected programming language name; relevance (number), how
sure lowlight is that the given code is in the language.
###### Example
`js
import {common, createLowlight} from 'lowlight'
const lowlight = createLowlight(common)
console.log(lowlight.highlightAuto('"hello, " + name + "!"'))
`
Yields:
`js`
{type: 'root', children: [Array], data: {language: 'arduino', relevance: 2}}
List registered languages.
###### Returns
[Names][] of registered language (Array).
###### Example
`js
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']
`
Register languages.
###### Signatures
* register(name, grammar)register(grammars)
*
###### Parameters
* name (string)grammar
— programming language [name][names]
* ([LanguageFn][api-language-fn])grammars
— grammar
* ([Record][api-language-fn], optional)
— grammars
###### Returns
Nothing (undefined).
###### Example
`js
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'))
Yields:
`js`
{type: 'root', children: [Array], data: {language: 'html', relevance: 2}}
Register aliases.
###### Signatures
* registerAlias(aliases)registerAlias(name, alias)
*
###### Parameters
* aliases (Record)name
— map of programming language [names][] to one or more aliases
* (string)alias
— programming language [name][names]
* (Array)
— one or more aliases for the programming language
###### Returns
Nothing (undefined).
###### Example
`js
import {createLowlight} from 'lowlight'
import markdown from 'highlight.js/lib/languages/markdown'
const lowlight = createLowlight()
lowlight.register({markdown})
// lowlight.highlight('mdown', 'Emphasis')
// ^ would throw: Error: Unknown language: mdown is not registered
lowlight.registerAlias({markdown: ['mdown', 'mkdn', 'mdwn', 'ron']})
lowlight.highlight('mdown', 'Emphasis')
// ^ Works!
`
Check whether an alias or name is registered.
###### Parameters
* aliasOrlanguage (string)
— [name][names] of a language or alias for one
###### Returns
Whether aliasOrName is registered (boolean).
###### Example
`js
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`
Configuration for highlightAuto (TypeScript type).
###### Fields
* prefix (string, default: 'hljs-')subset
— class prefix
* (Array, default: all registered languages)
— list of allowed languages
Highlight.js grammar (TypeScript type).
###### Type
`ts`
type {LanguageFn} from 'highlight.js'
Configuration for highlight (TypeScript type).
###### Fields
* prefix (string, default: 'hljs-')
— class prefix
hast trees as returned by lowlight can be serialized with
[hast-util-to-html][hast-util-to-html]:
`js
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:
`html`
;
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][hast-util-to-jsx-runtime]:
`js
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:
`js`
{
$$typeof: Symbol(react.element),
type: Symbol(react.fragment),
key: null,
ref: null,
props: {children: [[Object], ';']},
_owner: null,
_store: {}
}
This package is fully typed with [TypeScript][].
It exports the additional types
[AutoOptions][api-auto-options],LanguageFn
[][api-language-fn], andOptions
[][api-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.
`js
/**
* @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?.`
If you’re using createLowlight(), no syntaxes are included yet.all
You can import or common and pass them, such as withcreateLowlight(all).common
Checked syntaxes are included in .all
All syntaxes are included in .
You can also manually import syntaxes from highlight.js/lib/languages/xxx,xxx
where is the name, such as 'highlight.js/lib/languages/wasm'.
* [ ] 1c — 1C:Enterpriseabnf
* [ ] — Augmented Backus-Naur Formaccesslog
* [ ] — Apache Access Logactionscript
* [ ] (as) — ActionScriptada
* [ ] — Adaangelscript
* [ ] (asc) — AngelScriptapache
* [ ] (apacheconf) — Apache configapplescript
* [ ] (osascript) — AppleScriptarcade
* [ ] — ArcGIS Arcadearduino
* [x] (ino) — Arduinoarmasm
* [ ] (arm) — ARM Assemblyasciidoc
* [ ] (adoc) — AsciiDocaspectj
* [ ] — AspectJautohotkey
* [ ] (ahk) — AutoHotkeyautoit
* [ ] — AutoItavrasm
* [ ] — AVR Assemblyawk
* [ ] — Awkaxapta
* [ ] (x++) — X++bash
* [x] (sh, zsh) — Bashbasic
* [ ] — BASICbnf
* [ ] — Backus–Naur Formbrainfuck
* [ ] (bf) — Brainfuckc
* [x] (h) — Ccal
* [ ] — C/ALcapnproto
* [ ] (capnp) — Cap’n Protoceylon
* [ ] — Ceylonclean
* [ ] (icl, dcl) — Cleanclojure
* [ ] (clj, edn) — Clojureclojure-repl
* [ ] — Clojure REPLcmake
* [ ] (cmake.in) — CMakecoffeescript
* [ ] (coffee, cson, iced) — CoffeeScriptcoq
* [ ] — Coqcos
* [ ] (cls) — Caché Object Scriptcpp
* [x] (cc, c++, h++, hpp, hh, hxx, cxx) — C++crmsh
* [ ] (crm, pcmk) — crmshcrystal
* [ ] (cr) — Crystalcsharp
* [x] (cs, c#) — C#csp
* [ ] — CSPcss
* [x] — CSSd
* [ ] — Ddart
* [ ] — Dartdelphi
* [ ] (dpr, dfm, pas, pascal) — Delphidiff
* [x] (patch) — Diffdjango
* [ ] (jinja) — Djangodns
* [ ] (bind, zone) — DNS Zonedockerfile
* [ ] (docker) — Dockerfiledos
* [ ] (bat, cmd) — Batch file (DOS)dsconfig
* [ ] — undefineddts
* [ ] — Device Treedust
* [ ] (dst) — Dustebnf
* [ ] — Extended Backus-Naur Formelixir
* [ ] (ex, exs) — Elixirelm
* [ ] — Elmerb
* [ ] — ERBerlang
* [ ] (erl) — Erlangerlang-repl
* [ ] — Erlang REPLexcel
* [ ] (xlsx, xls) — Excel formulaefix
* [ ] — FIXflix
* [ ] — Flixfortran
* [ ] (f90, f95) — Fortranfsharp
* [ ] (fs, f#) — F#gams
* [ ] (gms) — GAMSgauss
* [ ] (gss) — GAUSSgcode
* [ ] (nc) — G-code (ISO 6983)gherkin
* [ ] (feature) — Gherkinglsl
* [ ] — GLSLgml
* [ ] — GMLgo
* [x] (golang) — Gogolo
* [ ] — Gologradle
* [ ] — Gradlegraphql
* [x] (gql) — GraphQLgroovy
* [ ] — Groovyhaml
* [ ] — HAMLhandlebars
* [ ] (hbs, html.hbs, html.handlebars, htmlbars) — Handlebarshaskell
* [ ] (hs) — Haskellhaxe
* [ ] (hx) — Haxehsp
* [ ] — HSPhttp
* [ ] (https) — HTTPhy
* [ ] (hylang) — Hyinform7
* [ ] (i7) — Inform 7ini
* [x] (toml) — TOML, also INIirpf90
* [ ] — IRPF90isbl
* [ ] — ISBLjava
* [x] (jsp) — Javajavascript
* [x] (js, jsx, mjs, cjs) — JavaScriptjboss-cli
* [ ] (wildfly-cli) — JBoss CLIjson
* [x] (jsonc) — JSONjulia
* [ ] — Juliajulia-repl
* [ ] (jldoctest) — Julia REPLkotlin
* [x] (kt, kts) — Kotlinlasso
* [ ] (ls, lassoscript) — Lassolatex
* [ ] (tex) — LaTeXldif
* [ ] — LDIFleaf
* [ ] — Leafless
* [x] — Lesslisp
* [ ] — Lisplivecodeserver
* [ ] — LiveCodelivescript
* [ ] (ls) — LiveScriptllvm
* [ ] — LLVM IRlsl
* [ ] — LSL (Linden Scripting Language)lua
* [x] (pluto) — Luamakefile
* [x] (mk, mak, make) — Makefilemarkdown
* [x] (md, mkdown, mkd) — Markdownmathematica
* [ ] (mma, wl) — Mathematicamatlab
* [ ] — Matlabmaxima
* [ ] — Maximamel
* [ ] — MELmercury
* [ ] (m, moo) — Mercurymipsasm
* [ ] (mips) — MIPS Assemblymizar
* [ ] — Mizarmojolicious
* [ ] — Mojoliciousmonkey
* [ ] — Monkeymoonscript
* [ ] (moon) — MoonScriptn1ql
* [ ] — N1QLnestedtext
* [ ] (nt) — Nested Textnginx
* [ ] (nginxconf) — Nginx confignim
* [ ] — Nimnix
* [ ] (nixos) — Nixnode-repl
* [ ] — Node REPLnsis
* [ ] — NSISobjectivec
* [x] (mm, objc, obj-c, obj-c++, objective-c++) — Objective-Cocaml
* [ ] (ml) — OCamlopenscad
* [ ] (scad) — OpenSCADoxygene
* [ ] — Oxygeneparser3
* [ ] — Parser3perl
* [x] (pl, pm) — Perlpf
* [ ] (pf.conf) — Packet Filter configpgsql
* [ ] (postgres, postgresql) — PostgreSQLphp
* [x] — undefinedphp-template
* [x] — PHP templateplaintext
* [x] (text, txt) — Plain textpony
* [ ] — Ponypowershell
* [ ] (pwsh, ps, ps1) — PowerShellprocessing
* [ ] (pde) — Processingprofile
* [ ] — Python profilerprolog
* [ ] — Prologproperties
* [ ] — .propertiesprotobuf
* [ ] (proto) — Protocol Bufferspuppet
* [ ] (pp) — Puppetpurebasic
* [ ] (pb, pbi) — PureBASICpython
* [x] (py, gyp, ipython) — Pythonpython-repl
* [x] (pycon) — undefinedq
* [ ] (k, kdb) — Qqml
* [ ] (qt) — QMLr
* [x] — Rreasonml
* [ ] (re) — ReasonMLrib
* [ ] — RenderMan RIBroboconf
* [ ] (graph, instances) — Roboconfrouteros
* [ ] (mikrotik) — MikroTik RouterOS scriptrsl
* [ ] — RenderMan RSLruby
* [x] (rb, gemspec, podspec, thor, irb) — Rubyruleslanguage
* [ ] — Oracle Rules Languagerust
* [x] (rs) — Rustsas
* [ ] — SASscala
* [ ] — Scalascheme
* [ ] (scm) — Schemescilab
* [ ] (sci) — Scilabscss
* [x] — SCSSshell
* [x] (console, shellsession) — Shell Sessionsmali
* [ ] — Smalismalltalk
* [ ] (st) — Smalltalksml
* [ ] (ml) — SML (Standard ML)sqf
* [ ] — SQFsql
* [x] — SQLstan
* [ ] (stanfuncs) — Stanstata
* [ ] (do, ado) — Statastep21
* [ ] (p21, step, stp) — STEP Part 21stylus
* [ ] (styl) — Stylussubunit
* [ ] — SubUnitswift
* [x] — Swifttaggerscript
* [ ] — Tagger Scripttap
* [ ] — Test Anything Protocoltcl
* [ ] (tk) — Tclthrift
* [ ] — Thrifttp
* [ ] — TPtwig
* [ ] (craftcms) — Twigtypescript
* [x] (ts, tsx, mts, cts) — TypeScriptvala
* [ ] — Valavbnet
* [x] (vb) — Visual Basic .NETvbscript
* [ ] (vbs) — VBScriptvbscript-html
* [ ] — VBScript in HTMLverilog
* [ ] (v, sv, svh) — Verilogvhdl
* [ ] — VHDLvim
* [ ] — Vim Scriptwasm
* [x] — WebAssemblywren
* [ ] — Wrenx86asm
* [ ] — Intel x86 Assemblyxl
* [ ] (tao) — XLxml
* [x] (html, xhtml, rss, atom, xjb, xsd, xsl, plist, wsf, svg) — HTML, XMLxquery
* [ ] (xpath, xq, xqm) — XQueryyaml
* [x] (yml) — YAMLzephir
* [ ] (zep) — Zephir
lowlight does not inject CSS for the syntax highlighted code (because well,highlight.js
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 theme.
For example, to get GitHub Dark from cdnjs:
`html`
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.
This package is safe.
* [refractor][refractor]starry-night
— the same as lowlight but with [Prism][]
* [][starry-night]
— similar but like GitHub and really good
* emphasize
— syntax highlighting in ANSI (for the terminal)
* react-lowlight
— syntax highlighter for [React][]
* react-syntax-highlighter
— [React][] component for syntax highlighting
* rehype-highlight
— rehype plugin to highlight code
blocks
* jstransformer-lowlight`
— syntax highlighting for JSTransformers
and Pug
Yes please!
See [How to Contribute to Open Source][contribute].
[MIT][license] © [Titus Wormer][author]
[build-badge]: https://github.com/wooorm/lowlight/workflows/main/badge.svg
[build]: https://github.com/wooorm/lowlight/actions
[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/lowlight.svg
[coverage]: https://codecov.io/github/wooorm/lowlight
[downloads-badge]: https://img.shields.io/npm/dm/lowlight.svg
[downloads]: https://www.npmjs.com/package/lowlight
[size-badge]: https://img.shields.io/bundlephobia/minzip/lowlight.svg
[size]: https://bundlephobia.com/result?p=lowlight
[npm]: https://docs.npmjs.com/cli/install
[esmsh]: https://esm.sh
[license]: license
[author]: https://wooorm.com
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[typescript]: https://www.typescriptlang.org
[contribute]: https://opensource.guide/how-to-contribute/
[hast-root]: https://github.com/syntax-tree/hast#root
[highlight-js]: https://github.com/highlightjs/highlight.js
[names]: https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md
[react]: https://facebook.github.io/react/
[prism]: https://github.com/PrismJS/prism
[refractor]: https://github.com/wooorm/refractor
[starry-night]: https://github.com/wooorm/starry-night
[hast-util-to-html]: https://github.com/syntax-tree/hast-util-to-html
[hast-util-to-jsx-runtime]: https://github.com/syntax-tree/hast-util-to-jsx-runtime
[api-all]: #all
[api-auto-options]: #autooptions
[api-common]: #common
[api-create-lowlight]: #createlowlightgrammars
[api-language-fn]: #languagefn
[api-options]: #options