Virtual syntax highlighting for virtual DOMs and non-HTML things based on
highlight.js.
- What is this?
- When should I use this?
- Install
- Use
- API
- Examples
- Types
- Data
- CSS
- Compatibility
- Security
- Related
- Projects
- Contribute
- License
This package uses 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 if you want to use Prism
grammars instead.
If youβre looking for a really good (but rather heavy) alternative, use
starry-night.
This package is ESM only. In Node.js (version 16+), install with npm:
npm install lowlightIn 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>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}
}This package exports the identifiers all,
common, and
createLowlight.
There is no default export.
Map of all (Β±190) grammars (Record<string, LanguageFn>).
Map of common (37) grammars (Record<string, LanguageFn>).
Create a lowlight instance.
grammars(Record<string, LanguageFn>, optional) β grammars to add
Lowlight (Lowlight).
Highlight value (code) as language (name).
language(string) β programming language namevalue(string) β code to highlightoptions(Options, optional) β configuration
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.
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}}Highlight value (code) and guess its programming language.
value(string) β code to highlightoptions(AutoOptions, optional) β configuration
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.
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}}List registered languages.
Names of registered language (Array<string>).
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.
register(name, grammar)register(grammars)
name(string) β programming language namegrammar(LanguageFn) β grammargrammars(Record<string, LanguageFn>, optional) β grammars
Nothing (undefined).
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}}Register aliases.
registerAlias(aliases)registerAlias(name, alias)
aliases(Record<string, Array<string> | string>) β map of programming language names to one or more aliasesname(string) β programming language namealias(Array<string> | string) β one or more aliases for the programming language
Nothing (undefined).
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!Check whether an alias or name is registered.
aliasOrlanguage(string) β name of a language or alias for one
Whether aliasOrName is registered (boolean).
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).
prefix(string, default:'hljs-') β class prefixsubset(Array<string>, default: all registered languages) β list of allowed languages
Highlight.js grammar (TypeScript type).
type {LanguageFn} from 'highlight.js'Configuration for highlight (TypeScript type).
prefix(string, default:'hljs-') β class prefix
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>;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: {}
}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?`.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'.
-
1cβ 1C:Enterprise -
abnfβ Augmented Backus-Naur Form -
accesslogβ Apache Access Log -
actionscript(as) β ActionScript -
adaβ Ada -
angelscript(asc) β AngelScript -
apache(apacheconf) β Apache config -
applescript(osascript) β AppleScript -
arcadeβ ArcGIS Arcade -
arduino(ino) β Arduino -
armasm(arm) β ARM Assembly -
asciidoc(adoc) β AsciiDoc -
aspectjβ AspectJ -
autohotkey(ahk) β AutoHotkey -
autoitβ AutoIt -
avrasmβ AVR Assembly -
awkβ Awk -
axapta(x++) β X++ -
bash(sh,zsh) β Bash -
basicβ BASIC -
bnfβ BackusβNaur Form -
brainfuck(bf) β Brainfuck -
c(h) β C -
calβ C/AL -
capnproto(capnp) β Capβn Proto -
ceylonβ Ceylon -
clean(icl,dcl) β Clean -
clojure(clj,edn) β Clojure -
clojure-replβ Clojure REPL -
cmake(cmake.in) β CMake -
coffeescript(coffee,cson,iced) β CoffeeScript -
coqβ Coq -
cos(cls) β CachΓ© Object Script -
cpp(cc,c++,h++,hpp,hh,hxx,cxx) β C++ -
crmsh(crm,pcmk) β crmsh -
crystal(cr) β Crystal -
csharp(cs,c#) β C# -
cspβ CSP -
cssβ CSS -
dβ D -
dartβ Dart -
delphi(dpr,dfm,pas,pascal) β Delphi -
diff(patch) β Diff -
django(jinja) β Django -
dns(bind,zone) β DNS Zone -
dockerfile(docker) β Dockerfile -
dos(bat,cmd) β Batch file (DOS) -
dsconfigβ undefined -
dtsβ Device Tree -
dust(dst) β Dust -
ebnfβ Extended Backus-Naur Form -
elixir(ex,exs) β Elixir -
elmβ Elm -
erbβ ERB -
erlang(erl) β Erlang -
erlang-replβ Erlang REPL -
excel(xlsx,xls) β Excel formulae -
fixβ FIX -
flixβ Flix -
fortran(f90,f95) β Fortran -
fsharp(fs,f#) β F# -
gams(gms) β GAMS -
gauss(gss) β GAUSS -
gcode(nc) β G-code (ISO 6983) -
gherkin(feature) β Gherkin -
glslβ GLSL -
gmlβ GML -
go(golang) β Go -
goloβ Golo -
gradleβ Gradle -
graphql(gql) β GraphQL -
groovyβ Groovy -
hamlβ HAML -
handlebars(hbs,html.hbs,html.handlebars,htmlbars) β Handlebars -
haskell(hs) β Haskell -
haxe(hx) β Haxe -
hspβ HSP -
http(https) β HTTP -
hy(hylang) β Hy -
inform7(i7) β Inform 7 -
ini(toml) β TOML, also INI -
irpf90β IRPF90 -
isblβ ISBL -
java(jsp) β Java -
javascript(js,jsx,mjs,cjs) β JavaScript -
jboss-cli(wildfly-cli) β JBoss CLI -
json(jsonc) β JSON -
juliaβ Julia -
julia-repl(jldoctest) β Julia REPL -
kotlin(kt,kts) β Kotlin -
lasso(ls,lassoscript) β Lasso -
latex(tex) β LaTeX -
ldifβ LDIF -
leafβ Leaf -
lessβ Less -
lispβ Lisp -
livecodeserverβ LiveCode -
livescript(ls) β LiveScript -
llvmβ LLVM IR -
lslβ LSL (Linden Scripting Language) -
lua(pluto) β Lua -
makefile(mk,mak,make) β Makefile -
markdown(md,mkdown,mkd) β Markdown -
mathematica(mma,wl) β Mathematica -
matlabβ Matlab -
maximaβ Maxima -
melβ MEL -
mercury(m,moo) β Mercury -
mipsasm(mips) β MIPS Assembly -
mizarβ Mizar -
mojoliciousβ Mojolicious -
monkeyβ Monkey -
moonscript(moon) β MoonScript -
n1qlβ N1QL -
nestedtext(nt) β Nested Text -
nginx(nginxconf) β Nginx config -
nimβ Nim -
nix(nixos) β Nix -
node-replβ Node REPL -
nsisβ NSIS -
objectivec(mm,objc,obj-c,obj-c++,objective-c++) β Objective-C -
ocaml(ml) β OCaml -
openscad(scad) β OpenSCAD -
oxygeneβ Oxygene -
parser3β Parser3 -
perl(pl,pm) β Perl -
pf(pf.conf) β Packet Filter config -
pgsql(postgres,postgresql) β PostgreSQL -
phpβ undefined -
php-templateβ PHP template -
plaintext(text,txt) β Plain text -
ponyβ Pony -
powershell(pwsh,ps,ps1) β PowerShell -
processing(pde) β Processing -
profileβ Python profiler -
prologβ Prolog -
propertiesβ .properties -
protobuf(proto) β Protocol Buffers -
puppet(pp) β Puppet -
purebasic(pb,pbi) β PureBASIC -
python(py,gyp,ipython) β Python -
python-repl(pycon) β undefined -
q(k,kdb) β Q -
qml(qt) β QML -
rβ R -
reasonml(re) β ReasonML -
ribβ RenderMan RIB -
roboconf(graph,instances) β Roboconf -
routeros(mikrotik) β MikroTik RouterOS script -
rslβ RenderMan RSL -
ruby(rb,gemspec,podspec,thor,irb) β Ruby -
ruleslanguageβ Oracle Rules Language -
rust(rs) β Rust -
sasβ SAS -
scalaβ Scala -
scheme(scm) β Scheme -
scilab(sci) β Scilab -
scssβ SCSS -
shell(console,shellsession) β Shell Session -
smaliβ Smali -
smalltalk(st) β Smalltalk -
sml(ml) β SML (Standard ML) -
sqfβ SQF -
sqlβ SQL -
stan(stanfuncs) β Stan -
stata(do,ado) β Stata -
step21(p21,step,stp) β STEP Part 21 -
stylus(styl) β Stylus -
subunitβ SubUnit -
swiftβ Swift -
taggerscriptβ Tagger Script -
tapβ Test Anything Protocol -
tcl(tk) β Tcl -
thriftβ Thrift -
tpβ TP -
twig(craftcms) β Twig -
typescript(ts,tsx,mts,cts) β TypeScript -
valaβ Vala -
vbnet(vb) β Visual Basic .NET -
vbscript(vbs) β VBScript -
vbscript-htmlβ VBScript in HTML -
verilog(v,sv,svh) β Verilog -
vhdlβ VHDL -
vimβ Vim Script -
wasmβ WebAssembly -
wrenβ Wren -
x86asmβ Intel x86 Assembly -
xl(tao) β XL -
xml(html,xhtml,rss,atom,xjb,xsd,xsl,plist,wsf,svg) β HTML, XML -
xquery(xpath,xq,xqm) β XQuery -
yaml(yml) β YAML -
zephir(zep) β Zephir
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">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β the same as lowlight but with Prismstarry-nightβ similar but like GitHub and really good
emphasizeβ syntax highlighting in ANSI (for the terminal)react-lowlightβ syntax highlighter for Reactreact-syntax-highlighterβ React component for syntax highlightingrehype-highlightβ rehype plugin to highlight code blocksjstransformer-lowlightβ syntax highlighting for JSTransformers and Pug
Yes please! See How to Contribute to Open Source.
MIT Β© Titus Wormer