### Get and Set Processor Data
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Demonstrates how to use the `data` method to get and set arbitrary information on a Unified processor. This is useful for storing configuration or state.
```javascript
import {unified} from 'unified'
const processor = unified().data('alpha', 'bravo')
processor.data('alpha') // => 'bravo'
processor.data() // => {alpha: 'bravo'}
processor.data({charlie: 'delta'})
processor.data() // => {charlie: 'delta'}
```
--------------------------------
### Create a New Processor from Remark
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
This example shows how to create a new, independent processor instance from the 'remark' preset. It pipes stdin to the processor and writes the processed output to stdout, demonstrating a common pattern for command-line tools.
```js
import process from 'node:process'
import concatStream from 'concat-stream'
import {remark} from 'remark'
process.stdin.pipe(
concatStream(function (buf) {
process.stdout.write(String(remark().processSync(buf)))
})
)
```
--------------------------------
### Configure a Unified Processor
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Configure a processor with plugins for parsing, transforming, and compiling content. This example shows a typical pipeline for processing markdown to HTML.
```javascript
const processor = unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeDocument, {title: 'ππ'})
.use(rehypeFormat)
.use(rehypeStringify)
```
--------------------------------
### Install Unified with npm
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Install the unified package using npm. This package is ESM only and requires Node.js version 16 or higher.
```sh
npm install unified
```
--------------------------------
### Unified Processor Example
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Demonstrates how to create a new Unified processor and chain plugins for parsing, linting, transforming, and stringifying markdown content. It also shows how to report errors and convert the processed file to a string.
```APIDOC
## unified()
Create a new processor.
### Description
Initializes a new processor instance. This processor can be configured with various plugins to perform transformations on content.
### Returns
New *[unfrozen][api-freeze]* processor ([`processor`][api-processor]).
### Example
```js
import rehypeStringify from 'rehype-stringify'
import remarkParse from 'remark-parse'
import remarkPresetLintMarkdownStyleGuide from 'remark-preset-lint-markdown-style-guide'
import remarkRehype from 'remark-rehype'
import remarkRetext from 'remark-retext'
import retextEnglish from 'retext-english'
import {unified} from 'unified'
import {reporter} from 'vfile-reporter'
const file = await unified()
.use(remarkParse)
.use(remarkPresetLintMarkdownStyleGuide)
.use(remarkRetext, unified().use(retextEnglish).use(retextEquality))
.use(remarkRehype)
.use(rehypeStringify)
.process('*Emphasis* and _stress_, you guys!')
console.error(reporter(file))
console.log(String(file))
```
```
--------------------------------
### Create a Custom Unified Plugin (JavaScript)
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Example of creating a custom Unified plugin named 'move' that modifies the file extension. It takes an options object with an `extname` property and returns a transformer function.
```javascript
/**
* @import {Plugin} from 'unified'
*/
/**
* @typedef Options
* Configuration (required).
* @property {string} extname
* File extension to use (must start with `.`)
*/
/** @type {Plugin<[Options]>} */
export function move(options) {
if (!options || !options.extname) {
throw new Error('Missing `options.extname`')
}
return function (_, file) {
if (file.extname && file.extname !== options.extname) {
file.extname = options.extname
}
}
}
```
--------------------------------
### Freeze Unified Processor
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Shows how to freeze a Unified processor using `.freeze()`. Frozen processors cannot be configured further but can be used to create new processors. This example illustrates how `rehype` prevents extensions after freezing.
```javascript
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'
export const rehype = unified().use(rehypeParse).use(rehypeStringify).freeze()
```
```javascript
import {rehype} from 'rehype'
import rehypeFormat from 'rehype-format'
// β¦
rehype()
.use(rehypeFormat)
// β¦
```
```javascript
import {rehype} from 'rehype'
import rehypeFormat from 'rehype-format'
// β¦
rehype
.use(rehypeFormat)
// β¦
```
```text
Error: Cannot call `use` on a frozen processor.
Create a new processor first, by calling it: use `processor()` instead of `processor`.
at assertUnfrozen (~/node_modules/unified/index.js:426:11)
at Function.use (~/node_modules/unified/index.js:165:5)
β¦
```
--------------------------------
### Process Markdown to HTML with Unified
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
This example demonstrates processing markdown content to HTML using a pipeline of unified plugins. It includes parsing markdown, converting it to HTML, adding a document structure, formatting, and stringifying the result. The output is then logged to the console.
```js
import rehypeDocument from 'rehype-document'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {unified} from 'unified'
import {reporter} from 'vfile-reporter'
const file = await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeDocument, {title: 'ππ'})
.use(rehypeFormat)
.use(rehypeStringify)
.process('# Hello world!')
console.error(reporter(file))
console.log(String(file))
```
--------------------------------
### processor.freeze()
Source: https://context7.com/unifiedjs/unified/llms.txt
Freezes the processor, executing all attached plugin setup functions and locking its configuration. Frozen processors cannot be reconfigured directly. To extend a frozen processor, call it to get an unfrozen copy.
```APIDOC
## `processor.freeze()` β Freeze a processor
Explicitly freezes the processor, executing all attached plugin setup functions and locking its configuration. Frozen processors cannot be reconfigured. To extend a frozen processor, call it as a function to get an unfrozen copy: `frozenProcessor()`.
Processors freeze automatically when `parse`, `run`, `runSync`, `stringify`, `process`, or `processSync` is called.
```js
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
// Expose a frozen, reusable processor (e.g., as a package export)
export const rehype = unified().use(rehypeParse).use(rehypeStringify).freeze()
// Consumers create an unfrozen copy via calling the frozen processor
import rehypeFormat from 'rehype-format'
const customRehype = rehype().use(rehypeFormat)
const file = await customRehype.process('
')
console.log(String(file))
//
//
//
// This would throw β frozen processors cannot be configured directly:
// rehype.use(rehypeFormat)
// => Error: Cannot call `use` on a frozen processor.
```
```
--------------------------------
### Typing Unified.js Plugins with TypeScript
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Demonstrates how to correctly type Unified.js plugins using the `Plugin` type from TypeScript. Includes examples for plugins accepting options, plugins working on specific tree types, and plugins acting as parsers or compilers.
```js
/**
* @import {Root as HastRoot} from 'hast'
* @import {Root as MdastRoot} from 'mdast'
* @import {Plugin} from 'unified'
*/
/**
* @typedef Options
* Configuration (optional).
* @property {boolean | null | undefined} [someField]
* Some option (optional).
*/
// To type options:
/** @type {Plugin<[(Options | null | undefined)?]>} */
export function myPluginAcceptingOptions(options) {
const settings = options || {}
// `settings` is now `Options`.
}
// To type a plugin that works on a certain tree, without options:
/** @type {Plugin<[], MdastRoot>} */
export function myRemarkPlugin() {
return function (tree, file) {
// `tree` is `MdastRoot`.
}
}
// To type a plugin that transforms one tree into another:
/** @type {Plugin<[], MdastRoot, HastRoot>} */
export function remarkRehype() {
return function (tree) {
// `tree` is `MdastRoot`.
// Result must be `HastRoot`.
}
}
// To type a plugin that defines a parser:
/** @type {Plugin<[], string, MdastRoot>} */
export function remarkParse(options) {}
// To type a plugin that defines a compiler:
/** @type {Plugin<[], HastRoot, string>} */
export function rehypeStringify(options) {}
```
--------------------------------
### Process Markdown with Plugins
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
This example demonstrates processing markdown text through a series of plugins, including parsing, linting, natural language processing, and HTML conversion. It shows how to use the unified API to chain multiple transformations and report any issues found.
```js
import rehypeStringify from 'rehype-stringify'
import remarkParse from 'remark-parse'
import remarkPresetLintMarkdownStyleGuide from 'remark-preset-lint-markdown-style-guide'
import remarkRehype from 'remark-rehype'
import remarkRetext from 'remark-retext'
import retextEnglish from 'retext-english'
import retextEquality from 'retext-equality'
import {unified} from 'unified'
import {reporter} from 'vfile-reporter'
const file = await unified()
.use(remarkParse)
.use(remarkPresetLintMarkdownStyleGuide)
.use(remarkRetext, unified().use(retextEnglish).use(retextEquality))
.use(remarkRehype)
.use(rehypeStringify)
.process('*Emphasis* and _stress_, you guys!')
console.error(reporter(file))
console.log(String(file))
```
--------------------------------
### unified() - Create a new processor
Source: https://context7.com/unifiedjs/unified/llms.txt
Creates a new, independent Processor instance. Processors can be configured with plugins for parsing, transforming, and serializing content. The example shows creating a markdown-to-HTML processor.
```APIDOC
## unified() - Create a new processor
Returns a new unfrozen `Processor` instance copied from the root `unified` export. Each call creates an independent processor that inherits any configuration of its parent but can be further configured without affecting the parent.
```js
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import rehypeDocument from 'rehype-document'
// Create a fully configured markdown-to-HTML processor
const processor = unified()
.use(remarkParse) // sets parser: markdown string β mdast
.use(remarkRehype) // transformer: mdast β hast
.use(rehypeDocument, {title: 'My Page'}) // transformer: wraps in
.use(rehypeStringify) // sets compiler: hast β HTML string
const file = await processor.process('# Hello, world!')
console.log(String(file))
// =>
//
//
// My Page
// Hello, world!
//
```
```
--------------------------------
### Process Markdown File with a Preset
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Use the Unified.js remark processor with a custom preset to process a Markdown file. This example reads a file, applies the preset, and then reports any issues and writes the processed file.
```javascript
import {remark} from 'remark'
import {read, write} from 'to-vfile'
import {reporter} from 'vfile-reporter'
import preset from './preset.js'
const file = await remark()
.use(preset)
.process(await read('example.md'))
console.error(reporter(file))
await write(file)
```
--------------------------------
### Freeze a Processor with `processor.freeze()`
Source: https://context7.com/unifiedjs/unified/llms.txt
Explicitly freeze a processor to execute plugin setup functions and lock its configuration. Frozen processors cannot be reconfigured directly. Consumers create an unfrozen copy by calling the frozen processor.
```javascript
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'
// Expose a frozen, reusable processor (e.g., as a package export)
export const rehype = unified().use(rehypeParse).use(rehypeStringify).freeze()
// Consumers create an unfrozen copy via calling the frozen processor
import rehypeFormat from 'rehype-format'
const customRehype = rehype().use(rehypeFormat)
const file = await customRehype.process('')
console.log(String(file))
//
//
//
// This would throw β frozen processors cannot be configured directly:
// rehype.use(rehypeFormat)
// => Error: Cannot call `use` on a frozen processor.
```
--------------------------------
### Writing a Custom Plugin
Source: https://context7.com/unifiedjs/unified/llms.txt
Plugins are functions that can be used to extend the functionality of a Unified.js processor. They can modify the syntax tree or install custom parsers/compilers.
```APIDOC
## Writing a Custom Plugin
Plugins are functions called with `this` set to the processor. They can optionally return a `Transformer` function for the run phase, or directly set `this.parser` / `this.compiler` to install a parser or compiler.
```js
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkStringify from 'remark-stringify'
/**
* Plugin that converts all heading text to uppercase.
* @param {{ maxDepth?: number }} [options]
*/
function remarkUppercaseHeadings(options = {}) {
const {maxDepth = 6} = options
// Return a transformer to be called during the run phase
return function (tree) {
// Visit every node of type 'heading'
visit(tree, 'heading', function (node) {
if (node.depth <= maxDepth) {
for (const child of node.children) {
if (child.type === 'text') {
child.value = child.value.toUpperCase()
}
}
}
})
}
}
// Async transformer example
function remarkAddTimestamp() {
return async function (tree, file) {
// Simulate async work (e.g., fetching metadata)
await new Promise((resolve) => setTimeout(resolve, 10))
file.data.processedAt = new Date().toISOString()
}
}
const processor = unified()
.use(remarkParse)
.use(remarkUppercaseHeadings, {maxDepth: 2})
.use(remarkAddTimestamp)
.use(remarkStringify)
const file = await processor.process('# hello\n\n## world\n\n### skip me')
console.log(String(file))
// # HELLO
//
// ## WORLD
//
// ### skip me
console.log(file.data.processedAt) // '2024-01-15T10:30:00.000Z'
```
```
--------------------------------
### processor.data([key[, value]])
Source: https://context7.com/unifiedjs/unified/llms.txt
This method allows you to get or set shared data on a processor. It's useful for sharing configuration between plugins. Note that this cannot be called on frozen processors.
```APIDOC
## `processor.data([key[, value]])` β Get/set shared processor data
Stores and retrieves arbitrary data shared across all plugins attached to this processor. Useful for sharing configuration between plugins (e.g., a list of void HTML elements). Cannot be called on frozen processorsβcall the processor first to create an unfrozen copy.
```js
import {unified} from 'unified'
const processor = unified()
.data('htmlVoidElements', ['area', 'br', 'hr', 'img', 'input', 'link', 'meta'])
.data('settings', {position: false})
// Get a single key
console.log(processor.data('htmlVoidElements'))
// ['area', 'br', 'hr', 'img', 'input', 'link', 'meta']
// Get the entire dataset
console.log(processor.data())
// { htmlVoidElements: [...], settings: { position: false } }
// Set the entire dataset (replaces everything)
processor.data({newKey: 'newValue'})
console.log(processor.data()) // { newKey: 'newValue' }
```
```
--------------------------------
### Define a Typed Remark Transformer Plugin
Source: https://context7.com/unifiedjs/unified/llms.txt
Example of a properly typed remark transformer plugin that accepts options and modifies the file message.
```typescript
const myRemarkPlugin: Plugin<[{uppercase?: boolean}], MdastRoot> =
function (options = {}) {
return function (tree, file) {
// tree is typed as MdastRoot
file.message('Plugin executed')
}
}
```
--------------------------------
### Serialize Syntax Tree with rehype-stringify
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Use `processor.stringify` to serialize a syntax tree into its textual representation. This example demonstrates serializing a simple HAST tree to HTML.
```javascript
import {h} from 'hastscript'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'
const tree = h('h1', 'Hello world!')
const document = unified().use(rehypeStringify).stringify(tree)
console.log(document)
```
```html
Hello world!
```
--------------------------------
### Write a Custom Plugin for Unified.js
Source: https://context7.com/unifiedjs/unified/llms.txt
Plugins are functions called with `this` set to the processor. They can return a Transformer for the run phase or directly set `this.parser` / `this.compiler`. This example shows a plugin that converts heading text to uppercase and another that adds a timestamp.
```javascript
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkStringify from 'remark-stringify'
/**
* Plugin that converts all heading text to uppercase.
* @param {{ maxDepth?: number }} [options]
*/
function remarkUppercaseHeadings(options = {}) {
const {maxDepth = 6} = options
// Return a transformer to be called during the run phase
return function (tree) {
// Visit every node of type 'heading'
visit(tree, 'heading', function (node) {
if (node.depth <= maxDepth) {
for (const child of node.children) {
if (child.type === 'text') {
child.value = child.value.toUpperCase()
}
}
}
})
}
}
// Async transformer example
function remarkAddTimestamp() {
return async function (tree, file) {
// Simulate async work (e.g., fetching metadata)
await new Promise((resolve) => setTimeout(resolve, 10))
file.data.processedAt = new Date().toISOString()
}
}
const processor = unified()
.use(remarkParse)
.use(remarkUppercaseHeadings, {maxDepth: 2})
.use(remarkAddTimestamp)
.use(remarkStringify)
const file = await processor.process('# hello\n\n## world\n\n### skip me')
console.log(String(file))
// # HELLO
//
// ## WORLD
//
// ### skip me
console.log(file.data.processedAt) // '2024-01-15T10:30:00.000Z'
```
--------------------------------
### Define a Typed Remark-to-Hast Transformer Plugin
Source: https://context7.com/unifiedjs/unified/llms.txt
Example of a properly typed plugin that transforms a Markdown Abstract Syntax Tree (Mdast) to a HyperText Abstract Syntax Tree (Hast).
```typescript
const myRemarkRehype: Plugin<[], MdastRoot, HastRoot> = function () {
return function (tree): HastRoot {
// tree is MdastRoot; must return HastRoot
return {type: 'root', children: [], properties: {}}
}
}
```
--------------------------------
### Get/Set Shared Processor Data with `processor.data()`
Source: https://context7.com/unifiedjs/unified/llms.txt
Use `processor.data()` to store and retrieve arbitrary data shared across plugins. This method cannot be called on frozen processors. Call the processor first to get an unfrozen copy if it's frozen.
```javascript
import {unified} from 'unified'
const processor = unified()
.data('htmlVoidElements', ['area', 'br', 'hr', 'img', 'input', 'link', 'meta'])
.data('settings', {position: false})
// Get a single key
console.log(processor.data('htmlVoidElements'))
// ['area', 'br', 'hr', 'img', 'input', 'link', 'meta']
// Get the entire dataset
console.log(processor.data())
// { htmlVoidElements: [...], settings: { position: false } }
// Set the entire dataset (replaces everything)
processor.data({newKey: 'newValue'})
console.log(processor.data()) // { newKey: 'newValue' }
```
--------------------------------
### Configure Unified Processor with Plugins and Options
Source: https://context7.com/unifiedjs/unified/llms.txt
Demonstrates various ways to attach plugins to a Unified processor, including single plugins, lists of plugins, plugin tuples with options, presets, and disabling plugins.
```javascript
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkStringify from 'remark-stringify'
// Plugin with options
const processor = unified()
.use(remarkParse, {fragment: true})
// Merge options: result is {fragment: true, position: false}
.use(remarkParse, {position: false})
// List of plugins
unified().use([remarkParse, remarkStringify])
// Plugin tuple in a list
unified().use([[remarkParse, {fragment: true}], remarkStringify])
// Preset: plugins + shared settings
unified().use({
plugins: [remarkParse, remarkStringify],
settings: {bullet: '*', fences: true}
})
// Disable a plugin that was previously added
unified().use(remarkParse).use(remarkParse, false)
```
--------------------------------
### Configure Processor with Plugins and Options
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
The `processor.use` method configures the processor with plugins, presets, or settings. Plugins can be passed individually or in lists, with options. Subsequent calls with the same plugin merge configurations.
```javascript
import {unified} from 'unified'
unified()
// Plugin with options:
.use(pluginA, {x: true, y: true})
// Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):
.use(pluginA, {y: false, z: true})
// Plugins:
.use([pluginB, pluginC])
// Two plugins, the second with options:
.use([pluginD, [pluginE, {}]])
// Preset with plugins and settings:
.use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
// Settings only:
.use({settings: {position: false}})
```
--------------------------------
### Create Markdown-to-HTML Processor with Unified
Source: https://context7.com/unifiedjs/unified/llms.txt
Configure a processor to parse markdown, transform it to HTML, wrap it in a document structure, and stringify it. Requires importing necessary parsers, transformers, and compilers.
```javascript
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import rehypeDocument from 'rehype-document'
// Create a fully configured markdown-to-HTML processor
const processor = unified()
.use(remarkParse) // sets parser: markdown string β mdast
.use(remarkRehype) // transformer: mdast β hast
.use(rehypeDocument, {title: 'My Page'}) // transformer: wraps in
.use(rehypeStringify) // sets compiler: hast β HTML string
const file = await processor.process('# Hello, world!')
console.log(String(file))
```
--------------------------------
### processor.use(plugin[, ...parameters])
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Configures the processor to use a plugin, a list of usable values, or a preset. If the processor is already using a plugin, its configuration is updated based on the provided options.
```APIDOC
## `processor.use(plugin[, ...parameters])`
### Description
Configure the processor to use a plugin, a list of usable values, or a preset.
If the processor is already using a plugin, the previous plugin configuration
is changed based on the options that are passed in.
In other words, the plugin is not added a second time.
> π **Note**: `use` cannot be called on [*frozen*][api-freeze] processors.
> Call the processor first to create a new unfrozen processor.
### Signatures
* `processor.use(preset?)
* `processor.use(list)`
* `processor.use(plugin[, ...parameters])`
### Parameters
* `preset` ([`Preset`][api-preset]) β plugins and settings
* `list` ([`PluggableList`][api-pluggable-list]) β list of usable things
* `plugin` ([`Plugin`][api-plugin]) β plugin
* `parameters` (`Array`) β configuration for `plugin`, typically a
single options object
### Returns
Current processor ([`processor`][api-processor]).
### Example
There are many ways to pass plugins to `.use()`.
This example gives an overview:
```js
import {unified} from 'unified'
unified()
// Plugin with options:
.use(pluginA, {x: true, y: true})
// Passing the same plugin again merges configuration (to `{x: true, y: false, z: true}`):
.use(pluginA, {y: false, z: true})
// Plugins:
.use([pluginB, pluginC])
// Two plugins, the second with options:
.use([pluginD, [pluginE, {}]])
// Preset with plugins and settings:
.use({plugins: [pluginF, [pluginG, {}]], settings: {position: false}})
// Settings only:
.use({settings: {position: false}})
```
```
--------------------------------
### processor.use(plugin[, options]) - Attach a plugin
Source: https://context7.com/unifiedjs/unified/llms.txt
Attaches a plugin to the processor. Plugins can be provided as a single function, a tuple with options, a list of plugins, or a preset object. Options can be merged or disabled.
```APIDOC
## processor.use(plugin[, options]) - Attach a plugin
Configures the processor with a plugin function, a `[plugin, options]` tuple, a list of plugins, or a preset object. If the same plugin is passed a second time, its options are merged (plain objects are deep-merged; non-object values replace). Passing `false` as the option disables a plugin; `true` re-enables it.
```js
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkStringify from 'remark-stringify'
// Plugin with options
const processor = unified()
.use(remarkParse, {fragment: true})
// Merge options: result is {fragment: true, position: false}
.use(remarkParse, {position: false})
// List of plugins
unified().use([remarkParse, remarkStringify])
// Plugin tuple in a list
unified().use([[remarkParse, {fragment: true}], remarkStringify])
// Preset: plugins + shared settings
unified().use({
plugins: [remarkParse, remarkStringify],
settings: {bullet: '*', fences: true}
})
// Disable a plugin that was previously added
unified().use(remarkParse).use(remarkParse, false)
```
```
--------------------------------
### Parse File to Syntax Tree
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Demonstrates using the `parse` method to convert a string into a syntax tree. Note that `parse` freezes the processor if it's not already frozen.
```javascript
import remarkParse from 'remark-parse'
import {unified} from 'unified'
const tree = unified().use(remarkParse).parse('# Hello world!')
console.log(tree)
```
```javascript
{
type: 'root',
children: [
{type: 'heading', depth: 1, children: [Array], position: [Object]}
],
position: {
start: {line: 1, column: 1, offset: 0},
end: {line: 1, column: 15, offset: 14}
}
}
```
--------------------------------
### Process Markdown with Callback
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Demonstrates using the `process` method with a callback function to handle the result of processing a Markdown string. It includes parsing, applying GitHub-specific remark plugins, and stringifying the output.
```javascript
import remarkGithub from 'remark-github'
import remarkParse from 'remark-parse'
import remarkStringify from 'remark-stringify'
import {unified} from 'unified'
import {reporter} from 'vfile-reporter'
unified()
.use(remarkParse)
.use(remarkGithub)
.use(remarkStringify)
.process('@unifiedjs', function (error, file) {
if (error) throw error
if (file) {
console.error(reporter(file))
console.log(String(file))
}
})
```
--------------------------------
### Full Pipeline: Parse, Run, Stringify (Promise-based)
Source: https://context7.com/unifiedjs/unified/llms.txt
Executes the full Unified.js pipeline: parse, run transformers, and stringify. Returns a Promise that resolves with the processed VFile. Use try-catch for error handling and check file.value for output.
```javascript
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkPresetLintMarkdownStyleGuide from 'remark-preset-lint-markdown-style-guide'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import {reporter} from 'vfile-reporter'
const processor = unified()
.use(remarkParse)
.use(remarkPresetLintMarkdownStyleGuide)
.use(remarkRehype)
.use(rehypeStringify)
// Promise-based (recommended)
try {
const file = await processor.process('_Emphasis_ and *stress*.')
console.error(reporter(file)) // Print lint warnings
console.log(String(file)) // Emphasis and stress.
} catch (error) {
console.error(reporter(error)) // Print fatal errors
}
```
--------------------------------
### Process Markdown with Custom Plugin (JavaScript)
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Demonstrates using the custom 'move' plugin within a Unified pipeline. It parses Markdown, transforms it using remark-rehype, changes the file extension with 'move', and stringifies the result.
```javascript
import rehypeStringify from 'rehype-stringify'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {read, write} from 'to-vfile'
import {unified} from 'unified'
import {reporter} from 'vfile-reporter'
import {move} from './move.js'
const file = await unified()
.use(remarkParse)
.use(remarkRehype)
.use(move, {extname: '.html'})
.use(rehypeStringify)
.process(await read('example.md'))
console.error(reporter(file))
await write(file) // Written to `example.html`.
```
--------------------------------
### Configure a Preset with Plugins
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Define a preset configuration for Unified.js, including remark plugins and their settings. This is useful for setting up a consistent linting and transformation pipeline.
```javascript
/**
* @import {Preset} from 'unified'
*/
import remarkCommentConfig from 'remark-comment-config'
import remarkLicense from 'remark-license'
import remarkPresetLintConsistent from 'remark-preset-lint-consistent'
import remarkPresetLintRecommended from 'remark-preset-lint-recommended'
import remarkToc from 'remark-toc'
/** @type {Preset} */
const preset = {
plugins: [
remarkPresetLintRecommended,
remarkPresetLintConsistent,
remarkCommentConfig,
[remarkToc, {maxDepth: 3, tight: true}],
remarkLicense
],
settings: {bullet: '*', emphasis: '*', fences: true},
}
export default preset
```
--------------------------------
### Import Unified in Deno
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Import the unified package in Deno using esm.sh. Ensure you are using a compatible version.
```js
import {unified} from 'https://esm.sh/unified@11'
```
--------------------------------
### `processor.stringify(tree[, file])` β Compile a syntax tree to output
Source: https://context7.com/unifiedjs/unified/llms.txt
Runs only the stringify phase, requiring `processor.compiler` to be set. It accepts a Node and an optional file, returning the compiled value.
```APIDOC
## `processor.stringify(tree[, file])` β Compile a syntax tree to output
Runs only the **stringify phase**. Requires `processor.compiler` to be set (typically via a plugin). Accepts a `Node` and an optional file. Returns the compiled valueβusually a `string` but may be a `Uint8Array` or other value depending on the compiler.
```js
import {unified} from 'unified'
import {h} from 'hastscript'
import rehypeStringify from 'rehype-stringify'
const processor = unified().use(rehypeStringify)
const tree = h('article', [
h('h1', 'Hello world!'),
h('p', ['This is a ', h('strong', 'paragraph'), '.'])
])
const output = processor.stringify(tree)
console.log(output)
// Hello world!
This is a paragraph.
```
```
--------------------------------
### Compile Syntax Tree to Output
Source: https://context7.com/unifiedjs/unified/llms.txt
Runs only the stringify phase to compile a syntax tree to output. Requires a compiler to be set, typically via a plugin. Returns the compiled value, usually a string.
```javascript
import {unified} from 'unified'
import {h} from 'hastscript'
import rehypeStringify from 'rehype-stringify'
const processor = unified().use(rehypeStringify)
const tree = h('article', [
h('h1', 'Hello world!'),
h('p', ['This is a ', h('strong', 'paragraph'), '.'])
])
const output = processor.stringify(tree)
console.log(output)
// Hello world!
This is a paragraph.
```
--------------------------------
### Full Pipeline: Parse, Run, Stringify (Callback-based)
Source: https://context7.com/unifiedjs/unified/llms.txt
Executes the full Unified.js pipeline using a callback function. The callback receives an error and the processed VFile. Ensure proper error handling within the callback.
```javascript
processor.process('# Hello', function (error, file) {
if (error) throw error
console.log(String(file)) // Hello
})
```
--------------------------------
### `processor.process(file[, done])` β Full parse β run β stringify pipeline
Source: https://context7.com/unifiedjs/unified/llms.txt
Executes the complete pipeline: parse, run transformers, and stringify. Returns a Promise or uses a callback, with the result available in `file.value` or `file.result`.
```APIDOC
## `processor.process(file[, done])` β Full parse β run β stringify pipeline
Runs all three phases in sequence: parse, run (transformers), and stringify. Returns a `Promise` (or calls `done(error, file)` if a callback is given). The compiled result is available as `file.value` (for string/Uint8Array output) or `file.result` (for other compiler outputs). Freezes the processor.
```js
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkPresetLintMarkdownStyleGuide from 'remark-preset-lint-markdown-style-guide'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import {reporter} from 'vfile-reporter'
const processor = unified()
.use(remarkParse)
.use(remarkPresetLintMarkdownStyleGuide)
.use(remarkRehype)
.use(rehypeStringify)
// Promise-based (recommended)
try {
const file = await processor.process('_Emphasis_ and *stress*.')
console.error(reporter(file)) // Print lint warnings
console.log(String(file)) // Emphasis and stress.
} catch (error) {
console.error(reporter(error)) // Print fatal errors
}
// Callback-based
processor.process('# Hello', function (error, file) {
if (error) throw error
console.log(String(file)) // Hello
})
```
```
--------------------------------
### Import Unified in Browsers
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Import the unified package in browsers using esm.sh. The ?bundle flag can be used for bundling.
```html
```
--------------------------------
### processor.stringify(tree[, file])
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Compiles a syntax tree into its textual representation. This method performs the stringify phase and freezes the processor if it's not already frozen.
```APIDOC
## `processor.stringify(tree[, file])`
### Description
Compile a syntax tree.
> π **Note**: `stringify` freezes the processor if not already
> *[frozen][api-freeze]*.
>
> π **Note**: `stringify` performs the [stringify phase][overview], not the run
> phase or other phases.
### Parameters
* `tree` ([`Node`][node]) β tree to compile
* `file` ([`Compatible`][vfile-compatible], optional) β file associated
with `node`; any value accepted as `x` in `new VFile(x)`
### Returns
Textual representation of the tree (`Uint8Array` or `string`, see note).
> π **Note**: unified typically compiles by serializing: most compilers
> return `string` (or `Uint8Array`).
> Some compilers, such as the one configured with
> [`rehype-react`][rehype-react], return other values (in this case, a
> React tree).
> If youβre using a compiler that doesnβt serialize, expect different
> result values.
>
> To register custom results in TypeScript, add them to
> [`CompileResultMap`][api-compile-result-map].
### Example
```js
import {h} from 'hastscript'
import rehypeStringify from 'rehype-stringify'
import {unified} from 'unified'
const tree = h('h1', 'Hello world!')
const document = unified().use(rehypeStringify).stringify(tree)
console.log(document)
```
Yields:
```html
Hello world!
```
```
--------------------------------
### Run Transformers on a Syntax Tree (Promise-based)
Source: https://context7.com/unifiedjs/unified/llms.txt
Executes registered transformer plugins on a syntax tree. Returns a Promise that resolves with the transformed tree. Ensure transformers are correctly configured.
```javascript
import {unified} from 'unified'
import {u} from 'unist-builder'
import remarkReferenceLinks from 'remark-reference-links'
const tree = u('root', [
u('paragraph', [
u('link', {url: 'https://example.com'}, [u('text', 'Example')])
])
])
// Promise-based
const transformedTree = await unified().use(remarkReferenceLinks).run(tree)
console.log(transformedTree)
// { type: 'root', children: [
// { type: 'paragraph', children: [{ type: 'linkReference', ... }] },
// { type: 'definition', identifier: '1', url: 'https://example.com' }
// ]}
```
--------------------------------
### Processor Data Management
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Explains how to configure a processor with shared information using the `data` method, and how to retrieve this information.
```APIDOC
## processor.data([key[, value]])
Configure the processor with info available to all plugins.
### Description
Manages data associated with the processor. This data can be accessed by plugins. Information is stored in an object. Setting information cannot occur on *[frozen][api-freeze]* processors.
### Signatures
* `processor = processor.data(key, value)`
* `processor = processor.data(dataset)`
* `value = processor.data(key)`
* `dataset = processor.data()`
### Parameters
* `key` ([`keyof Data`][api-data], optional) β Field to get or set.
* `value` ([`Data[key]`][api-data]) β Value to set for the given key.
* `values` ([`Data`][api-data]) β An object containing multiple key-value pairs to set.
### Returns
The current processor when setting (`processor.data(key, value)` or `processor.data(dataset)`), the value at `key` when getting (`processor.data(key)`), or the entire dataset when getting without a key (`processor.data()`).
### Example
```js
import process from 'node:process'
import concatStream from 'concat-stream'
import {remark} from 'remark'
// Example of creating a new processor and setting data
const newProcessor = remark().data('customKey', 'customValue');
console.log(newProcessor.data('customKey')); // Output: customValue
// Example of linking to stdin and stdout (from original docs)
process.stdin.pipe(
concatStream(function (buf) {
process.stdout.write(String(remark().processSync(buf)))
})
)
```
```
--------------------------------
### Process a file asynchronously with Unified.js
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Use `process` to transform markdown content to HTML. This method handles asynchronous transformers and returns a Promise.
```javascript
import rehypeDocument from 'rehype-document'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import {unified} from 'unified'
const file = await unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeDocument, {title: 'ππ'})
.use(rehypeFormat)
.use(rehypeStringify)
.process('# Hello world!')
console.log(String(file))
```
--------------------------------
### `processor.run(tree[, file][, done])` β Run transformers on a syntax tree
Source: https://context7.com/unifiedjs/unified/llms.txt
Executes registered transformer plugins on a syntax tree. It can be used with Promises or callbacks and freezes the processor.
```APIDOC
## `processor.run(tree[, file][, done])` β Run transformers on a syntax tree
Executes all registered **transformer** plugins on the given syntax tree. Returns a `Promise` if no callback is given, or calls `done(error, tree, file)`. Accepts both sync transformers (return a node or error) and async transformers (return a Promise or use the `next` callback). Freezes the processor.
```js
import {unified} from 'unified'
import {u} from 'unist-builder'
import remarkReferenceLinks from 'remark-reference-links'
const tree = u('root', [
u('paragraph', [
u('link', {url: 'https://example.com'}, [u('text', 'Example')])
])
])
// Promise-based
const transformedTree = await unified().use(remarkReferenceLinks).run(tree)
console.log(transformedTree)
// { type: 'root', children: [
// { type: 'paragraph', children: [{ type: 'linkReference', ... }] },
// { type: 'definition', identifier: '1', url: 'https://example.com' }
// ]}
// Callback-based with error handling
unified()
.use(function () {
return function (tree, file) {
// Async transformer using a Promise
return new Promise((resolve) => {
file.message('custom warning')
resolve(undefined)
})
}
})
.run(tree, function (error, resultTree, file) {
if (error) throw error
console.log(file.messages) // [{ reason: 'custom warning', ... }]
})
```
```
--------------------------------
### `processor.processSync(file)` β Full pipeline, synchronous
Source: https://context7.com/unifiedjs/unified/llms.txt
The synchronous version of `processor.process()`. It throws an error if any plugin is asynchronous and returns the processed VFile directly.
```APIDOC
## `processor.processSync(file)` β Full pipeline, synchronous
Synchronous version of `processor.process()`. Throws if any plugin is asynchronous. Returns the processed `VFile` directly.
```js
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
const processor = unified()
.use(remarkParse)
.use(remarkRehype)
.use(rehypeStringify)
const file = processor.processSync('## Section\n\nContent here.')
console.log(String(file))
// Section
// Content here.
```
```
--------------------------------
### Run transformers on a syntax tree asynchronously
Source: https://github.com/unifiedjs/unified/blob/main/readme.md
Use `run` to transform a syntax tree. This method performs only the run phase and freezes the processor if not already. It returns a Promise resolving with the transformed tree.
```javascript
import remarkReferenceLinks from 'remark-reference-links'
import {unified} from 'unified'
import {u} from 'unist-builder'
const tree = u('root', [
u('paragraph', [
u('link', {href: 'https://example.com'}, [u('text', 'Example Domain')])
])
])
const changedTree = await unified().use(remarkReferenceLinks).run(tree)
console.log(changedTree)
```