Lightweight, robust, and elegant virtual syntax highlighting using Prism.
- What is this?
- When should I use this?
- Playground
- Install
- Use
- API
- Examples
- Data
- CSS
- Compatibility
- Security
- Related
- Projects
- Contribute
This package wraps 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 languagesrefractor/coreβ 0 languagesrefractor(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,
does the same as refractor but uses highlight.js
instead.
If youβre looking for a really good but rather heavy highlighter,
try starry-night.
You can play with refractor on the interactive demo (Replit).
This package is ESM only. In Node.js (version 16+), install with npm:
npm install refractorIn Deno with esm.sh:
import {refractor} from 'https://esm.sh/refractor@5'In browsers with esm.sh:
<script type="module">
import {refractor} from 'https://esm.sh/refractor@5?bundle'
</script>import {refractor} from 'refractor'
const tree = refractor.highlight('"use strict";', 'js')
console.log(tree)Yields:
{
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, which exportsrefractorand registers common grammarsrefractor/all, which exportsrefractorand registers all grammarsrefractor/core, which exportsrefractorand registers no grammarsrefractor/*, where*is a language name such asmarkdown, which exports a syntax function as the default export
Highlight value (code) as language (programming language).
value(string) β code to highlightlanguage(stringorGrammar) β programming language name, alias, or grammar
Node representing highlighted code (Root).
import css from 'refractor/css'
import {refractor} from 'refractor/core'
refractor.register(css)
console.log(refractor.highlight('em { color: red }', 'css'))Yields:
{
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]}
]
}Register a syntax.
syntax(Function) β language function custom made for refractor, as in, the files inrefractor/*
import markdown from 'refractor/markdown'
import {refractor} from 'refractor/core'
refractor.register(markdown)
console.log(refractor.highlight('*Emphasis*', 'markdown'))Yields:
{
type: 'root',
children: [
{type: 'element', tagName: 'span', properties: [Object], children: [Array]}
]
}Register aliases for already registered languages.
alias(name, alias | list)alias(aliases)
language(string) β programming language namealias(string) β new aliases for the programming languagelist(Array<string>) β list of aliasesaliases(Record<language, alias | list>) β map oflanguages toaliases orlists
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!Check whether an alias or language is registered.
aliasOrlanguage(string) β programming language name or alias
import markdown from 'refractor/markdown'
import {refractor} from 'refractor/core'
console.log(refractor.registered('markdown')) //=> false
refractor.register(markdown)
console.log(refractor.registered('markdown')) //=> trueList all registered languages (names and aliases).
Array<string>.
import markdown from 'refractor/markdown'
import {refractor} from 'refractor/core'
console.log(refractor.listLanguages()) //=> []
refractor.register(markdown)
console.log(refractor.listLanguages())Yields:
[
'markup', // Note that `markup` (a lot of xml based languages) is a dep of markdown.
'html',
// β¦
'markdown',
'md'
]Refractor syntax function (TypeScript type).
export type Syntax = ((prism: Refractor) => undefined | void) & {
aliases?: Array<string> | undefined
displayName: string
}hast trees as returned by refractor can be serialized with
hast-util-to-html:
import {toHtml} from 'hast-util-to-html'
import {refractor} from 'refractor'
const tree = refractor.highlight('"use strict";', 'js')
console.log(toHtml(tree))Yields:
<span class="token string">"use strict"</span><span class="token punctuation">;</span>hast trees as returned by refractor can be turned into React (or Preact) with
hast-util-to-jsx-runtime:
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:
{
'$$typeof': Symbol(react.element),
type: 'div',
key: 'h-1',
ref: null,
props: { children: [ [Object], [Object] ] },
_owner: null,
_store: {}
}If youβre using refractor/core,
no syntaxes are included.
Checked syntaxes are included if you import refractor.
Unchecked syntaxes are available through refractor/all.
You can import refractor/core 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.
-
arduinoβ alias:ino -
bashβ alias:sh,shell -
basic -
c -
clike -
cpp -
csharpβ alias:cs,dotnet -
css -
diff -
go -
ini -
java -
javascriptβ alias:js -
jsonβ alias:webmanifest -
kotlinβ alias:kt,kts -
less -
lua -
makefile -
markdownβ alias:md -
markupβ alias:atom,html,mathml,rss,ssml,svg,xml -
markup-templating -
objectivecβ alias:objc -
perl -
php -
pythonβ alias:py -
r -
regex -
rubyβ alias:rb -
rust -
sass -
scss -
sql -
swift -
typescriptβ alias:ts -
vbnet -
yamlβ alias:yml -
abap -
abnf -
actionscript -
ada -
agda -
al -
antlr4β alias:g4 -
apacheconf -
apex -
apl -
applescript -
aql -
arff -
armasmβ alias:arm-asm -
arturoβ alias:art -
asciidocβ alias:adoc -
asm6502 -
asmatmel -
aspnet -
autohotkey -
autoit -
avisynthβ alias:avs -
avro-idlβ alias:avdl -
awkβ alias:gawk -
batch -
bbcodeβ alias:shortcode -
bbj -
bicep -
birb -
bison -
bnfβ alias:rbnf -
bqn -
brainfuck -
brightscript -
bro -
bslβ alias:oscript -
cfscriptβ alias:cfc -
chaiscript -
cil -
cilkcβ alias:cilk-c -
cilkcppβ alias:cilk,cilk-cpp -
clojure -
cmake -
cobol -
coffeescriptβ alias:coffee -
concurnasβ alias:conc -
cooklang -
coq -
crystal -
cshtmlβ alias:razor -
csp -
css-extras -
csv -
cue -
cypher -
d -
dart -
dataweave -
dax -
dhall -
djangoβ alias:jinja2 -
dns-zone-fileβ alias:dns-zone -
dockerβ alias:dockerfile -
dotβ alias:gv -
ebnf -
editorconfig -
eiffel -
ejsβ alias:eta -
elixir -
elm -
erb -
erlang -
etlua -
excel-formulaβ alias:xls,xlsx -
factor -
false -
firestore-security-rules -
flow -
fortran -
fsharp -
ftl -
gap -
gcode -
gdscript -
gedcom -
gettextβ alias:po -
gherkin -
git -
glsl -
gmlβ alias:gamemakerlanguage -
gnβ alias:gni -
go-moduleβ alias:go-mod -
gradle -
graphql -
groovy -
haml -
handlebarsβ alias:hbs,mustache -
haskellβ alias:hs -
haxe -
hcl -
hlsl -
hoon -
hpkp -
hsts -
http -
ichigojam -
icon -
icu-message-format -
idrisβ alias:idr -
iecst -
ignoreβ alias:gitignore,hgignore,npmignore -
inform7 -
io -
j -
javadoc -
javadoclike -
javastacktrace -
jexl -
jolie -
jq -
js-extras -
js-templates -
jsdoc -
json5 -
jsonp -
jsstacktrace -
jsx -
julia -
keepalived -
keyman -
kumirβ alias:kum -
kusto -
latexβ alias:context,tex -
latte -
lilypondβ alias:ly -
linker-scriptβ alias:ld -
liquid -
lispβ alias:elisp,emacs,emacs-lisp -
livescript -
llvm -
log -
lolcode -
magma -
mata -
matlab -
maxscript -
mel -
mermaid -
metafont -
mizar -
mongodb -
monkey -
moonscriptβ alias:moon -
n1ql -
n4jsβ alias:n4jsd -
nand2tetris-hdl -
naniscriptβ alias:nani -
nasm -
neon -
nevod -
nginx -
nim -
nix -
nsis -
ocaml -
odin -
opencl -
openqasmβ alias:qasm -
oz -
parigp -
parser -
pascalβ alias:objectpascal -
pascaligo -
pcaxisβ alias:px -
peoplecodeβ alias:pcode -
php-extras -
phpdoc -
plant-umlβ alias:plantuml -
plsql -
powerqueryβ alias:mscript,pq -
powershell -
processing -
prolog -
promql -
properties -
protobuf -
psl -
pug -
puppet -
pure -
purebasicβ alias:pbfasm -
purescriptβ alias:purs -
q -
qml -
qore -
qsharpβ alias:qs -
racketβ alias:rkt -
reason -
rego -
renpyβ alias:rpy -
rescriptβ alias:res -
rest -
rip -
roboconf -
robotframeworkβ alias:robot -
sas -
scala -
scheme -
shell-sessionβ alias:sh-session,shellsession -
smali -
smalltalk -
smarty -
smlβ alias:smlnj -
solidityβ alias:sol -
solution-fileβ alias:sln -
soy -
sparqlβ alias:rq -
splunk-spl -
sqf -
squirrel -
stan -
stata -
stylus -
supercolliderβ alias:sclang -
systemd -
t4-csβ alias:t4 -
t4-templating -
t4-vb -
tap -
tcl -
textile -
toml -
tremorβ alias:trickle,troy -
tsx -
tt2 -
turtleβ alias:trig -
twig -
typoscriptβ alias:tsconfig -
unrealscriptβ alias:uc,uscript -
uorazor -
uriβ alias:url -
v -
vala -
velocity -
verilog -
vhdl -
vim -
visual-basicβ alias:vb,vba -
warpscript -
wasm -
web-idlβ alias:webidl -
wgsl -
wiki -
wolframβ alias:mathematica,nb,wl -
wren -
xeoraβ alias:xeoracube -
xml-doc -
xojo -
xquery -
yang -
zig
refractor does not inject CSS for the syntax highlighted code.
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 esm.sh:
<link rel="stylesheet" href="https://esm.sh/prismjs@1.30.0/themes/prism-dark.css">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 with
refractor 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β the same as refractor but withhighlight.jsstarry-nightβ similar but like GitHub and really good
react-syntax-highlighterβ React component for syntax highlighting@mapbox/rehype-prismβ rehype plugin to highlight code blocksreact-refractorβ syntax highlighter for React
Yes please! See How to Contribute to Open Source.
MIT Β© Titus Wormer