starry-night

starry-night

GitHub 风格的开源代码语法高亮库

starry-night 是一个模仿 GitHub 代码高亮效果的开源库。它支持超过 600 种编程语言,采用 TextMate 语法规则生成高质量的语法高亮。该项目适用于需要精确代码高亮的场景,尤其适合面向开发者的内容。starry-night 提供了简单的 API 接口,可输出 AST 对象便于后续处理。此外,它还包含了适配浅色和深色模式的 CSS 样式。

starry-night语法高亮GitHubJavaScript开源Github开源项目

<p align="center">Close up of <b>The Starry Night</b> by Vincent van Gogh (1889)<br>with examples of <code>starry-night</code> over it</p> <br>

starry-night

[![Build][build-badge]][build] [![Coverage][coverage-badge]][coverage] [![Downloads][downloads-badge]][downloads] [![Size][size-badge]][size]

Syntax highlighting, like what GitHub uses to highlight code, but free and open source and JavaScript!

Contents

What is this?

This package is an open source version of GitHub’s closed-source PrettyLights project (more on that later). It supports 600+ grammars and its extremely high quality. It uses TextMate grammars which are also used in popular editors (SublimeText, Atom, VS Code, &c). They’re heavy but high quality.

When should I use this?

starry-night is a high quality highlighter (when your readers or authors are programmers, you want this!) that can support tons of grammars (from new things like MDX to much more!) which approaches how GitHub renders code.

It has a WASM dependency, and rather big grammars, which means that starry-night might be too heavy particularly in browsers, in which case [lowlight][lowlight] or [refractor][refractor] might be more suitable.

This project is similar to the excellent [shiki][shiki], and it uses the same underlying dependencies, but starry-night is meant to match GitHub in that it produces classes and works with the CSS it ships, making it easier to add dark mode and other themes with CSS compared to inline styles.

Finally, this package produces objects (an AST), which makes it useful when you want to perform syntax highlighting in a place where serialized HTML wouldn’t work or wouldn’t work well. For example, 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 [hast][hast] or [rehype][rehype].

Bundled, minified, and gzipped, starry-night and the WASM binary are 185 kB. There are two lists of grammars you can use: [common][api-common] (±35 languages, good for your own site) adds 250 kB and [all][api-all] (~600 languages, useful if you are making a site like GitHub) is 1.6 MB. You can also manually choose which grammars to include (or add to common): a language is typically between 3 and 5 kB. To illustrate, Astro costs 2.1 kB and TSX costs 25.4 kB.

What is PrettyLights?

PrettyLights is the syntax highlighter that GitHub uses to turn this:

```markdown # Hello, world! ```

…into this:

<span class="pl-mh"><span class="pl-mh">#</span><span class="pl-mh"> </span>Hello, world!</span>

…which is what starry-night does too (some small differences in markup, but essentially the same)!

PrettyLights is responsible for taking the flag markdown, looking it up in [languages.yml][languages-yml] from github-linguist to figure out that that means markdown, taking a corresponding grammar (in this case [wooorm/markdown-tm-language][markdown-tm-language]), doing some GPL magic in C, and turning it into spans with classes.

