• Stars
    star
    553
  • Rank 77,359 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Virtual syntax highlighting for virtual DOMs and non-HTML things

lowlight

Build Coverage Downloads Size

Virtual syntax highlighting for virtual DOMs and non-HTML things.

Contents

What is this?

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 languages
  • lib/common.js (default) — 37 languages
  • lib/all.js — 192 languages

Bundled, minified, and gzipped, those are roughly 9.7 kB, 47 kB, and 290 kB.

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

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.

Install

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>

Use

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: ';'}
  ]
}

API

This package exports the identifier lowlight. There is no default export.

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

Highlight value (code) as language (name).

Parameters
  • language (string) — programming language name
  • value (string) — code to highlight
  • options.prefix (string?, default: 'hljs-') — class prefix
Returns

A hast Root node with the following data fields:

  • relevance (number) — how sure lowlight is that the given code is in the language
  • language (string) — detected programming language name
Example
import {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.

Parameters
  • value (string) — code to highlight
  • options.prefix (string?, default: 'hljs-') — class prefix
  • options.subset (Array<string>, default: all registered language names) — list of allowed languages
Returns

The same result as lowlight.highlight is returned.

Example
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.

Parameters
  • language (string) — programming language name
  • syntax (HighlightSyntax) — highlight.js syntax
Note

highlight.js operates as a singleton: once you register a language in one place, it’ll be available everywhere.

Example
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.

Signatures
  • registerAlias(language, alias|list)
  • registerAlias(aliases)
Parameters
  • language (string) — programming language name
  • alias (string) — new aliases for the programming language
  • list (Array<string>) — list of aliases
  • aliases (Record<language, alias|list>) — map of languages to aliases or lists
Example
import {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.

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

Whether aliasOrlanguage is registered (boolean).

Example
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.

Returns

Names of registered language (Array<string>).

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

Examples

Example: serializing hast as html

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

Example: turning hast into react nodes

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

Types

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

Data

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: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) — 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 — 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 — 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) — XQuery
  • yaml (yml) — YAML
  • 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.2.0/styles/github-dark.min.css">

Compatibility

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.

Security

This package is safe.

Related

Projects

Contribute

Yes please! See How to Contribute to Open Source.

License

MIT © Titus Wormer

More Repositories

1

franc

Natural language detection
JavaScript
3,906
star
2

dictionaries

Hunspell dictionaries in UTF-8
JavaScript
1,051
star
3

markdown-rs

CommonMark compliant markdown parser in Rust with ASTs and extensions
Rust
736
star
4

starry-night

Syntax highlighting, like GitHub
JavaScript
614
star
5

xdm

Just a *really* good MDX compiler. No runtime. With esbuild, Rollup, and webpack plugins
JavaScript
589
star
6

refractor

Lightweight, robust, elegant virtual syntax highlighting using Prism
JavaScript
535
star
7

mdxjs-rs

Compile MDX to JavaScript in Rust
Rust
387
star
8

nspell

📝 Hunspell compatible spell-checker
JavaScript
260
star
9

markdown-table

Generate a markdown (GFM) table
JavaScript
249
star
10

gemoji

Info on gemoji (GitHub Emoji)
JavaScript
218
star
11

write-music

visualise sentence length
JavaScript
192
star
12

readability

visualise readability
JavaScript
185
star
13

parse-english

English (natural language) parser
JavaScript
159
star
14

server-components-mdx-demo

React server components + MDX
JavaScript
123
star
15

emphasize

ANSI syntax highlighting for the terminal
JavaScript
101
star
16

linked-list

Minimalistic linked lists
JavaScript
81
star
17

levenshtein.c

Levenshtein algorithm in C
C
79
star
18

import-meta-resolve

Resolve things like Node.js — ponyfill for `import.meta.resolve`
JavaScript
78
star
19

short-words

visualise lengthy words
JavaScript
65
star
20

trough

`trough` is middleware
JavaScript
61
star
21

bcp-47

Parse and stringify BCP 47 language tags
JavaScript
59
star
22

html-tag-names

List of known HTML tag names
JavaScript
58
star
23

parse-latin

Latin-script (natural language) parser
JavaScript
57
star
24

iso-3166

ISO 3166 (standard for country codes and codes for their subdivisions)
JavaScript
51
star
25

html-element-attributes

Map of HTML elements to allowed attributes
JavaScript
51
star
26

trim-lines

Remove spaces and tabs around line-breaks
JavaScript
50
star
27

common-words

visualise rare words
JavaScript
49
star
28

parse-entities

Parse HTML character references
JavaScript
46
star
29

iso-639-3

Info on ISO 639-3
JavaScript
46
star
30

levenshtein-rs

Levenshtein algorithm in Rust
Rust
42
star
31

emoticon

List of emoticons
JavaScript
40
star
32

direction

Detect directionality: left-to-right, right-to-left, or neutral
JavaScript
39
star
33

textom

DEPRECATED in favour of retext’s virtual object model
39
star
34

dictionary

Dictionary app that can work without JavaScript or internet
JavaScript
37
star
35

f-ck

🤬 Clean-up cuss words
JavaScript
37
star
36

dioscuri

