Lightweight, robust, elegant virtual syntax highlighting using Prism
npm install refractor[![Build][badge-build-image]][badge-build-url]
[![Coverage][badge-coverage-image]][badge-coverage-url]
[![Downloads][badge-downloads-image]][badge-downloads-url]
[![Size][badge-size-image]][badge-size-url]
Lightweight,
robust,
and elegant virtual syntax highlighting using [Prism][github-prism].
* What is this?
* When should I use this?
* Playground
* Install
* Use
* API
* refractor
* Syntax
* Examples
* Example: serializing hast as html
* Example: turning hast into react nodes
* Data
* CSS
* Compatibility
* Security
* Related
* Projects
* Contribute
This package wraps [Prism][github-prism] to output objects (ASTs) instead of a
string of HTML.
Prism,
through refractor,
supports 290+ programming languages.
Supporting all of them requires a lot of code.
That’s why there are three entry points for refractor:
* refractor/all — 297 languages
* refractor/core — 0 languages
* refractor (default) — 36 common languages
Bundled,
minified,
and gzipped,
those are roughly 12.7 kB (core),
40 kB (default),
and 211 kB (all).
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 refractor 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,
[lowlight][github-lowlight],
does the same as refractor but uses [highlight.js][github-highlightjs]
instead.
If you’re looking for a really good but rather heavy highlighter,
try [starry-night][github-starry-night].
You can play with refractor on the
interactive demo (Replit).
This package is [ESM only][github-gist-esm].
In Node.js (version 16+),
install with [npm][npmjs-install]:
``sh`
npm install refractor
In Deno with [esm.sh][esmsh]:
`js`
import {refractor} from 'https://esm.sh/refractor@5'
In browsers with [esm.sh][esmsh]:
`html`
`js
import {refractor} from 'refractor'
const tree = refractor.highlight('"use strict";', 'js')
console.log(tree)
`
Yields:
`js`
{
type: 'root',
children: [
{
type: 'element',
tagName: 'span',
properties: {className: ['token', 'string']},
children: [{type: 'text', value: '"use strict"'}]
},
{
type: 'element',
tagName: 'span',
properties: {className: ['token', 'punctuation']},
children: [{type: 'text', value: ';'}]
}
]
}
refractor has several entries in its export map:
* refractor,refractor
which exports and registers common grammarsrefractor/all
* ,refractor
which exports and registers all grammarsrefractor/core
* ,refractor
which exports and registers no grammarsrefractor/
,*
where is a language name such as markdown,
which exports a [syntax function][api-syntax] as the default export
#### refractor.highlight(value, language)
Highlight value (code) as language (programming language).
###### Parameters
* value (string)language
— code to highlight
* (string or Grammar)
— programming language name,
alias,
or grammar
###### Returns
Node representing highlighted code ([Root][github-hast-root]).
###### Example
`js
import css from 'refractor/css'
import {refractor} from 'refractor/core'
refractor.register(css)
console.log(refractor.highlight('em { color: red }', 'css'))
`
Yields:
`js`
{
type: 'root',
children: [
{type: 'element', tagName: 'span', properties: [Object], children: [Array]},
{type: 'text', value: ' '},
// …
{type: 'text', value: ' red '},
{type: 'element', tagName: 'span', properties: [Object], children: [Array]}
]
}
#### refractor.register(syntax)
Register a syntax.
###### Parameters
* syntax (Function)refractor/*
— language function custom made for refractor,
as in,
the files in
###### Example
`js
import markdown from 'refractor/markdown'
import {refractor} from 'refractor/core'
refractor.register(markdown)
console.log(refractor.highlight('Emphasis', 'markdown'))
`
Yields:
`js`
{
type: 'root',
children: [
{type: 'element', tagName: 'span', properties: [Object], children: [Array]}
]
}
#### refractor.alias(name[, alias])
Register aliases for already registered languages.
###### Signatures
* alias(name, alias | list)alias(aliases)
*
###### Parameters
* language (string)alias
— programming language [name][prismjs-languages]
* (string)list
— new aliases for the programming language
* (Array)aliases
— list of aliases
* (Record)language
— map of s to aliases or lists
###### Example
`js
import markdown from 'refractor/markdown'
import {refractor} from 'refractor/core'
refractor.register(markdown)
// refractor.highlight('Emphasis', 'mdown')
// ^ would throw: Error: Unknown language: mdown is not registered
refractor.alias({markdown: ['mdown', 'mkdn', 'mdwn', 'ron']})
refractor.highlight('Emphasis', 'mdown')
// ^ Works!
`
#### refractor.registered(aliasOrlanguage)
Check whether an alias or language is registered.
###### Parameters
* aliasOrlanguage (string)
— programming language name or alias
###### Example
`js
import markdown from 'refractor/markdown'
import {refractor} from 'refractor/core'
console.log(refractor.registered('markdown')) //=> false
refractor.register(markdown)
console.log(refractor.registered('markdown')) //=> true
`
#### refractor.listLanguages()
List all registered languages (names and aliases).
###### Returns
Array.
###### Example
`js
import markdown from 'refractor/markdown'
import {refractor} from 'refractor/core'
console.log(refractor.listLanguages()) //=> []
refractor.register(markdown)
console.log(refractor.listLanguages())
`
Yields:
`jsmarkup
[
'markup', // Note that (a lot of xml based languages) is a dep of markdown.`
'html',
// …
'markdown',
'md'
]
Refractor syntax function (TypeScript type).
###### Type
`ts`
export type Syntax = ((prism: Refractor) => undefined | void) & {
aliases?: Array
displayName: string
}
hast trees as returned by refractor can be serialized with
[hast-util-to-html][github-hast-util-to-html]:
`js
import {toHtml} from 'hast-util-to-html'
import {refractor} from 'refractor'
const tree = refractor.highlight('"use strict";', 'js')
console.log(toHtml(tree))
`
Yields:
`html`
"use strict";
hast trees as returned by refractor can be turned into React (or Preact) with
[hast-util-to-jsx-runtime][github-hast-util-to-jsx-runtime]:
`js
import {toJsxRuntime} from 'hast-util-to-jsx-runtime'
import {Fragment, jsxs, jsx} from 'react/jsx-runtime'
import {refractor} from 'refractor'
const tree = refractor.highlight('"use strict";', 'js')
const reactNode = toJsxRuntime(tree, {Fragment, jsxs, jsx})
console.log(react)
`
Yields:
`js`
{
'$$typeof': Symbol(react.element),
type: 'div',
key: 'h-1',
ref: null,
props: { children: [ [Object], [Object] ] },
_owner: null,
_store: {}
}
If you’re using refractor/core,refractor
no syntaxes are included.
Checked syntaxes are included if you import .refractor/all
Unchecked syntaxes are available through .refractor/core
You can import or refractor and manually add more languages
as you please.
Prism operates as a singleton:
once you register a language in one place,
it’ll be available everywhere.
Only these custom built syntaxes will work with refractor because Prism’s own
syntaxes are made to work with global variables and are not importable.
* [x] arduino — alias: inobash
* [x] — alias: sh, shellbasic
* [x] c
* [x] clike
* [x] cpp
* [x] csharp
* [x] — alias: cs, dotnetcss
* [x] diff
* [x] go
* [x] ini
* [x] java
* [x] javascript
* [x] — alias: jsjson
* [x] — alias: webmanifestkotlin
* [x] — alias: kt, ktsless
* [x] lua
* [x] makefile
* [x] markdown
* [x] — alias: mdmarkup
* [x] — alias: atom, html, mathml, rss, ssml, svg, xmlmarkup-templating
* [x] objectivec
* [x] — alias: objcperl
* [x] php
* [x] python
* [x] — alias: pyr
* [x] regex
* [x] ruby
* [x] — alias: rbrust
* [x] sass
* [x] scss
* [x] sql
* [x] swift
* [x] typescript
* [x] — alias: tsvbnet
* [x] yaml
* [x] — alias: ymlabap
* [ ] abnf
* [ ] actionscript
* [ ] ada
* [ ] agda
* [ ] al
* [ ] antlr4
* [ ] — alias: g4apacheconf
* [ ] apex
* [ ] apl
* [ ] applescript
* [ ] aql
* [ ] arff
* [ ] armasm
* [ ] — alias: arm-asmarturo
* [ ] — alias: artasciidoc
* [ ] — alias: adocasm6502
* [ ] asmatmel
* [ ] aspnet
* [ ] autohotkey
* [ ] autoit
* [ ] avisynth
* [ ] — alias: avsavro-idl
* [ ] — alias: avdlawk
* [ ] — alias: gawkbatch
* [ ] bbcode
* [ ] — alias: shortcodebbj
* [ ] bicep
* [ ] birb
* [ ] bison
* [ ] bnf
* [ ] — alias: rbnfbqn
* [ ] brainfuck
* [ ] brightscript
* [ ] bro
* [ ] bsl
* [ ] — alias: oscriptcfscript
* [ ] — alias: cfcchaiscript
* [ ] cil
* [ ] cilkc
* [ ] — alias: cilk-ccilkcpp
* [ ] — alias: cilk, cilk-cppclojure
* [ ] cmake
* [ ] cobol
* [ ] coffeescript
* [ ] — alias: coffeeconcurnas
* [ ] — alias: conccooklang
* [ ] coq
* [ ] crystal
* [ ] cshtml
* [ ] — alias: razorcsp
* [ ] css-extras
* [ ] csv
* [ ] cue
* [ ] cypher
* [ ] d
* [ ] dart
* [ ] dataweave
* [ ] dax
* [ ] dhall
* [ ] django
* [ ] — alias: jinja2dns-zone-file
* [ ] — alias: dns-zonedocker
* [ ] — alias: dockerfiledot
* [ ] — alias: gvebnf
* [ ] editorconfig
* [ ] eiffel
* [ ] ejs
* [ ] — alias: etaelixir
* [ ] elm
* [ ] erb
* [ ] erlang
* [ ] etlua
* [ ] excel-formula
* [ ] — alias: xls, xlsxfactor
* [ ] false
* [ ] firestore-security-rules
* [ ] flow
* [ ] fortran
* [ ] fsharp
* [ ] ftl
* [ ] gap
* [ ] gcode
* [ ] gdscript
* [ ] gedcom
* [ ] gettext
* [ ] — alias: pogherkin
* [ ] git
* [ ] glsl
* [ ] gml
* [ ] — alias: gamemakerlanguagegn
* [ ] — alias: gnigo-module
* [ ] — alias: go-modgradle
* [ ] graphql
* [ ] groovy
* [ ] haml
* [ ] handlebars
* [ ] — alias: hbs, mustachehaskell
* [ ] — alias: hshaxe
* [ ] hcl
* [ ] hlsl
* [ ] hoon
* [ ] hpkp
* [ ] hsts
* [ ] http
* [ ] ichigojam
* [ ] icon
* [ ] icu-message-format
* [ ] idris
* [ ] — alias: idriecst
* [ ] ignore
* [ ] — alias: gitignore, hgignore, npmignoreinform7
* [ ] io
* [ ] j
* [ ] javadoc
* [ ] javadoclike
* [ ] javastacktrace
* [ ] jexl
* [ ] jolie
* [ ] jq
* [ ] js-extras
* [ ] js-templates
* [ ] jsdoc
* [ ] json5
* [ ] jsonp
* [ ] jsstacktrace
* [ ] jsx
* [ ] julia
* [ ] keepalived
* [ ] keyman
* [ ] kumir
* [ ] — alias: kumkusto
* [ ] latex
* [ ] — alias: context, texlatte
* [ ] lilypond
* [ ] — alias: lylinker-script
* [ ] — alias: ldliquid
* [ ] lisp
* [ ] — alias: elisp, emacs, emacs-lisplivescript
* [ ] llvm
* [ ] log
* [ ] lolcode
* [ ] magma
* [ ] mata
* [ ] matlab
* [ ] maxscript
* [ ] mel
* [ ] mermaid
* [ ] metafont
* [ ] mizar
* [ ] mongodb
* [ ] monkey
* [ ] moonscript
* [ ] — alias: moonn1ql
* [ ] n4js
* [ ] — alias: n4jsdnand2tetris-hdl
* [ ] naniscript
* [ ] — alias: naninasm
* [ ] neon
* [ ] nevod
* [ ] nginx
* [ ] nim
* [ ] nix
* [ ] nsis
* [ ] ocaml
* [ ] odin
* [ ] opencl
* [ ] openqasm
* [ ] — alias: qasmoz
* [ ] parigp
* [ ] parser
* [ ] pascal
* [ ] — alias: objectpascalpascaligo
* [ ] pcaxis
* [ ] — alias: pxpeoplecode
* [ ] — alias: pcodephp-extras
* [ ] phpdoc
* [ ] plant-uml
* [ ] — alias: plantumlplsql
* [ ] powerquery
* [ ] — alias: mscript, pqpowershell
* [ ] processing
* [ ] prolog
* [ ] promql
* [ ] properties
* [ ] protobuf
* [ ] psl
* [ ] pug
* [ ] puppet
* [ ] pure
* [ ] purebasic
* [ ] — alias: pbfasmpurescript
* [ ] — alias: pursq
* [ ] qml
* [ ] qore
* [ ] qsharp
* [ ] — alias: qsracket
* [ ] — alias: rktreason
* [ ] rego
* [ ] renpy
* [ ] — alias: rpyrescript
* [ ] — alias: resrest
* [ ] rip
* [ ] roboconf
* [ ] robotframework
* [ ] — alias: robotsas
* [ ] scala
* [ ] scheme
* [ ] shell-session
* [ ] — alias: sh-session, shellsessionsmali
* [ ] smalltalk
* [ ] smarty
* [ ] sml
* [ ] — alias: smlnjsolidity
* [ ] — alias: solsolution-file
* [ ] — alias: slnsoy
* [ ] sparql
* [ ] — alias: rqsplunk-spl
* [ ] sqf
* [ ] squirrel
* [ ] stan
* [ ] stata
* [ ] stylus
* [ ] supercollider
* [ ] — alias: sclangsystemd
* [ ] t4-cs
* [ ] — alias: t4t4-templating
* [ ] t4-vb
* [ ] tap
* [ ] tcl
* [ ] textile
* [ ] toml
* [ ] tremor
* [ ] — alias: trickle, troytsx
* [ ] tt2
* [ ] turtle
* [ ] — alias: trigtwig
* [ ] typoscript
* [ ] — alias: tsconfigunrealscript
* [ ] — alias: uc, uscriptuorazor
* [ ] uri
* [ ] — alias: urlv
* [ ] vala
* [ ] velocity
* [ ] verilog
* [ ] vhdl
* [ ] vim
* [ ] visual-basic
* [ ] — alias: vb, vbawarpscript
* [ ] wasm
* [ ] web-idl
* [ ] — alias: webidlwgsl
* [ ] wiki
* [ ] wolfram
* [ ] — alias: mathematica, nb, wlwren
* [ ] xeora
* [ ] — alias: xeoracubexml-doc
* [ ] xojo
* [ ] xquery
* [ ] yang
* [ ] zig
* [ ]
refractor does not inject CSS for the syntax highlighted code.esm.sh
It does not make sense: refractor 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 Prism theme.
For example,
to get Prism Dark from [][esmsh]:
`html`
This package is at least compatible with all maintained versions of Node.js.
As of now,
that is Node.js 16+.
It also works in Deno and modern browsers.
Only the custom built syntaxes in refractor/* will work withrefractor as Prism’s own syntaxes are made to work with global variables and
are not importable.
refractor also does not support Prism plugins,
due to the same limitations,
and that they almost exclusively deal with the DOM.
This package is safe.
* [lowlight][github-lowlight]highlight.js
— the same as refractor but with [][github-highlightjs]starry-night
* [][github-starry-night]
— similar but like GitHub and really good
* react-syntax-highlighter
— [React][] component for syntax highlighting
* @mapbox/rehype-prism
— [rehype][github-rehype] plugin to highlight code
blocks
* react-refractor`
— syntax highlighter for [React][]
Yes please!
See [How to Contribute to Open Source][opensource-guide].
[MIT][file-license] © [Titus Wormer][wooorm]
[api-syntax]: #syntax
[badge-build-image]: https://github.com/wooorm/refractor/workflows/main/badge.svg
[badge-build-url]: https://github.com/wooorm/refractor/actions
[badge-coverage-image]: https://img.shields.io/codecov/c/github/wooorm/refractor.svg
[badge-coverage-url]: https://codecov.io/github/wooorm/refractor
[badge-downloads-image]: https://img.shields.io/npm/dm/refractor.svg
[badge-downloads-url]: https://www.npmjs.com/package/refractor
[badge-size-image]: https://img.shields.io/bundlejs/size/refractor
[badge-size-url]: https://bundlejs.com/?q=refractor
[esmsh]: https://esm.sh
[file-license]: license
[github-gist-esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[github-hast-root]: https://github.com/syntax-tree/hast#root
[github-hast-util-to-html]: https://github.com/syntax-tree/hast-util-to-html
[github-hast-util-to-jsx-runtime]: https://github.com/syntax-tree/hast-util-to-jsx-runtime
[github-highlightjs]: https://github.com/highlightjs/highlight.js
[github-lowlight]: https://github.com/wooorm/lowlight
[github-prism]: https://github.com/PrismJS/prism
[github-rehype]: https://github.com/rehypejs/rehype
[github-starry-night]: https://github.com/wooorm/starry-night
[npmjs-install]: https://docs.npmjs.com/cli/install
[opensource-guide]: https://opensource.guide/how-to-contribute/
[prismjs-languages]: https://prismjs.com/#languages-list
[react]: https://react.dev
[wooorm]: https://wooorm.com