Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Lightweight, robust, elegant virtual syntax highlighting using Prism

License

NotificationsYou must be signed in to change notification settings

wooorm/refractor

Repository files navigation

BuildCoverageDownloadsSize

Lightweight,robust,and elegant virtual syntax highlighting usingPrism.

Contents

What is this?

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

When should I use this?

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.

Playground

You can play with refractor on theinteractive demo (Replit).

Install

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>

Use

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

API

refractor has several entries in its export map:

  • refractor,which exportsrefractor and registers common grammars
  • refractor/all,which exportsrefractor and registers all grammars
  • refractor/core,which exportsrefractor and registers no grammars
  • refractor/*,where* is a language name such asmarkdown,which exports asyntax function as the default export

refractor

refractor.highlight(value, language)

Highlightvalue (code) aslanguage (programming language).

Parameters
  • value (string)— code to highlight
  • language (string orGrammar)— programming language name,alias,or grammar
Returns

Node representing highlighted code (Root).

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

refractor.register(syntax)

Register a syntax.

Parameters
  • syntax (Function)— language function custom made for refractor,as in,the files inrefractor/*
Example
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]}]}

refractor.alias(name[, alias])

Register aliases for already registered languages.

Signatures
  • alias(name, alias | list)
  • alias(aliases)
Parameters
  • language (string)— programming languagename
  • alias (string)— new aliases for the programming language
  • list (Array<string>)— list of aliases
  • aliases (Record<language, alias | list>)— map oflanguages toaliases orlists
Example
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!

refractor.registered(aliasOrlanguage)

Check whether analias orlanguage is registered.

Parameters
  • aliasOrlanguage (string)— programming language name or alias
Example
importmarkdownfrom'refractor/markdown'import{refractor}from'refractor/core'console.log(refractor.registered('markdown'))//=> falserefractor.register(markdown)console.log(refractor.registered('markdown'))//=> true

refractor.listLanguages()

List all registered languages (names and aliases).

Returns

Array<string>.

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

Syntax

Refractor syntax function (TypeScript type).

Type
exporttypeSyntax=((prism:Refractor)=>undefined|void)&{aliases?:Array<string>|undefineddisplayName:string}

Examples

Example: serializing hast as html

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>

Example: turning hast into react nodes

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

Data

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.

CSS

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

Compatibility

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.

Security

This package is safe.

Related

Projects

Contribute

Yes please!SeeHow to Contribute to Open Source.

License

MIT ©Titus Wormer

About

Lightweight, robust, elegant virtual syntax highlighting using Prism

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Contributors14


[8]ページ先頭

©2009-2026 Movatter.jp