Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork31
Virtual syntax highlighting for virtual DOMs and non-HTML things
License
wooorm/lowlight
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Virtual syntax highlighting for virtual DOMs and non-HTML things based onhighlight.js.
- What is this?
- When should I use this?
- Install
- Use
- API
- Examples
- Types
- Data
- CSS
- Compatibility
- Security
- Related
- Projects
- Contribute
- License
This package useshighlight.js for syntax highlighting andoutputs 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 placewhere 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 byrendering to ANSI sequences, when you’re using virtual DOM frameworks (such asReact or Preact) so that diffing can be performant, or when you’re working withASTs (rehype).
You can use the similarrefractor if you want to usePrismgrammars instead.If you’re looking for areally good (but rather heavy) alternative, usestarry-night.
This package isESM only.In Node.js (version 16+), install withnpm:
npm install lowlight
In Deno withesm.sh:
import{all,common,createLowlight}from'https://esm.sh/lowlight@3'
In browsers withesm.sh:
<scripttype="module">import{all,common,createLowlight}from'https://esm.sh/lowlight@3?bundle'</script>
import{common,createLowlight}from'lowlight'constlowlight=createLowlight(common)consttree=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 identifiersall,common, andcreateLowlight.There is no default export.
Map of all (±190) grammars (Record<string, LanguageFn>).
Map of common (37) grammars (Record<string, LanguageFn>).
Create alowlight instance.
grammars(Record<string, LanguageFn>, optional)— grammars to add
Lowlight (Lowlight).
Highlightvalue (code) aslanguage (name).
language(string)— programming languagenamevalue(string)— code to highlightoptions(Options, optional)— configuration
Tree (Root); with the followingdata fields:language(string), detected programming language name;relevance (number), howsure lowlight is that the given code is in the language.
import{common,createLowlight}from'lowlight'constlowlight=createLowlight(common)console.log(lowlight.highlight('css','em { color: red }'))
Yields:
{type:'root',children:[Array],data:{language:'css',relevance:3}}
Highlightvalue (code) and guess its programming language.
value(string)— code to highlightoptions(AutoOptions, optional)— configuration
Tree (Root); with the followingdata fields:language(string), detected programming language name;relevance (number), howsure lowlight is that the given code is in the language.
import{common,createLowlight}from'lowlight'constlowlight=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'importmarkdownfrom'highlight.js/lib/languages/markdown'constlowlight=createLowlight()console.log(lowlight.listLanguages())// => []lowlight.register({markdown})console.log(lowlight.listLanguages())// => ['markdown']
Register languages.
register(name, grammar)register(grammars)
name(string)— programming languagenamegrammar(LanguageFn)— grammargrammars(Record<string, LanguageFn>, optional)— grammars
Nothing (undefined).
import{createLowlight}from'lowlight'importxmlfrom'highlight.js/lib/languages/xml'constlowlight=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 languagenames to one or more aliasesname(string)— programming languagenamealias(Array<string> | string)— one or more aliases for the programming language
Nothing (undefined).
import{createLowlight}from'lowlight'importmarkdownfrom'highlight.js/lib/languages/markdown'constlowlight=createLowlight()lowlight.register({markdown})// lowlight.highlight('mdown', '<em>Emphasis</em>')// ^ would throw: Error: Unknown language: `mdown` is not registeredlowlight.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
WhetheraliasOrName is registered (boolean).
import{createLowlight}from'lowlight'importjavascriptfrom'highlight.js/lib/languages/javascript'constlowlight=createLowlight({javascript})console.log(lowlight.registered('funkyscript'))// => `false`lowlight.registerAlias({javascript:'funkyscript'})console.log(lowlight.registered('funkyscript'))// => `true`
Configuration forhighlightAuto (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 forhighlight (TypeScript type).
prefix(string, default:'hljs-')— class prefix
hast trees as returned by lowlight can be serialized withhast-util-to-html:
import{common,createLowlight}from'lowlight'import{toHtml}from'hast-util-to-html'constlowlight=createLowlight(common)consttree=lowlight.highlight('js','"use strict";')console.log(toHtml(tree))
Yields:
<spanclass="hljs-meta">"use strict"</span>;
hast trees as returned by lowlight can be turned into nodes of any frameworkthat supports JSX, such as preact, react, solid, svelte, vue, and more, withhast-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'constlowlight=createLowlight(common)consttree=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 withTypeScript.It exports the additional typesAutoOptions,LanguageFn, andOptions.
It also registersroot.data with@types/hast.If you’re working with the data fields, make sure to import this packagesomewhere 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} */constroot={type:'root',children:[]}console.log(root.data?.language)//=> TS now knows that this is a `string?`.
If you’re usingcreateLowlight(), no syntaxes are included yet.You can importall orcommon and pass them, such as withcreateLowlight(all).Checked syntaxes are included incommon.All syntaxes are included inall.
You can also manually import syntaxes fromhighlight.js/lib/languages/xxx,wherexxx 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(ino) — Arduinoarmasm(arm) — ARM Assemblyasciidoc(adoc) — AsciiDocaspectj— AspectJautohotkey(ahk) — AutoHotkeyautoit— AutoItavrasm— AVR Assemblyawk— Awkaxapta(x++) — X++bash(sh,zsh) — Bashbasic— BASICbnf— Backus–Naur Formbrainfuck(bf) — Brainfuckc(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(cc,c++,h++,hpp,hh,hxx,cxx) — C++crmsh(crm,pcmk) — crmshcrystal(cr) — Crystalcsharp(cs,c#) — C#csp— CSPcss— CSSd— Ddart— Dartdelphi(dpr,dfm,pas,pascal) — Delphidiff(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(golang) — Gogolo— Gologradle— Gradlegraphql(gql) — GraphQLgroovy— Groovyhaml— HAMLhandlebars(hbs,html.hbs,html.handlebars,htmlbars) — Handlebarshaskell(hs) — Haskellhaxe(hx) — Haxehsp— HSPhttp(https) — HTTPhy(hylang) — Hyinform7(i7) — Inform 7ini(toml) — TOML, also INIirpf90— IRPF90isbl— ISBLjava(jsp) — Javajavascript(js,jsx,mjs,cjs) — JavaScriptjboss-cli(wildfly-cli) — JBoss CLIjson(jsonc) — JSONjulia— Juliajulia-repl(jldoctest) — Julia REPLkotlin(kt,kts) — Kotlinlasso(ls,lassoscript) — Lassolatex(tex) — LaTeXldif— LDIFleaf— Leafless— Lesslisp— Lisplivecodeserver— LiveCodelivescript(ls) — LiveScriptllvm— LLVM IRlsl— LSL (Linden Scripting Language)lua(pluto) — Luamakefile(mk,mak,make) — Makefilemarkdown(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(mm,objc,obj-c,obj-c++,objective-c++) — Objective-Cocaml(ml) — OCamlopenscad(scad) — OpenSCADoxygene— Oxygeneparser3— Parser3perl(pl,pm) — Perlpf(pf.conf) — Packet Filter configpgsql(postgres,postgresql) — PostgreSQLphp— undefinedphp-template— PHP templateplaintext(text,txt) — Plain textpony— Ponypowershell(pwsh,ps,ps1) — PowerShellprocessing(pde) — Processingprofile— Python profilerprolog— Prologproperties— .propertiesprotobuf(proto) — Protocol Bufferspuppet(pp) — Puppetpurebasic(pb,pbi) — PureBASICpython(py,gyp,ipython) — Pythonpython-repl(pycon) — undefinedq(k,kdb) — Qqml(qt) — QMLr— Rreasonml(re) — ReasonMLrib— RenderMan RIBroboconf(graph,instances) — Roboconfrouteros(mikrotik) — MikroTik RouterOS scriptrsl— RenderMan RSLruby(rb,gemspec,podspec,thor,irb) — Rubyruleslanguage— Oracle Rules Languagerust(rs) — Rustsas— SASscala— Scalascheme(scm) — Schemescilab(sci) — Scilabscss— SCSSshell(console,shellsession) — Shell Sessionsmali— Smalismalltalk(st) — Smalltalksml(ml) — SML (Standard ML)sqf— SQFsql— SQLstan(stanfuncs) — Stanstata(do,ado) — Statastep21(p21,step,stp) — STEP Part 21stylus(styl) — Stylussubunit— SubUnitswift— Swifttaggerscript— Tagger Scripttap— Test Anything Protocoltcl(tk) — Tclthrift— Thrifttp— TPtwig(craftcms) — Twigtypescript(ts,tsx,mts,cts) — TypeScriptvala— Valavbnet(vb) — Visual Basic .NETvbscript(vbs) — VBScriptvbscript-html— VBScript in HTMLverilog(v,sv,svh) — Verilogvhdl— VHDLvim— Vim Scriptwasm— WebAssemblywren— Wrenx86asm— Intel x86 Assemblyxl(tao) — XLxml(html,xhtml,rss,atom,xjb,xsd,xsl,plist,wsf,svg) — HTML, XMLxquery(xpath,xq,xqm) — XQueryyaml(yml) — YAMLzephir(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 anyhighlight.js theme.For example, to get GitHub Dark from cdnjs:
<linkrel="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 ofNode.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 withPrismstarry-night— similar but like GitHub and really good
emphasize— syntax highlighting in ANSI (for the terminal)react-lowlight— syntax highlighter forReactreact-syntax-highlighter—React component for syntax highlightingrehype-highlight—rehype plugin to highlight codeblocksjstransformer-lowlight— syntax highlighting forJSTransformersandPug
Yes please!SeeHow to Contribute to Open Source.
About
Virtual syntax highlighting for virtual DOMs and non-HTML things
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Contributors12
Uh oh!
There was an error while loading.Please reload this page.