Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
The lowlight npm package is a library for syntax highlighting of code using languages supported by highlight.js. It is primarily used to parse and transform code into a syntax-highlighted format without a browser, making it suitable for server-side applications or pre-processing of static pages.
Syntax Highlighting
This feature allows you to highlight syntax of various programming languages. The code sample demonstrates highlighting a simple JavaScript code snippet.
const lowlight = require('lowlight');
const highlightedCode = lowlight.highlight('javascript', 'const x = 123;').value;
console.log(highlightedCode);
Registering Languages
This feature enables the addition of new languages to lowlight's highlighting capabilities by registering them through highlight.js. The code sample shows how to register and highlight Python code.
const lowlight = require('lowlight');
lowlight.registerLanguage('python', require('highlight.js/lib/languages/python'));
const highlightedPython = lowlight.highlight('python', 'def foo(): return 123').value;
console.log(highlightedPython);
Auto-Detection of Language
This feature automatically detects the programming language of a given code snippet and applies appropriate syntax highlighting. The code sample demonstrates auto-detection for a JavaScript snippet.
const lowlight = require('lowlight');
const result = lowlight.highlightAuto('const x = 123;');
console.log(result.language); // 'javascript'
console.log(result.value);
highlight.js is a widely used library for syntax highlighting. It supports numerous languages and is often used directly in web browsers. Compared to lowlight, highlight.js is more versatile for client-side applications but both can be used server-side.
Prism is another popular syntax highlighting library that works both in the browser and on the server. It is known for its lightweight core and extensible plugins. Unlike lowlight, PrismJS focuses more on client-side performance and extensibility.
Shiki is a syntax highlighter powered by the same language grammars as Visual Studio Code. It provides accurate and visually appealing highlights. Shiki is similar to lowlight in that it can be used server-side, but it offers a richer set of themes and a different integration approach.
Virtual syntax highlighting for virtual DOMs and non-HTML things.
This package wraps highlight.js to output objects (ASTs) instead of a string of HTML.
highlight.js
, through lowlight, supports 190+ programming languages.
Supporting all of them requires a lot of code.
That’s why there are three entry points for lowlight:
lib/core.js
— 0 languageslib/common.js
(default) — 37 languageslib/all.js
— 192 languagesBundled, minified, and gzipped, those are roughly 9.7 kB, 47 kB, and 290 kB.
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).
A different package, refractor
, does the same as lowlight but
uses Prism instead.
If you’re looking for a really good (but rather heavy) highlighter, try
starry-night
.
This package is ESM only. In Node.js (version 14.14+, 16.0+), install with npm:
npm install lowlight
In Deno with esm.sh
:
import {lowlight} from 'https://esm.sh/lowlight@2'
In browsers with esm.sh
:
<script type="module">
import {lowlight} from 'https://esm.sh/lowlight@2?bundle'
</script>
import {lowlight} from 'lowlight'
const tree = lowlight.highlight('js', '"use strict";')
console.dir(tree, {depth: null})
Yields:
{
type: 'root',
data: {language: 'js', relevance: 10},
children: [
{
type: 'element',
tagName: 'span',
properties: {className: ['hljs-meta']},
children: [{type: 'text', value: '"use strict"'}]
},
{type: 'text', value: ';'}
]
}
This package exports the identifier lowlight
.
There is no default export.
lowlight.highlight(language, value[, options])
Highlight value
(code) as language
(name).
language
(string
)
— programming language namevalue
(string
)
— code to highlightoptions.prefix
(string?
, default: 'hljs-'
)
— class prefixA hast Root
node with the following data
fields:
relevance
(number
)
— how sure lowlight is that the given code is in the languagelanguage
(string
)
— detected programming language nameimport {lowlight} from 'lowlight'
console.log(lowlight.highlight('css', 'em { color: red }'))
Yields:
{type: 'root', data: {language: 'css', relevance: 3}, children: [Array]}
lowlight.highlightAuto(value[, options])
Highlight value
(code) and guess its programming language.
value
(string
)
— code to highlightoptions.prefix
(string?
, default: 'hljs-'
)
— class prefixoptions.subset
(Array<string>
, default: all registered language names)
— list of allowed languagesThe same result as lowlight.highlight
is returned.
import {lowlight} from 'lowlight'
console.log(lowlight.highlightAuto('"hello, " + name + "!"'))
Yields:
{type: 'root', data: {language: 'applescript', relevance: 3}, children: [Array]}
lowlight.registerLanguage(language, syntax)
Register a language.
language
(string
)
— programming language namesyntax
(HighlightSyntax
)
— highlight.js
syntaxhighlight.js
operates as a singleton: once you register a language in one
place, it’ll be available everywhere.
import {lowlight} from 'lowlight/lib/core.js'
import xml from 'highlight.js/lib/languages/xml.js'
lowlight.registerLanguage('xml', xml)
console.log(lowlight.highlight('html', '<em>Emphasis</em>'))
Yields:
{type: 'root', data: {language: 'html', relevance: 2}, children: [Array]}
lowlight.registerAlias(language, alias)
Register aliases for already registered languages.
registerAlias(language, alias|list)
registerAlias(aliases)
language
(string
)
— programming language namealias
(string
)
— new aliases for the programming languagelist
(Array<string>
)
— list of aliasesaliases
(Record<language, alias|list>
)
— map of language
s to alias
es or list
simport {lowlight} from 'lowlight/lib/core.js'
import md from 'highlight.js/lib/languages/markdown.js'
lowlight.registerLanguage('markdown', md)
// 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 language
is registered.
aliasOrlanguage
(string
)
— name of a registered language or aliasWhether aliasOrlanguage
is registered (boolean
).
import {lowlight} from 'lowlight/lib/core.js'
import javascript from 'highlight.js/lib/languages/javascript.js'
lowlight.registerLanguage('javascript', javascript)
lowlight.registered('js') // return false
lowlight.registerAlias('javascript', 'js')
lowlight.registered('js') // return true
lowlight.listLanguages()
List registered languages.
Names of registered language (Array<string>
).
import {lowlight} from 'lowlight/lib/core.js'
import md from 'highlight.js/lib/languages/markdown.js'
console.log(lowlight.listLanguages()) // => []
lowlight.registerLanguage('markdown', md)
console.log(lowlight.listLanguages()) // => ['markdown']
hast trees as returned by lowlight can be serialized with
hast-util-to-html
:
import {lowlight} from 'lowlight'
import {toHtml} from 'hast-util-to-html'
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 React (or Preact) with
hast-to-hyperscript
:
import {lowlight} from 'lowlight'
import {toH} from 'hast-to-hyperscript'
import React from 'react'
const tree = lowlight.highlight('js', '"use strict";')
const react = toH(React.createElement, tree)
console.log(react)
Yields:
{
'$$typeof': Symbol(react.element),
type: 'div',
key: 'h-1',
ref: null,
props: { children: [ [Object], ';' ] },
_owner: null,
_store: {}
}
This package is fully typed with TypeScript.
It exports the additional types Root
, Options
, and AutoOptions
.
If you’re using lowlight/lib/core.js
, no syntaxes are included.
Checked syntaxes are included if you import lowlight
(or explicitly
lowlight/lib/common.js
).
Unchecked syntaxes are available through lowlight/lib/all.js
.
You can import core
or common
and manually add more languages as you please.
highlight.js
operates as a singleton: once you register a language in one
place, it’ll be available everywhere.
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
) — 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
— 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
— 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
) — XQueryyaml
(yml
) — YAMLzephir
(zep
) — Zephirlowlight
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.2.0/styles/github-dark.min.css">
This package is at least compatible with all maintained versions of Node.js. As of now, that is Node.js 14.14+ and 16.0+. It also works in Deno and modern browsers.
This package is safe.
refractor
— the same as lowlight but with Prismstarry-night
— similar but like GitHub and really goodemphasize
— 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 PugYes please! See How to Contribute to Open Source.
FAQs
Virtual syntax highlighting for virtual DOMs and non-HTML things
The npm package lowlight receives a total of 1,985,344 weekly downloads. As such, lowlight popularity was classified as popular.
We found that lowlight demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.