Security News
NIST Misses 2024 Deadline to Clear NVD Backlog
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
Refractor is a lightweight, robust, and extensible syntax highlighter that works in both Node.js and the browser. It is built on top of the Prism syntax highlighter and provides a way to highlight code syntax in various programming languages.
Syntax Highlighting
This feature allows you to highlight code syntax for a given programming language. The example highlights a simple JavaScript code snippet.
const refractor = require('refractor');
const html = refractor.highlight('const x = 42;', 'javascript');
console.log(html);
Registering Languages
You can register additional languages for syntax highlighting. This example registers the Python language and highlights a Python code snippet.
const refractor = require('refractor');
const python = require('refractor/lang/python');
refractor.register(python);
const html = refractor.highlight('print("Hello, World!")', 'python');
console.log(html);
Syntax Highlighting with Plugins
Refractor supports plugins to extend its functionality. This example uses the line-numbers plugin to add line numbers to the highlighted code.
const refractor = require('refractor');
const lineNumbers = require('refractor/plugins/line-numbers');
refractor.use(lineNumbers);
const html = refractor.highlight('const x = 42;', 'javascript');
console.log(html);
Highlight.js is a popular syntax highlighter written in JavaScript. It automatically detects the language of the code and applies syntax highlighting. Compared to Refractor, Highlight.js is more automatic in language detection but may not be as customizable.
Prism is a lightweight, extensible syntax highlighter, built with modern web standards in mind. Refractor is built on top of Prism, so they share many similarities. However, Refractor provides a more modular approach and additional features like plugins.
CodeMirror is a versatile text editor implemented in JavaScript for the browser. It is specialized for editing code and comes with syntax highlighting capabilities. While CodeMirror is more of a full-fledged code editor, Refractor focuses solely on syntax highlighting.
Lightweight, robust, elegant virtual syntax highlighting using Prism. Useful for virtual DOMs and non-HTML things. Perfect for React, VDOM, and others.
refractor
is built to work with all syntaxes supported by Prism,
that’s 277 languages (as of prism@1.27.0
) and all
themes.
Want to use highlight.js
instead?
Try lowlight
!
npm:
npm install refractor
var refractor = require('refractor')
var nodes = refractor.highlight('"use strict";', 'js')
console.log(nodes)
Yields:
[
{
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: ';'}]
}
]
Which serialized with rehype
or hast-util-to-html
yields (you may have to wrap it into a fragment like so: {type: 'root', children: nodes}
):
<span class="token string">"use strict"</span><span class="token punctuation">;</span>
Tip: Use
hast-to-hyperscript
to transform to other virtual DOMs, or DIY.
refractor.register(syntax)
Register a syntax.
Needed if you’re using refractor/core
.
var refractor = require('refractor/core')
var markdown = require('refractor/lang/markdown')
refractor.register(markdown)
console.log(refractor.highlight('*Emphasis*', 'markdown'))
Yields:
[
{
type: 'element',
tagName: 'span',
properties: {className: [Array]},
children: [[Object], [Object], [Object]]
}
]
refractor.alias(name[, alias])
Register a new alias
for the name
language.
alias(name, alias|list)
alias(aliases)
name
(string
) — Name of a registered languagealias
(string
) — New alias for the registered languagelist
(Array.<alias>
) — List of aliasesaliases
(Object.<alias|list>
) — Map where each key is a name
and each
value an alias
or a list
var refractor = require('refractor/core')
var markdown = require('refractor/lang/markdown')
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.highlight(value, language)
Parse value
(string
) according to the language
(name or alias)
syntax.
Virtual nodes representing the highlighted value (Array.<Node>
).
var refractor = require('refractor/core')
console.log(refractor.highlight('em { color: red }', 'css'))
Yields:
[
{
type: 'element',
tagName: 'span',
properties: {className: [Array]},
children: [[Object]]
},
{type: 'text', value: ' '},
// …
{type: 'text', value: ' red '},
{
type: 'element',
tagName: 'span',
properties: {className: [Array]},
children: [[Object]]
}
]
refractor.registered(language)
Check if a language
(name or alias) is registered.
var refractor = require('refractor/core')
var markdown = require('refractor/lang/markdown')
console.log(refractor.registered('markdown'))
refractor.register(markdown)
console.log(refractor.registered('markdown'))
Yields:
false
true
refractor.listLanguages()
List all registered languages (names and aliases).
Array.<string>
.
var refractor = require('refractor/core')
var markdown = require('refractor/lang/markdown')
console.log(refractor.listLanguages())
refractor.register(markdown)
console.log(refractor.listLanguages())
Yields:
[
'markup',
'html',
// …
'javascript',
'js'
]
[
'markup',
'html',
// …
'javascript',
'js',
'markdown',
'md'
]
I do not suggest using the pre-bundled files or requiring
refractor
itself in the browser as that would include a 376kb (139kb GZipped)
of code.
Instead require refractor/core
and include only the needed syntaxes.
For example:
var refractor = require('refractor/core')
refractor.register(require('refractor/lang/jsx'))
console.log(refractor.highlight('<Dropdown primary />', 'jsx'))
Yields:
[
{
type: 'element',
tagName: 'span',
properties: {className: ['token', 'tag']},
children: [
{type: 'element', tagName: 'span', properties: {className: [Array]}, children: [[Object], [Object]]},
{type: 'text', value: ' '},
{type: 'element', tagName: 'span', properties: {className: [Array]}, children: [[Object]]},
{type: 'text', value: ' '},
{type: 'element', tagName: 'span', properties: {className: [Array]}, children: [[Object]]}
]
}
]
…When using browserify and minifying with tinyify this results in just 65kb of code (23kb with GZip).
refractor
does not support Prism plugins:
require
just what you
needAll syntaxes are included if you require('refractor')
.
If you’re using refractor/core
, checked syntaxes are always included, but
unchecked syntaxes are not and must be require
d and register
ed.
Unlike in Prism, cssExtras
and phpExtras
are camel-cased instead of
dash-cased.
Only these custom built syntaxes will work with refractor
because Prism’s own
syntaxes are made to work with global variables and are not requirable.
clike
css
javascript
— alias: js
markup
— alias: html
, mathml
, svg
, xml
, ssml
, atom
, rss
abap
abnf
actionscript
ada
agda
al
antlr4
— alias: g4
apacheconf
apex
apl
applescript
aql
arduino
— alias: ino
arff
asciidoc
— alias: adoc
asm6502
asmatmel
aspnet
autohotkey
autoit
avisynth
— alias: avs
avroIdl
bash
— alias: shell
basic
batch
bbcode
— alias: shortcode
bicep
birb
bison
bnf
— alias: rbnf
brainfuck
brightscript
bro
bsl
c
cfscript
chaiscript
cil
clojure
cmake
cobol
coffeescript
— alias: coffee
concurnas
— alias: conc
coq
cpp
crystal
csharp
— alias: dotnet
, cs
cshtml
— alias: razor
csp
cssExtras
csv
cypher
d
dart
dataweave
dax
dhall
diff
django
— alias: jinja2
dnsZoneFile
docker
— alias: dockerfile
dot
— alias: gv
ebnf
editorconfig
eiffel
ejs
— alias: eta
elixir
elm
erb
erlang
etlua
excelFormula
factor
$false
firestoreSecurityRules
flow
fortran
fsharp
ftl
gap
gcode
gdscript
gedcom
gherkin
git
glsl
gml
gn
— alias: gni
goModule
go
graphql
groovy
haml
handlebars
— alias: hbs
haskell
— alias: hs
haxe
hcl
hlsl
hoon
hpkp
hsts
http
ichigojam
icon
icuMessageFormat
idris
— alias: idr
iecst
ignore
— alias: gitignore
, hgignore
, npmignore
inform7
ini
io
j
java
javadoc
javadoclike
javastacktrace
jexl
jolie
jq
jsExtras
jsTemplates
jsdoc
json
— alias: webmanifest
json5
jsonp
jsstacktrace
jsx
julia
keepalived
keyman
kotlin
— alias: kt
, kts
kumir
— alias: kum
kusto
latex
— alias: tex
, context
latte
less
lilypond
liquid
lisp
livescript
llvm
log
lolcode
lua
magma
makefile
markdown
— alias: md
markupTemplating
matlab
maxscript
mel
mermaid
mizar
mongodb
monkey
moonscript
— alias: moon
n1ql
n4js
— alias: n4jsd
nand2tetrisHdl
naniscript
nasm
neon
nevod
nginx
nim
nix
nsis
objectivec
— alias: objc
ocaml
opencl
openqasm
— alias: qasm
oz
parigp
parser
pascal
— alias: objectpascal
pascaligo
pcaxis
— alias: px
peoplecode
— alias: pcode
perl
phpExtras
php
phpdoc
plsql
powerquery
powershell
processing
prolog
promql
properties
protobuf
psl
pug
puppet
pure
purebasic
purescript
— alias: purs
python
— alias: py
q
qml
qore
qsharp
— alias: qs
r
racket
— alias: rkt
reason
regex
rego
renpy
— alias: rpy
rest
rip
roboconf
robotframework
ruby
— alias: rb
rust
sas
sass
scala
scheme
scss
shellSession
smali
smalltalk
smarty
sml
— alias: smlnj
solidity
— alias: sol
solutionFile
soy
sparql
— alias: rq
splunkSpl
sqf
sql
squirrel
stan
stylus
swift
systemd
t4Cs
t4Templating
t4Vb
tap
tcl
textile
toml
tremor
tsx
tt2
turtle
twig
typescript
— alias: ts
typoscript
— alias: tsconfig
unrealscript
— alias: uc
, uscript
uorazor
uri
— alias: url
v
vala
vbnet
velocity
verilog
vhdl
vim
visualBasic
warpscript
wasm
webIdl
wiki
wolfram
— alias: mathematica
, wl
, nb
wren
xeora
— alias: xeoracube
xmlDoc
xojo
xquery
yaml
— alias: yml
yang
zig
lowlight
— Same, but based on highlight.js
react-syntax-highlighter
— React component for syntax highlightingrehype-prism
— Syntax highlighting in rehypereact-refractor
— Syntax highlighter for ReactFAQs
Lightweight, robust, elegant virtual syntax highlighting using Prism
The npm package refractor receives a total of 1,496,070 weekly downloads. As such, refractor popularity was classified as popular.
We found that refractor demonstrated a not healthy version release cadence and project activity because the last version was released 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
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
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.