GitHub is using PrettyLights since December 2014, when it [replaced Pygments][ref-1]. They wanted to open source it, but [were unable][ref-2] due to licensing issues. Recently ([Feb 2019][ref-3]?), GitHub has slowly started to move towards TreeLights, which is based on TreeSitter, and also closed source. If TreeLights includes a language (currently: C, C#, CSS, CodeQL, EJS, Elixir, ERB, Gleam, Go, HTML, Java, JS, Nix, PHP, Python, RegEx, Ruby, Rust, TLA, TS), that’ll be used, for everything else PrettyLights is used.

starry-night does what PrettyLights does, not what TreeLights does. I’m hopeful that that will be open sourced in the future and we can mimic both.

<br>

[][ref]

Install

This package is [ESM only][esm]. In Node.js (version 16+), install with [npm][]:

npm install @wooorm/starry-night

In Deno with [esm.sh][esmsh]:

import {common, createStarryNight} from 'https://esm.sh/@wooorm/starry-night@3'

In browsers with [esm.sh][esmsh]:

<script type="module"> import {common, createStarryNight} from 'https://esm.sh/@wooorm/starry-night@3?bundle' </script>

To get the CSS in browsers, do (see [CSS][] for more info):

<!-- This supports light and dark mode automatically. --> <link rel="stylesheet" href="https://esm.sh/@wooorm/starry-night@3/style/both">

Use

import {common, createStarryNight} from '@wooorm/starry-night' const starryNight = await createStarryNight(common) const scope = starryNight.flagToScope('markdown') const tree = starryNight.highlight('# hi', scope) console.log(tree)

Yields:

{ type: 'root', children: [ { type: 'element', tagName: 'span', properties: {className: ['pl-mh']}, children: [ {type: 'text', value: '# '}, { type: 'element', tagName: 'span', properties: {className: ['pl-en']}, children: [{type: 'text', value: 'hi'}] } ] } ] }

API

This package exports the identifiers [all][api-all], [common][api-common], and [createStarryNight][api-create-starry-night] from the main module. There is no default export.

It also includes grammars directly in its export map. Do not use the lang/ folder or the .js extension. For CSS files, do use style/ but don’t use .css:

import mdx from '@wooorm/starry-night/source.mdx' // Grammar. import tritanopiaDark from '@wooorm/starry-night/style/tritanopia-dark' // CSS.

all

List of all grammars ([Array<Grammar>][api-grammar])

common

List of ±35 common grammars ([Array<Grammar>][api-grammar])

createStarryNight(grammars[, options])

Create a StarryNight that can highlight things with the given grammars. This is async to allow async loading and registering, which is currently only used for WASM.

Parameters
  • grammars ([Array<Grammar>][api-grammar]) — grammars to support
  • options ([Options][api-options], optional) — configuration
Returns

Promise that resolves to an instance which highlights with the bound grammars (Promise<StarryNight>).

starryNight.flagToScope(flag)

Get the grammar scope (such as text.md) associated with a grammar name (such as markdown) or grammar extension (such as .mdwn).

This function uses the first word (when splitting on spaces and tabs) that is used after the opening of a fenced code block:

```js console.log(1) ```

To match GitHub, this also accepts entire paths:

```path/to/example.js console.log(1) ```

👉 Note: languages can use the same extensions. For example, .h is reused by many languages. In those cases, you will get one scope back, but it might not be the most popular language associated with an extension.

Parameters
  • flag (string) — grammar name (such as 'markdown'), grammar extension (such as '.mdwn'), or entire file path ending in extension
Returns

Grammar scope, such as 'text.md' (string or undefined).

Example
import {common, createStarryNight} from '@wooorm/starry-night' const starryNight = await createStarryNight(common) console.log(starryNight.flagToScope('pandoc')) // `'text.md'` console.log(starryNight.flagToScope('workbook')) // `'text.md'` console.log(starryNight.flagToScope('.workbook')) // `'text.md'` console.log(starryNight.flagToScope('path/to/example.js')) // `'source.js'` console.log(starryNight.flagToScope('whatever')) // `undefined`

starryNight.highlight(value, scope)

Highlight programming code.

Parameters
  • value (string) — code to highlight
  • scope (string) — registered grammar scope to highlight as (such as 'text.md')
Returns

Node representing highlighted code ([Root][hast-root]).

Example
import {createStarryNight} from '@wooorm/starry-night' import sourceCss from '@wooorm/starry-night/source.css' const starryNight = await createStarryNight([sourceCss]) console.log(starryNight.highlight('em { color: red }', 'source.css'))

Yields:

{ type: 'root', children: [ {type: 'element', tagName: 'span', properties: [Object], children: [Array]}, {type: 'text', value: ' { '}, {type: 'element', tagName: 'span', properties: [Object], children: [Array]}, {type: 'text', value: ': '}, {type: 'element', tagName: 'span', properties: [Object], children: [Array]}, {type: 'text', value: ' }'} ] }

starryNight.missingScopes()

List scopes that are needed by the registered grammars but that are missing.

To illustrate, the text.xml.svg grammar needs the text.xml grammar. When you register text.xml.svg without text.xml, it will be listed here.

Returns

List of grammar scopes, such as 'text.md' (Array<string>).

Example
import {createStarryNight} from '@wooorm/starry-night' import textXml from '@wooorm/starry-night/text.xml' import textXmlSvg from '@wooorm/starry-night/text.xml.svg' const svg = await createStarryNight([textXmlSvg]) console.log(svg.missingScopes()) //=> ['text.xml'] const svgAndXml = await createStarryNight([textXmlSvg, textXml]) console.log(svgAndXml.missingScopes()) //=> []

starryNight.register(grammars)

Add more grammars.

Parameters
  • grammars ([Array<Grammar>][api-grammar]) — grammars to support
Returns

Promise resolving to nothing (Promise<undefined>).

Example
import {createStarryNight} from '@wooorm/starry-night' import sourceCss from '@wooorm/starry-night/source.css' import textMd from '@wooorm/starry-night/text.md' import {toHtml} from 'hast-util-to-html' const markdown = '```css\nem { color: red }\n```' const starryNight = await createStarryNight([textMd]) console.log(toHtml(starryNight.highlight(markdown, 'text.md'))) await starryNight.register([sourceCss]) console.log(toHtml(starryNight.highlight(markdown, 'text.md')))

Yields:

<span class="pl-s">```</span><span class="pl-en">css</span> <span class="pl-c1">em { color: red }</span> <span class="pl-s">```</span>
<span class="pl-s">```</span><span class="pl-en">css</span> <span class="pl-ent">em</span> { <span class="pl-c1">color</span>: <span class="pl-c1">red</span> } <span class="pl-s">```</span>

starryNight.scopes()

List all registered scopes.

Returns

List of grammar scopes, such as 'text.md' (Array<string>).

Example
import {common, createStarryNight} from '@wooorm/starry-night' const starryNight = await createStarryNight(common) console.log(starryNight.scopes())

Yields:

[ 'source.c', 'source.c++', // … 'text.xml', 'text.xml.svg' ]

GetOnigurumaUrl

Function to get a URL to the oniguruma WASM (TypeScript type).

👉 Note: this must currently result in a version 2 URL of onig.wasm from [vscode-oniguruma][vscode-oniguruma].

⚠️ Danger: when you use this functionality, your project might break at any time (when reinstalling dependencies), except when you make sure that the WASM binary you load manually is what our internally used vscode-oniguruma dependency expects. To solve this, you could for example use an npm script called [dependencies][npm-script-dependencies] (which runs everytime node_modules is changed) which copies vscode-oniguruma/release/onig.wasm to the place you want to host it.

Returns

URL object to a WASM binary (Promise<URL> or URL).

Example
import {common, createStarryNight} from '@wooorm/starry-night' const starryNight = await createStarryNight(common, { getOnigurumaUrlFetch() { return new URL('/onig.wasm', window.location.href); } })

Grammar

TextMate grammar with some extra info (TypeScript type).

Fields
  • dependencies (Array<string>, optional, example: ['source.tsx']) — list of scopes that are needed for this grammar to work
  • extensions (Array<string>, example: ['.mdx']) — list of extensions
  • extensionsWithDot (Array<string>, optional, example: ['.php']) — list of extensions that only match if used w/ a dot
  • injections (Record<string, Rule>, optional) — TextMate injections
  • names (Array<string>, example: ['mdx']) — list of names
  • patterns (Array<Rule>) — TextMate patterns
  • repository (Record<string, Rule>, optional) — TextMate repository
  • scopeName (string, example: 'source.mdx') — scope

Options

Configuration (TypeScript type).

Fields

编辑推荐精选

商汤小浣熊

商汤小浣熊

最强AI数据分析助手

小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。

imini AI

imini AI

像人一样思考的AI智能体

imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。

Keevx

Keevx

AI数字人视频创作平台

Keevx 一款开箱即用的AI数字人视频创作平台,广泛适用于电商广告、企业培训与社媒宣传,让全球企业与个人创作者无需拍摄剪辑,就能快速生成多语言、高质量的专业视频。

即梦AI

即梦AI

一站式AI创作平台

提供 AI 驱动的图片、视频生成及数字人等功能,助力创意创作

扣子-AI办公

扣子-AI办公

AI办公助手,复杂任务高效处理

AI办公助手,复杂任务高效处理。办公效率低?扣子空间AI助手支持播客生成、PPT制作、网页开发及报告写作,覆盖科研、商业、舆情等领域的专家Agent 7x24小时响应,生活工作无缝切换,提升50%效率!

TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
下拉加载更多