A gemtext (`text/gemini`) parser with support for streaming, ASTs, and CSTs
JavaScript
34
star
37

property-information

Info on the properties and attributes of the web platform
JavaScript
33
star
38

stmr.c

Porter Stemmer algorithm in C
C
32
star
39

eslint-md

Deprecated
30
star
40

svg-tag-names

List of known SVG tag names
JavaScript
29
star
41

checkmoji

Check emoji across platforms
JavaScript
26
star
42

html-void-elements

List of known void HTML elements
JavaScript
26
star
43

npm-high-impact

The high-impact (popular) packages of npm
JavaScript
26
star
44

iso-639-2

Info on ISO 639-2
JavaScript
23
star
45

aria-attributes

List of ARIA attributes
JavaScript
21
star
46

stringify-entities

Serialize (encode) HTML character references
JavaScript
21
star
47

bcp-47-match

Match BCP 47 language tags with language ranges per RFC 4647
JavaScript
19
star
48

speakers

Speaker count for 450+ languages
JavaScript
19
star
49

svg-element-attributes

Map of SVG elements to allowed attributes
JavaScript
19
star
50

osx-learn

Add words to the OS X Spell Check dictionary
Shell
18
star
51

trigrams

Trigram files for 400+ languages
JavaScript
18
star
52

fault

Functional errors with formatted output
JavaScript
17
star
53

remark-preset-wooorm

Personal markdown (and prose) style
JavaScript
17
star
54

udhr

Universal declaration of human rights
HTML
17
star
55

bcp-47-normalize

Normalize, canonicalize, and format BCP 47 tags
JavaScript
16
star
56

happy-places

Little list of happy places
15
star
57

wooorm.github.io

🐛 personal website
JavaScript
14
star
58

plain-text-data-to-json

Transform a simple plain-text database to JSON
JavaScript
14
star
59

parse-dutch

Dutch (natural language) parser
JavaScript
14
star
60

zwitch

Handle values based on a property
JavaScript
13
star
61

match-casing

Match the case of `value` to that of `base`
JavaScript
13
star
62

link-rel

List of valid values for `rel` on `<link>`
JavaScript
13
star
63

npm-esm-vs-cjs

Data on the share of ESM vs CJS on the public npm registry
JavaScript
13
star
64

linter-remark

Check markdown with remark in atom
13
star
65

is-badge

Check if `url` is a badge
JavaScript
13
star
66

vendors

List of vendor prefixes known to the web platform
JavaScript
12
star
67

load-plugin

Load a submodule / plugin
JavaScript
12
star
68

comma-separated-tokens

Parse and stringify comma-separated tokens
JavaScript
11
star
69

bail

Throw if given an error
JavaScript
11
star
70

space-separated-tokens

Parse and stringify space-separated tokens
JavaScript
10
star
71

trigram-utils

A few language trigram utilities
JavaScript
10
star
72

collapse-white-space

Collapse white space.
JavaScript
9
star
73

retext-language

Detect then language of text with Retext
JavaScript
9
star
74

longest-streak

Count the longest repeating streak of a substring
JavaScript
9
star
75

unherit

Clone a constructor without affecting the super-class
JavaScript
9
star
76

markdown-escapes

Legacy: list of escapable characters in markdown
JavaScript
9
star
77

state-toggle

Enter/exit a state
JavaScript
9
star
78

meta-name

List of values that can be used as `name`s on HTML `meta` elements
JavaScript
9
star
79

html-dangerous-encodings

List of dangerous HTML character encoding labels
JavaScript
8
star
80

character-entities

Map of named character references.
JavaScript
8
star
81

stmr

Porter Stemmer CLI
C
8
star
82

levenshtein

Levenshtein algorithm CLI
Shell
8
star
83

commonmark.json

CommonMark test spec in JSON
JavaScript
8
star
84

web-namespaces

Map of web namespaces
JavaScript
7
star
85

is-whitespace-character

Check if a character is a white space character
JavaScript
7
star
86

strip-skin-tone

Strip skin tone modifiers (as in Fitzpatrick scale) from emoji (🎅🏿 to 🎅)
JavaScript
7
star
87

atom-travis

Install Atom on Travis
Shell
7
star
88

svg-event-attributes

List of SVG event handler attributes
JavaScript
7
star
89

control-pictures

Replace pictures for control character codes with actual control characters
JavaScript
7
star
90

css-declarations

Legacy utility to parse and stringify CSS declarations
JavaScript
6
star
91

html-encodings

Info on HTML character encodings.
JavaScript
6
star
92

mathml-tag-names

List of known MathML tag names
JavaScript
6
star
93

array-iterate

`Array#forEach()` but it’s possible to define where to move to next
JavaScript
6
star
94

atom-tap-test-runner

Run Atom package tests using TAP
6
star
95

ccount

Count how often a substring occurs
JavaScript
6
star
96

doctype

Info on HTML / XHTML / MathML / SVG doctypes
JavaScript
6
star
97

retext-english

Moved
6
star
98

labels

GitHub labels
6
star
99

remark-range

Deprecated
6
star
100

dead-or-alive

check if urls are dead or alive
JavaScript
6
star