Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork48
Lightweight, robust, elegant virtual syntax highlighting using Prism
License
wooorm/refractor
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Lightweight,robust,and elegant virtual syntax highlighting usingPrism.
- What is this?
- When should I use this?
- Playground
- Install
- Use
- API
- Examples
- Data
- CSS
- Compatibility
- Security
- Related
- Projects
- Contribute
This package wrapsPrism to output objects (ASTs) instead of astring 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 placewhere 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 ANSIsequences,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 useshighlight.jsinstead.If you’re looking for areally good but rather heavy highlighter,trystarry-night.
You can play with refractor on theinteractive demo (Replit).
This package isESM only.In Node.js (version 16+),install withnpm:
npm install refractor
In Deno withesm.sh:
import{refractor}from'https://esm.sh/refractor@5'
In browsers withesm.sh:
<scripttype="module">import{refractor}from'https://esm.sh/refractor@5?bundle'</script>
import{refractor}from'refractor'consttree=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 asyntax function as the default export
Highlightvalue (code) aslanguage (programming language).
value(string)— code to highlightlanguage(stringorGrammar)— programming language name,alias,or grammar
Node representing highlighted code (Root).
importcssfrom'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/*
importmarkdownfrom'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 languagenamealias(string)— new aliases for the programming languagelist(Array<string>)— list of aliasesaliases(Record<language, alias | list>)— map oflanguages toaliases orlists
importmarkdownfrom'refractor/markdown'import{refractor}from'refractor/core'refractor.register(markdown)// refractor.highlight('*Emphasis*', 'mdown')// ^ would throw: Error: Unknown language: `mdown` is not registeredrefractor.alias({markdown:['mdown','mkdn','mdwn','ron']})refractor.highlight('*Emphasis*','mdown')// ^ Works!
Check whether analias orlanguage is registered.
aliasOrlanguage(string)— programming language name or alias
importmarkdownfrom'refractor/markdown'import{refractor}from'refractor/core'console.log(refractor.registered('markdown'))//=> falserefractor.register(markdown)console.log(refractor.registered('markdown'))//=> true
List all registered languages (names and aliases).
Array<string>.
importmarkdownfrom'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).
exporttypeSyntax=((prism:Refractor)=>undefined|void)&{aliases?:Array<string>|undefineddisplayName:string}
hast trees as returned by refractor can be serialized withhast-util-to-html:
import{toHtml}from'hast-util-to-html'import{refractor}from'refractor'consttree=refractor.highlight('"use strict";','js')console.log(toHtml(tree))
Yields:
<spanclass="token string">"use strict"</span><spanclass="token punctuation">;</span>
hast trees as returned by refractor can be turned into React (or Preact) withhast-util-to-jsx-runtime:
import{toJsxRuntime}from'hast-util-to-jsx-runtime'import{Fragment,jsxs,jsx}from'react/jsx-runtime'import{refractor}from'refractor'consttree=refractor.highlight('"use strict";','js')constreactNode=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 usingrefractor/core,no syntaxes are included.Checked syntaxes are included if you importrefractor.Unchecked syntaxes are available throughrefractor/all.You can importrefractor/core orrefractor and manually add more languagesas 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 withrefractor because Prism’s ownsyntaxes are made to work with global variables and are not importable.
arduino— alias:inobash— alias:sh,shellbasiccclikecppcsharp— alias:cs,dotnetcssdiffgoinijavajavascript— alias:jsjson— alias:webmanifestkotlin— alias:kt,ktslessluamakefilemarkdown— alias:mdmarkup— alias:atom,html,mathml,rss,ssml,svg,xmlmarkup-templatingobjectivec— alias:objcperlphppython— alias:pyrregexruby— alias:rbrustsassscsssqlswifttypescript— alias:tsvbnetyaml— alias:ymlabapabnfactionscriptadaagdaalantlr4— alias:g4apacheconfapexaplapplescriptaqlarffarmasm— alias:arm-asmarturo— alias:artasciidoc— alias:adocasm6502asmatmelaspnetautohotkeyautoitavisynth— alias:avsavro-idl— alias:avdlawk— alias:gawkbatchbbcode— alias:shortcodebbjbicepbirbbisonbnf— alias:rbnfbqnbrainfuckbrightscriptbrobsl— alias:oscriptcfscript— alias:cfcchaiscriptcilcilkc— alias:cilk-ccilkcpp— alias:cilk,cilk-cppclojurecmakecobolcoffeescript— alias:coffeeconcurnas— alias:conccooklangcoqcrystalcshtml— alias:razorcspcss-extrascsvcuecypherddartdataweavedaxdhalldjango— alias:jinja2dns-zone-file— alias:dns-zonedocker— alias:dockerfiledot— alias:gvebnfeditorconfigeiffelejs— alias:etaelixirelmerberlangetluaexcel-formula— alias:xls,xlsxfactorfalsefirestore-security-rulesflowfortranfsharpftlgapgcodegdscriptgedcomgettext— alias:pogherkingitglslgml— alias:gamemakerlanguagegn— alias:gnigo-module— alias:go-modgradlegraphqlgroovyhamlhandlebars— alias:hbs,mustachehaskell— alias:hshaxehclhlslhoonhpkphstshttpichigojamiconicu-message-formatidris— alias:idriecstignore— alias:gitignore,hgignore,npmignoreinform7iojjavadocjavadoclikejavastacktracejexljoliejqjs-extrasjs-templatesjsdocjson5jsonpjsstacktracejsxjuliakeepalivedkeymankumir— alias:kumkustolatex— alias:context,texlattelilypond— alias:lylinker-script— alias:ldliquidlisp— alias:elisp,emacs,emacs-lisplivescriptllvmloglolcodemagmamatamatlabmaxscriptmelmermaidmetafontmizarmongodbmonkeymoonscript— alias:moonn1qln4js— alias:n4jsdnand2tetris-hdlnaniscript— alias:naninasmneonnevodnginxnimnixnsisocamlodinopenclopenqasm— alias:qasmozparigpparserpascal— alias:objectpascalpascaligopcaxis— alias:pxpeoplecode— alias:pcodephp-extrasphpdocplant-uml— alias:plantumlplsqlpowerquery— alias:mscript,pqpowershellprocessingprologpromqlpropertiesprotobufpslpugpuppetpurepurebasic— alias:pbfasmpurescript— alias:pursqqmlqoreqsharp— alias:qsracket— alias:rktreasonregorenpy— alias:rpyrescript— alias:resrestriproboconfrobotframework— alias:robotsasscalaschemeshell-session— alias:sh-session,shellsessionsmalismalltalksmartysml— alias:smlnjsolidity— alias:solsolution-file— alias:slnsoysparql— alias:rqsplunk-splsqfsquirrelstanstatastylussupercollider— alias:sclangsystemdt4-cs— alias:t4t4-templatingt4-vbtaptcltextiletomltremor— alias:trickle,troytsxtt2turtle— alias:trigtwigtyposcript— alias:tsconfigunrealscript— alias:uc,uscriptuorazoruri— alias:urlvvalavelocityverilogvhdlvimvisual-basic— alias:vb,vbawarpscriptwasmweb-idl— alias:webidlwgslwikiwolfram— alias:mathematica,nb,wlwrenxeora— alias:xeoracubexml-docxojoxqueryyangzig
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 mightnot run in a browser!If you are in a browser,you can use any Prism theme.For example,to get Prism Dark fromesm.sh:
<linkrel="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 inrefractor/* will work withrefractor as Prism’s own syntaxes are made to work with global variables andare 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 codeblocksreact-refractor— syntax highlighter forReact
Yes please!SeeHow to Contribute to Open Source.
About
Lightweight, robust, elegant virtual syntax highlighting using Prism
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
Contributors14
Uh oh!
There was an error while loading.Please reload this page.