### Preset Plugin Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/unified-integration.md Combine multiple plugins and extensions into a single preset for easier configuration. This simplifies the setup for complex markdown features. ```javascript const remarkPreset = { plugins: [ 'remark-gfm', 'remark-frontmatter', ['remark-lint', {rules: {...}}] ] } remark().use(remarkPreset).processSync(markdown) ``` -------------------------------- ### Install remark-cli and plugins Source: https://github.com/remarkjs/remark/blob/main/packages/remark-cli/readme.md Install remark-cli and necessary plugins for linting and table of contents generation using npm. ```sh npm install --save-dev remark-cli remark-preset-lint-consistent remark-preset-lint-recommended remark-toc ``` -------------------------------- ### Real-world Remark CLI Examples Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-cli.md Practical examples for common markdown processing tasks like formatting, linting, and generating tables of contents. ```bash # Format all markdown in project with GFM support remark . -u remark-gfm -u remark-frontmatter -o ``` ```bash # Check markdown with linting rules remark . -u remark-lint -u remark-lint-list-item-indent --frail ``` ```bash # Convert markdown to HTML via AST remark input.md --tree-out | rehype --tree-in --output output.html ``` ```bash # Generate table of contents remark . -u remark-toc -o ``` ```bash # Extract headings as JSON remark . --tree-out --report json | jq '.messages' ``` ```bash # Watch and format on save remark docs -w -u remark-gfm -u remark-frontmatter -o ``` -------------------------------- ### Install Remark Packages Source: https://github.com/remarkjs/remark/blob/main/_autodocs/quick-reference.md Install remark and its related packages for parsing, stringifying, and the command-line interface. ```bash npm install remark npm install remark-parse remark-stringify unified # Individual packages npm install remark-cli # Command-line tool ``` -------------------------------- ### Markdown to HTML Conversion via Multiple Processors Source: https://github.com/remarkjs/remark/blob/main/_autodocs/ecosystem.md This example demonstrates the integration of multiple processors, starting with remark for markdown processing and converting to HTML using remark-rehype and rehype-stringify. It's useful for complex markdown transformations. ```javascript // markdown -> HTML via multiple processors import {remark} from 'remark' import remarkRehype from 'remark-rehype' import rehypeStringify from 'rehype-stringify' const html = await remark() .use(remarkRehype) .use(rehypeStringify) .process(markdown) ``` -------------------------------- ### Remark Plugin Package.json Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/ecosystem.md Provides an example of a package.json configuration for a remark plugin, emphasizing keywords, exports, type, and dependencies. ```json { "name": "remark-my-plugin", "keywords": ["remark", "remark-plugin", "custom"], "exports": "./index.js", "type": "module", "files": ["index.js", "index.d.ts"], "dependencies": { "unist-util-visit": "^4.0.0" } } ``` -------------------------------- ### Example: Basic Usage Source: https://github.com/remarkjs/remark/blob/main/packages/remark-parse/readme.md Demonstrates how to use remark-parse with remark-gfm, remark-rehype, and rehype-stringify to convert markdown to HTML. ```APIDOC ## Basic Markdown to HTML Conversion ### Description This example shows a common workflow: parsing markdown with `remark-parse`, adding GitHub Flavored Markdown (GFM) support with `remark-gfm`, transforming the markdown AST to an HTML AST with `remark-rehype`, and finally stringifying the HTML AST to HTML with `rehype-stringify`. ### Method `process` (on unified processor) ### Endpoint N/A (Client-side or Node.js script) ### Parameters N/A ### Request Body Input markdown string. ### Request Example ```javascript import rehypeStringify from 'rehype-stringify' import remarkGfm from 'remark-gfm' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import {unified} from 'unified' const value = ` # Mercury **Mercury** is the first planet from the [Sun](https://en.wikipedia.org/wiki/Sun) and the smallest planet in the Solar System. ` const file = await unified() .use(remarkParse) .use(remarkGfm) .use(remarkRehype) .use(rehypeStringify) .process(value) console.log(String(file)) ``` ### Response #### Success Response (200) HTML string. #### Response Example ```html

Mercury

Mercury is the first planet from the Sun and the smallest planet in the Solar System.

``` ``` -------------------------------- ### Example: Checking Markdown Consistency Source: https://github.com/remarkjs/remark/blob/main/packages/remark/readme.md This example demonstrates how to use Remark with linting presets to check markdown code style and identify potential issues. ```APIDOC ## Example: Checking Markdown Consistency ### Description The following example checks that markdown code style is consistent and follows some best practices using `remark-preset-lint-consistent` and `remark-preset-lint-recommended`. ### Method `remark().use().use().process()` ### Endpoint N/A (Client-side JavaScript example) ### Parameters N/A ### Request Body Input markdown string: `'1) Hello, _Jupiter_ and *Neptune!*'` ### Request Example ```javascript import {remark} from 'remark' import remarkPresetLintConsistent from 'remark-preset-lint-consistent' import remarkPresetLintRecommended from 'remark-preset-lint-recommended' import {reporter} from 'vfile-reporter' const file = await remark() .use(remarkPresetLintConsistent) .use(remarkPresetLintRecommended) .process('1) Hello, _Jupiter_ and *Neptune!') console.error(reporter(file)) ``` ### Response Reports any linting warnings found in the markdown. #### Success Response (200) - **output** (string) - A formatted string detailing linting warnings and their locations. #### Response Example ```text 1:2 warning Unexpected ordered list marker `)`, expected `.` ordered-list-marker-style remark-lint 1:25-1:34 warning Unexpected emphasis marker `*`, expected `_` emphasis-marker remark-lint [cause]: 1:11-1:20 info Emphasis marker style `'_'` first defined for `'consistent'` here emphasis-marker remark-lint 1:35 warning Unexpected missing final newline character, expected line feed (`\n`) at end of file final-newline remark-lint ⚠ 3 warnings ``` ``` -------------------------------- ### Remark Plugin Order Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/plugin-development.md Demonstrates the correct order for applying Remark.js plugins, emphasizing that extension plugins must come first. ```javascript remark() .use(remarkExtendSyntax) // Must come first .use(remarkTransformNodes) // Transformers can go anywhere .use(remarkStringify) // Built-in, comes last .processSync(markdown) ``` -------------------------------- ### Install remark-stringify with npm Source: https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/readme.md Install the remark-stringify package using npm. This package is ESM only and requires Node.js version 16 or later. ```sh npm install remark-stringify ``` -------------------------------- ### Example: GFM and Frontmatter Support Source: https://github.com/remarkjs/remark/blob/main/packages/remark-parse/readme.md Illustrates how to enable GFM features and frontmatter parsing by combining remark-parse with other plugins. ```APIDOC ## Markdown with GFM and Frontmatter ### Description This example demonstrates how to extend `remark-parse`'s capabilities by using additional plugins: `remark-frontmatter` for parsing YAML frontmatter and `remark-gfm` for GitHub Flavored Markdown features like strikethrough and tables. ### Method `process` (on unified processor) ### Endpoint N/A (Client-side or Node.js script) ### Parameters N/A ### Request Body Input markdown string with frontmatter. ### Request Example ```javascript import rehypeStringify from 'rehype-stringify' import remarkFrontmatter from 'remark-frontmatter' import remarkGfm from 'remark-gfm' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import {unified} from 'unified' const doc = `--- layout: solar-system --- # Hi ~~Mars~~Venus! ` const file = await unified() .use(remarkParse) .use(remarkFrontmatter) .use(remarkGfm) .use(remarkRehype) .use(rehypeStringify) .process(doc) console.log(String(file)) ``` ### Response #### Success Response (200) HTML string, with frontmatter typically ignored by the HTML stringifier. #### Response Example ```html

Hi MarsVenus!

``` ``` -------------------------------- ### Basic Serialization Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-stringify.md Demonstrates the basic usage of `remark-stringify` to convert an MDAST object into markdown text. ```javascript import remarkStringify from 'remark-stringify' import {unified} from 'unified' const ast = { type: 'root', children: [ { type: 'heading', depth: 1, children: [{ type: 'text', value: 'Title' }] }, { type: 'paragraph', children: [{ type: 'text', value: 'Paragraph text.' }] } ] } const processor = unified().use(remarkStringify) const markdown = processor.stringify(ast) console.log(markdown) // # Title // // Paragraph text. ``` -------------------------------- ### Install remark with npm Source: https://github.com/remarkjs/remark/blob/main/packages/remark/readme.md Install the remark package using npm. This package is ESM only. ```sh npm install remark ``` -------------------------------- ### Install remark-cli Source: https://github.com/remarkjs/remark/blob/main/packages/remark-cli/readme.md Install remark-cli using npm. This package is ESM only and requires Node.js version 16 or later. ```sh npm install remark-cli ``` -------------------------------- ### Asynchronous Remark Plugin Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/plugin-development.md An example of an asynchronous remark plugin that can perform operations like fetching data. It uses `async/await` and is processed using `remark().process()`. ```javascript const remarkAsyncPlugin = () => { return async (tree, file) => { // Can await async operations const data = await fetchData(file.path) tree.data = {metadata: data} } } // Use with async processing: const file = await remark().use(remarkAsyncPlugin).process(markdown) ``` -------------------------------- ### Create Preset Remark Processor Source: https://github.com/remarkjs/remark/blob/main/_autodocs/quick-reference.md Create a preset remark processor, which is the recommended approach. This example shows parsing markdown to an AST, stringifying the AST back to markdown, and processing a markdown string to a VFile. ```javascript import {remark} from 'remark' const processor = remark() const tree = processor.parse('# Title') const markdown = processor.stringify(tree) const file = processor.processSync('# Title') ``` -------------------------------- ### Install remark-parse with npm Source: https://github.com/remarkjs/remark/blob/main/packages/remark-parse/readme.md Install the remark-parse package using npm. This package is ESM only and requires Node.js version 16 or later. ```sh npm install remark-parse ``` -------------------------------- ### Extension Plugin Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/unified-integration.md This plugin pattern adds custom syntax parsing and serialization. It's useful for integrating new markdown syntaxes. ```javascript import {gfm} from 'micromark-extension-gfm' import {gfmFromMarkdown} from 'mdast-util-gfm' import {gfmToMarkdown} from 'mdast-util-gfm' const remarkGfm = () => { return (tree, file) => { this.data('micromarkExtensions', [ ...(this.data('micromarkExtensions') || []), gfm() ]) this.data('fromMarkdownExtensions', [ ...(this.data('fromMarkdownExtensions') || []), gfmFromMarkdown() ]) this.data('toMarkdownExtensions', [ ...(this.data('toMarkdownExtensions') || []), gfmToMarkdown() ]) } } // Problem: This only works if called BEFORE parse // Better pattern: return a preset ``` -------------------------------- ### Plugin Data Access Source: https://github.com/remarkjs/remark/blob/main/_autodocs/unified-integration.md Example of a plugin reading and writing data to the processor. Plugins can access processor data using `this.data()`. ```javascript const remarkMyPlugin = () => { return (tree, file) => { const extensions = this.data('micromarkExtensions') || [] this.data('fromMarkdownExtensions', [ ...this.data('fromMarkdownExtensions') || [], myExtension ]) } } ``` -------------------------------- ### Example: Using GFM Extensions with Remark Source: https://github.com/remarkjs/remark/blob/main/_autodocs/types.md Demonstrates how to integrate the GFM (GitHub Flavored Markdown) extensions for parsing and transforming markdown, including tables. This involves registering extensions with the remark processor. ```typescript import {gfm} from 'micromark-extension-gfm' import {gfmFromMarkdown, gfmToMarkdown} from 'mdast-util-gfm' import {remark} from 'remark' const processor = remark() .data('micromarkExtensions', [gfm()]) .data('fromMarkdownExtensions', [gfmFromMarkdown()]) .data('toMarkdownExtensions', [gfmToMarkdown()]) const tree = processor.parse('| a | b | |---|---| | 1 | 2 |') // tree contains GFM table nodes ``` -------------------------------- ### Example Remark Transformer for Headings Source: https://github.com/remarkjs/remark/blob/main/_autodocs/unified-integration.md An example of a remark plugin that transforms the AST to log information about heading nodes. It iterates through the tree's children and checks for nodes of type 'heading'. ```javascript const remarkTransformHeadings = () => { return (tree, file) => { // tree is Root AST // file is VFile with metadata tree.children.forEach(node => { if (node.type === 'heading') { console.log(`Found heading: depth=${node.depth}`) } }) } } ``` -------------------------------- ### Example: Creating a Custom Remark Plugin Source: https://github.com/remarkjs/remark/blob/main/_autodocs/types.md Illustrates how to define a custom plugin for remark. Plugins are functions that receive the processor instance and can return a transformer function to modify the AST. ```typescript import type {Plugin} from 'unified' import type {Root} from 'mdast' const myPlugin: Plugin<[], string, Root> = function() { return (tree: Root, file) => { // Transform tree here return tree } } ``` -------------------------------- ### TypeScript Type Checking Example Source: https://github.com/remarkjs/remark/blob/main/packages/remark/readme.md This example demonstrates how TypeScript expects settings to be registered with `unified`. It shows an expected type error when an invalid option is provided. ```javascript /** * @import {} from 'remark' */ import {unified} from 'unified' // @ts-expect-error: `thisDoesNotExist` is not a valid option. unified().data('settings', {thisDoesNotExist: false}) ``` -------------------------------- ### Markdown to mdast (AST) conversion example Source: https://github.com/remarkjs/remark/blob/main/readme.md Illustrates the transformation of a simple markdown heading with emphasis into its corresponding mdast (markdown Abstract Syntax Tree) JSON representation. Positional information is omitted for brevity. ```markdown ## Hello *Pluto*! ``` ```js { type: 'heading', depth: 2, children: [ {type: 'text', value: 'Hello '}, {type: 'emphasis', children: [{type: 'text', value: 'Pluto'}]} {type: 'text', value: '!'} ] } ``` -------------------------------- ### Traverse AST with unist-util-visit Source: https://github.com/remarkjs/remark/blob/main/_autodocs/ecosystem.md Use `unist-util-visit` to traverse and process nodes in a remark AST. This example shows how to iterate over all 'heading' nodes. ```javascript import {visit} from 'unist-util-visit' visit(tree, 'heading', (node) => { // Process each heading }) ``` -------------------------------- ### Register Micromark Extensions Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-parse.md Plugins can register micromark extensions by setting processor data. This example shows how to register GFM extensions. ```javascript import remarkParse from 'remark-parse' import {gfm} from 'micromark-extension-gfm' import {unified} from 'unified' const processor = unified() .data('micromarkExtensions', [gfm()]) .use(remarkParse) const ast = processor.parse('- [x] Task item') ``` -------------------------------- ### Configure remark Processor Settings Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark.md Configures the remark processor with custom settings for parsing and stringifying markdown. This example demonstrates options like `closeAtx`, `setext`, and custom emphasis characters. ```javascript import {remark} from 'remark' const output = remark() .data('settings', { closeAtx: true, // Add closing # marks to headings setext: true, // Use setext-style headings for h1/h2 strong: '_', // Use underscores for strong emphasis emphasis: '_' }) .processSync('# Hello\n\nSome **bold** text') .toString() console.log(output) ``` -------------------------------- ### Processing Markdown to String with Remark Source: https://github.com/remarkjs/remark/blob/main/_autodocs/types.md An example demonstrating how to use the remark processor to parse a markdown string and log its string representation and any associated messages. ```typescript import {remark} from 'remark' const file = remark().processSync('# Title') console.log(String(file)) // "# Title\n" console.log(file.messages) // [] console.log(file.history) // [] ``` -------------------------------- ### Process Markdown with Plugins using remark Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark.md Processes markdown asynchronously using the remark processor and applies plugins. This example uses `remark-toc` to automatically add a table of contents. ```javascript import {remark} from 'remark' import remarkToc from 'remark-toc' const markdown = ' # Main Title ## Section 1 Content here. ## Section 2 More content. ' const file = await remark() .use(remarkToc) .process(markdown) console.log(String(file)) ``` -------------------------------- ### Convert Markdown to Man Page Source: https://github.com/remarkjs/remark/blob/main/packages/remark-parse/readme.md Use unified with remark-parse and remark-man to serialize Markdown content into roff format for man pages. Ensure remark-man is installed. ```js import remarkMan from 'remark-man' import remarkParse from 'remark-parse' import {unified} from 'unified' const doc = ` # titan(7) -- largest moon of saturn Titan is the largest moon… ` const file = await unified().use(remarkParse).use(remarkMan).process(doc) console.log(String(file)) ``` -------------------------------- ### Test a Remark Plugin Source: https://github.com/remarkjs/remark/blob/main/_autodocs/plugin-development.md Example of how to test a Remark plugin using node:test. Ensure your plugin is imported and used within the remark processor. ```javascript import test from 'node:test' import {remark} from 'remark' import remarkMyPlugin from './my-plugin.js' test('my plugin', async (t) => { await t.test('should transform headings', () => { const input = '# Title\n\nText' const result = remark() .use(remarkMyPlugin) .processSync(input) .toString() assert.match(result, /custom-heading/) }) }) ``` -------------------------------- ### Configure remark-stringify Options Source: https://github.com/remarkjs/remark/blob/main/_autodocs/types.md Example of how to configure remark-stringify options by passing them to the `data('settings', ...)` method. This snippet demonstrates setting custom list bullet, emphasis marker, and enabling setext headings. ```typescript import {remark} from 'remark' const options = { bullet: '+', emphasis: '_', setext: true } const output = remark() .data('settings', options) .processSync('# Title').toString() ``` -------------------------------- ### Configure Alternative List Markers Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-stringify.md Customize list markers using options like 'bullet', 'bulletOrdered', 'rule', 'ruleRepetition', and 'ruleSpaces'. This example demonstrates using ')', '-', and specific spacing for lists. ```javascript processor.data('settings', { bullet: '+', bulletOrdered: ')', rule: '-', ruleRepetition: 5, ruleSpaces: true }) // Produces: // + Item 1 // 1) First // 2) Second // // - - - - - ``` -------------------------------- ### Registering a Custom Node Handler Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-stringify.md Provide handlers for custom node types to define how they are serialized to Markdown. This example shows how to register a handler for a 'customNode' type. ```javascript processor.data('settings', { handlers: { customNode(state, node) { // Return markdown string for custom node return `[CUSTOM: ${node.id}]` } } }) ``` -------------------------------- ### Pass Options to remark-stringify Source: https://github.com/remarkjs/remark/blob/main/packages/remark/readme.md When using remark-stringify manually, pass options to `use`. Since remark-stringify is already used in remark, pass options to `data` instead. This example shows how to configure remark-stringify's list markers and heading styles. ```javascript import {remark} from 'remark' const value = ` # Moons of Neptune 1. Naiad 2. Thalassa 3. Despine 4. … ` const file = await remark() .data('settings', { bulletOrdered: ')', incrementListMarker: false, setext: true }) .process(value) console.log(String(file)) ``` ```markdown Moons of Neptune ================ 1) Naiad 1) Thalassa 1) Despine 1) … ``` -------------------------------- ### Get Node Position Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/types.md Demonstrates how to parse markdown and access the position information of a specific node, such as a heading. ```typescript const root = remark().parse('# Title') const heading = root.children[0] console.log(heading.position) // { // start: { line: 1, column: 0, offset: 0 }, // end: { line: 1, column: 8, offset: 8 } // } ``` -------------------------------- ### Project Initialization Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-cli.md Initialize remark configuration and ignore files using shell commands. ```bash # Initialize remark config and ignore files echo '["remark-gfm"]' > .remarkrc echo 'node_modules/' > .remarkignore ``` -------------------------------- ### Remark CLI Configuration and Settings Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-cli.md Pass settings directly via the command line or load configurations from a .remarkrc file. ```bash # Pass settings directly remark input.md -s bullet:+ -s emphasis:_ -o ``` ```bash # Load from config file remark . --rc-path .remarkrc -o ``` ```bash # Disable config file search remark . --no-config -o ``` -------------------------------- ### Registering Settings with Unified Source: https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/readme.md Demonstrates how to register custom settings with unified. Note that `thisDoesNotExist` is an invalid option and will cause a TypeScript error. ```javascript /** * @import {} from 'remark-stringify' */ import {unified} from 'unified' // @ts-expect-error: `thisDoesNotExist` is not a valid option. unified().data('settings', {thisDoesNotExist: false}) ``` -------------------------------- ### remark-cli Help Output Source: https://github.com/remarkjs/remark/blob/main/packages/remark-cli/readme.md Displays the usage information and available options for the remark-cli command. ```text Usage: remark [options] [path | glob ...] CLI to process markdown with remark Options: --[no-]color specify color in report (on by default) --[no-]config search for configuration files (on by default) -e --ext specify extensions --file-path specify path to process as -f --frail exit with 1 on warnings -h --help output usage information --[no-]ignore search for ignore files (on by default) -i --ignore-path specify ignore file --ignore-path-resolve-from cwd|dir resolve patterns in `ignore-path` from its directory or cwd --ignore-pattern specify ignore patterns --inspect output formatted syntax tree -o --output [path] specify output location -q --quiet output only warnings and errors -r --rc-path specify configuration file --report specify reporter -s --setting specify settings -S --silent output only errors --silently-ignore do not fail when given ignored files --[no-]stdout specify writing to stdout (on by default) -t --tree specify input and output as syntax tree --tree-in specify input as syntax tree --tree-out output syntax tree -u --use use plugins --verbose report extra info for messages -v --version output version number -w --watch watch for changes and reprocess Examples: # Process `input.md` $ remark input.md -o output.md # Pipe $ remark < input.md > output.md # Rewrite all applicable files $ remark . -o ``` -------------------------------- ### Bulk Formatting Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-cli.md Format an entire directory of markdown files using the remark CLI. ```bash # Format entire docs directory remark docs -o -u remark-gfm -u remark-prettier ``` -------------------------------- ### Serialized Markdown Output Source: https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/readme.md The output generated by the example code, showing the markdown representation of the input HTML. ```markdown # Uranus **Uranus** is the seventh [planet](/wiki/Planet "Planet") from the Sun and is a gaseous cyan [ice giant](/wiki/Ice_giant "Ice giant"). ``` -------------------------------- ### remark (binary) Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-cli.md The command-line entry point for remark processing. ```APIDOC ## remark (binary) ### Description The command-line entry point for remark processing. ### Usage ```bash remark [options] [path | glob ...] ``` ### Options All options are case-insensitive and can use `--no-` prefix to negate boolean flags. #### File Selection | Option | Short | Argument | Default | Description | |--------|-------|----------|---------|-------------| | `--ext` | `-e` | `extensions` | `.md` | Comma-separated file extensions to process | | `--file-path` | — | `path` | — | Treat input as coming from a file at `path` (useful for stdin) | | `--ignore-pattern` | — | `globs` | — | Glob patterns to ignore (can be repeated) | | `--ignore-path` | `-i` | `path` | — | Path to ignore file (`.remarkignore`) | | `--ignore-path-resolve-from` | — | `cwd` or `dir` | `cwd` | Resolve ignore patterns from working dir or ignore file's directory | #### Processing | Option | Short | Argument | Default | Description | |--------|-------|----------|---------|-------------| | `--setting` | `-s` | `settings` | — | JSON settings for processor (can be repeated) | | `--use` | `-u` | `plugins` | — | Plugins to load (e.g., `remark-gfm`) (can be repeated) | | `--rc-path` | `-r` | `path` | `.remarkrc` | Path to config file | | `--tree` | `-t` | — | — | Use AST as both input and output format | | `--tree-in` | — | — | — | Parse input as AST (tree) | | `--tree-out` | — | — | — | Output AST (tree) instead of markdown | #### Output | Option | Short | Argument | Default | Description | |--------|-------|----------|---------|-------------| | `--output` | `-o` | `[path]` | — | Write to file or directory; no arg writes to same file | | `--[no-]stdout` | — | — | on | Write to stdout (disable with `--no-stdout`) | | `--quiet` | `-q` | — | — | Only output warnings and errors | | `--silent` | `-S` | — | — | Only output errors | #### Reporting & Diagnostics | Option | Short | Argument | Default | Description | |--------|-------|----------|---------|-------------| | `--[no-]color` | — | — | on | Use colored output (disable with `--no-color`) | | `--report` | — | `reporter` | — | Reporter to use: `json`, `ndjson`, `json-5`, `pretty` (from vfile-reporter) | | `--frail` | `-f` | — | — | Exit with code 1 on any warning (normally only on errors) | | `--verbose` | — | — | — | Report extra information for messages | #### Configuration & Control | Option | Short | Argument | Default | Description | |--------|-------|----------|---------|-------------| | `--[no-]config` | — | — | on | Search for config files (disable with `--no-config`) | | `--[no-]ignore` | — | — | on | Search for ignore files (disable with `--no-ignore`) | | `--silently-ignore` | — | — | — | Do not fail when given ignored files | | `--watch` | `-w` | — | — | Watch files and reprocess on changes | | `--inspect` | — | — | — | Output formatted AST instead of markdown | | `--help` | `-h` | — | — | Show help message | | `--version` | `-v` | — | — | Show version numbers | ``` -------------------------------- ### Import remark-stringify in the Browser Source: https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/readme.md Import remark-stringify in the browser using esm.sh with the ?bundle flag for easier integration. ```html ``` -------------------------------- ### Transform Markdown (Generic) Source: https://github.com/remarkjs/remark/blob/main/_autodocs/index.md A generic example of transforming markdown by modifying its AST. See plugin development for transformation patterns. ```javascript remark() .use(() => (tree) => { // Modify tree }) .processSync(markdown) ``` -------------------------------- ### Register MDAST Extensions Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-parse.md Plugins can register mdast-util-from-markdown extensions. This example registers GFM extensions for parsing Markdown tables. ```javascript import remarkParse from 'remark-parse' import {gfmFromMarkdown} from 'mdast-util-gfm' import {unified} from 'unified' const processor = unified() .data('fromMarkdownExtensions', [gfmFromMarkdown()]) .use(remarkParse) const ast = processor.parse('# Heading\n\n| a | b |\n|---|---| | 1 | 2 |') ``` -------------------------------- ### Basic Markdown Parsing with remark-parse Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-parse.md Demonstrates basic markdown string parsing into an AST using remark-parse and unified. ```javascript import remarkParse from 'remark-parse' import {unified} from 'unified' const processor = unified().use(remarkParse) const ast = processor.parse('# Heading\n\nParagraph text.') console.log(ast) // { // type: 'root', // children: [ // { type: 'heading', depth: 1, children: [...] }, // { type: 'paragraph', children: [...] } // ] // } ``` -------------------------------- ### Import remark in the browser Source: https://github.com/remarkjs/remark/blob/main/packages/remark/readme.md Import the remark package in the browser using esm.sh with bundling. ```html ``` -------------------------------- ### Transform Markdown AST Source: https://github.com/remarkjs/remark/blob/main/_autodocs/index.md Transform markdown by modifying its AST. This example uses `unist-util-visit` to make all headings one level deeper. ```javascript import {visit} from 'unist-util-visit' remark() .use(() => (tree) => { visit(tree, 'heading', (node) => { node.depth++ // Make all headings one level deeper }) }) .processSync('# Title') ``` -------------------------------- ### Add Remark Plugins (GFM) Source: https://github.com/remarkjs/remark/blob/main/_autodocs/index.md Use remark with plugins, such as remark-gfm for GitHub Flavored Markdown. This example parses a GFM table. ```javascript import remarkGfm from 'remark-gfm' remark() .use(remarkGfm) .processSync('| a | b | |---|---| | 1 | 2 |') ``` -------------------------------- ### Watching and Development with Remark CLI Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-cli.md Enable watching mode to automatically reprocess files on changes, with options for verbose output. ```bash # Watch files for changes remark . -w -o ``` ```bash # Watch with debug output remark . -w -o --verbose ``` -------------------------------- ### Transform-only Plugin Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/unified-integration.md Use this pattern to modify the AST without affecting parsing or serialization. It's suitable for simple AST transformations. ```javascript import {visit} from 'unist-util-visit' const remarkTransformLinks = () => { return (tree) => { visit(tree, 'link', (node) => { // Add target="_blank" to all links if (!node.data) node.data = {} node.data.hProperties = {target: '_blank'} }) } } remark().use(remarkTransformLinks).processSync(markdown) ``` -------------------------------- ### Markdown Processing Pipeline Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-parse.md Illustrates a complete processing pipeline using remark-parse for input and remark-stringify for output with unified. ```javascript import remarkParse from 'remark-parse' import remarkStringify from 'remark-stringify' import {unified} from 'unified' const markdown = '# Hello\n\nWorld' const processor = unified() .use(remarkParse) .use(remarkStringify) const result = processor.processSync(markdown).toString() console.log(result) // '# Hello\n\nWorld\n' ``` -------------------------------- ### Custom Micromark Extension for Tokenizing Source: https://github.com/remarkjs/remark/blob/main/_autodocs/plugin-development.md Defines a custom micromark extension to tokenize content starting with '{' and ending with '}'. This function should be used within `remarkExtendSyntax`. ```javascript function customMicromarkExtension() { return { text: { 123: { // charCode for '{' tokenize: tokenizeCustom } } } function tokenizeCustom(effects, ok, nok) { return start function start(code) { // code is the character code if (code !== 123) return nok(code) // '{' effects.consume(code) return inside } function inside(code) { if (code === 125) { // '}' effects.consume(code) effects.exit('customToken') return ok(code) } // Continue consuming effects.consume(code) return inside } } } ``` -------------------------------- ### Import remark-stringify in Deno Source: https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/readme.md Import remark-stringify in Deno using esm.sh. This provides an ESM-compatible module. ```js import remarkStringify from 'https://esm.sh/remark-stringify@11' ``` -------------------------------- ### Registering Remark Core Plugins Source: https://github.com/remarkjs/remark/blob/main/_autodocs/unified-integration.md This snippet shows how to register the core remark plugins, `remark-parse` and `remark-stringify`, with a unified processor. The order of registration is crucial for correct processing. ```javascript import {remark} from 'remark' import remarkParse from 'remark-parse' import remarkStringify from 'remark-stringify' const processor = unified() .use(remarkParse) .use(remarkStringify) .freeze() ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/remarkjs/remark/blob/main/_autodocs/quick-reference.md Process markdown files and directories using basic remark CLI commands. Use -o to write output to a file. ```bash # Process and output remark input.md ``` ```bash # Process and write remark input.md -o output.md ``` ```bash # Process directory remark . -o ``` ```bash # Process with plugin remark . -u remark-gfm -o ``` ```bash # Pass settings remark . -s bullet:+ -s emphasis:_ -o ``` -------------------------------- ### Extract Text from MDAST Nodes Source: https://github.com/remarkjs/remark/blob/main/_autodocs/ecosystem.md Use `mdast-util-to-string` to extract plain text content from MDAST nodes. This is useful for getting the text of a heading or other elements. ```javascript import {toString} from 'mdast-util-to-string' const text = toString(heading) ``` -------------------------------- ### Import remark in Deno Source: https://github.com/remarkjs/remark/blob/main/packages/remark/readme.md Import the remark package in Deno using esm.sh. ```js import {remark} from 'https://esm.sh/remark@15' ``` -------------------------------- ### Minimal Remark Plugin Structure Source: https://github.com/remarkjs/remark/blob/main/_autodocs/plugin-development.md A basic remark plugin function that transforms the AST and logs file information. It can be used as a starting point for custom transformations. ```javascript const remarkMinimalPlugin = () => { return (tree, file) => { // Transform tree here console.log('Processing:', file.path) } } // Usage: import {remark} from 'remark' remark().use(remarkMinimalPlugin).processSync(markdown) ``` -------------------------------- ### Integrating Plugins with Remark CLI Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-cli.md Add functionality to Remark by enabling plugins like remark-gfm and remark-frontmatter, including plugins with options. ```bash # Add GFM support remark . -u remark-gfm -o ``` ```bash # Add multiple plugins remark input.md -u remark-gfm -u remark-frontmatter -o ``` ```bash # Plugins with options remark . -u remark-gfm -u "remark-lint:false" -o ``` -------------------------------- ### Position and Point Interfaces Source: https://github.com/remarkjs/remark/blob/main/_autodocs/types.md These interfaces define the structure for tracking the start and end positions of nodes in source text, including line, column, and offset information. ```typescript interface Position { start: Point end: Point } interface Point { line: number column: number offset: number } ``` -------------------------------- ### Run remark format script Source: https://github.com/remarkjs/remark/blob/main/packages/remark-cli/readme.md Execute the 'format' npm script to check and format markdown files in your project. ```sh npm run format ``` -------------------------------- ### Create Custom Remark Processor Source: https://github.com/remarkjs/remark/blob/main/_autodocs/quick-reference.md Create a custom remark processor using unified, and configure it with remark-parse and remark-stringify plugins. ```javascript import {unified} from 'unified' import remarkParse from 'remark-parse' import remarkStringify from 'remark-stringify' const processor = unified() .use(remarkParse) .use(remarkStringify) ``` -------------------------------- ### Markdown to HTML Conversion with Remark and Rehype Source: https://github.com/remarkjs/remark/blob/main/_autodocs/ecosystem.md Use this snippet to convert markdown to HTML by chaining remark, remark-rehype, and rehype-stringify processors. Ensure all necessary packages are installed. ```javascript import {remark} from 'remark' import remarkRehype from 'remark-rehype' import rehypeStringify from 'rehype-stringify' const html = await remark() .use(remarkRehype) .use(rehypeStringify) .process(markdown) ``` -------------------------------- ### Basic Markdown to HTML Conversion Source: https://github.com/remarkjs/remark/blob/main/packages/remark-parse/readme.md Converts markdown text to HTML using remark-parse, remark-gfm, remark-rehype, and rehype-stringify. This example demonstrates a typical pipeline for processing markdown. ```js import rehypeStringify from 'rehype-stringify' import remarkGfm from 'remark-gfm' import remarkParse from 'remark-parse' import remarkRehype from 'remark-rehype' import {unified} from 'unified' const value = ` # Mercury **Mercury** is the first planet from the [Sun](https://en.wikipedia.org/wiki/Sun) and the smallest planet in the Solar System. ` const file = await unified() .use(remarkParse) .use(remarkGfm) .use(remarkRehype) .use(rehypeStringify) .process(value) console.log(String(file)) ``` -------------------------------- ### Basic Serialization with remark-stringify Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-stringify.md Demonstrates basic serialization of an MDAST to markdown text using `remark-stringify`. This is useful for converting a programmatically generated AST back into a markdown string. ```typescript declare const remarkStringify: Plugin< [(Readonly | null | undefined)?], Root, string > ``` ```javascript function remarkStringify(options?: Options): void ``` ```javascript import remarkStringify from 'remark-stringify' import {unified} from 'unified' const ast = { type: 'root', children: [ { type: 'heading', depth: 1, children: [{ type: 'text', value: 'Title' }] }, { type: 'paragraph', children: [{ type: 'text', value: 'Paragraph text.' }] } ] } const processor = unified().use(remarkStringify) const markdown = processor.stringify(ast) console.log(markdown) // # Title // // Paragraph text. ``` -------------------------------- ### Remark Import Patterns Source: https://github.com/remarkjs/remark/blob/main/_autodocs/quick-reference.md Import the core remark processor, individual plugins like remark-parse and remark-stringify, and utility functions such as visit and toString. ```javascript // Core processor import {remark} from 'remark' // Individual plugins import remarkParse from 'remark-parse' import remarkStringify from 'remark-stringify' import {unified} from 'unified' // Utilities import {visit} from 'unist-util-visit' import {toString} from 'mdast-util-to-string' ``` -------------------------------- ### Add Badges and Links to Markdown Source: https://github.com/remarkjs/remark/blob/main/_autodocs/common-use-cases.md Inserts badges and links into a Markdown document, typically after the main heading. This example shows how to create and insert paragraph nodes containing badge markdown. ```javascript import {remark} from 'remark' import {visit} from 'unist-util-visit' const addBadges = (options = {}) => { const {repo, style = 'flat'} = options return (tree) => { // Find where to insert badges (after main heading) let insertIndex = 0 visit(tree, 'heading', (node, index) => { if (node.depth === 1) insertIndex = index + 1 }) // Create badge nodes const badges = [ `[![Build Status](https://img.shields.io/badge/build-passing-${style})]`, `[![License](https://img.shields.io/badge/license-MIT-${style})]` ] tree.children.splice(insertIndex, 0, { type: 'paragraph', children: [{ type: 'text', value: badges.join(' ') }] }) } } const markdown = '# My Project\n\nDescription' const withBadges = remark() .use(addBadges, {repo: 'user/project'}) .processSync(markdown) .toString() ``` -------------------------------- ### VFile Methods Source: https://github.com/remarkjs/remark/blob/main/_autodocs/types.md Illustrates common methods for interacting with a VFile object, including string coercion and message creation. ```typescript String(file) // Coerce to string (returns file.value) file.toString() // Convert to string file.fail(reason, ...) // Create error message file.message(reason, ...) // Create warning/info message ``` -------------------------------- ### Register remark-stringify Settings Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-stringify.md Register remark-stringify with unified's settings system to customize Markdown output. This example sets custom characters for bullet points, emphasis, and strong text. ```javascript import {remark} from 'remark' const processor = remark().data('settings', { bullet: '+', emphasis: '_', strong: '_' }) const markdown = processor.processSync('# Title').toString() ``` -------------------------------- ### Remark Debugging Plugin Example Source: https://github.com/remarkjs/remark/blob/main/_autodocs/plugin-development.md A simple Remark plugin that logs the syntax tree, node count, and messages to the console. This is useful for understanding the structure of the Markdown AST and identifying potential issues. ```javascript const remarkDebug = () => { return (tree, file) => { // Pretty-print tree console.log(JSON.stringify(tree, null, 2)) // Count nodes let count = 0 visit(tree, () => {count++}) console.log('Total nodes:', count) // Check messages console.log('Messages:', file.messages) } } ``` -------------------------------- ### Remark Utilities Imports Source: https://github.com/remarkjs/remark/blob/main/_autodocs/quick-reference.md Import common utilities for working with Remark's AST. These include functions for visiting nodes, extracting text, finding and replacing, removing positions, and creating elements. ```javascript // Visit tree nodes import {visit} from 'unist-util-visit' // Extract text from nodes import {toString} from 'mdast-util-to-string' // Find and replace import {findAndReplace} from 'mdast-util-find-and-replace' // Remove positions import {removePosition} from 'unist-util-remove-position' // Create elements import {h} from 'hastscript' // For HTML AST (HAST) ``` -------------------------------- ### Render Markdown via Express.js API Source: https://github.com/remarkjs/remark/blob/main/_autodocs/common-use-cases.md Create an Express.js API endpoint to receive Markdown text and return rendered HTML. This example uses express.text() middleware to parse the request body. ```javascript import express from 'express' import {remark} from 'remark' import remarkRehype from 'remark-rehype' import rehypeStringify from 'rehype-stringify' const app = express() app.post('/api/render-markdown', express.text(), async (req, res) => { try { const html = await remark() .use(remarkRehype) .use(rehypeStringify) .process(req.body) res.json({html: String(html)}) } catch (error) { res.status(400).json({error: error.message}) } }) app.listen(3000) ``` -------------------------------- ### Register remark-parse Settings Source: https://github.com/remarkjs/remark/blob/main/_autodocs/remark-parse.md Register remark-parse with unified and pass options via `.data('settings', {...})`. Options are derived from mdast-util-from-markdown. ```javascript import {remark} from 'remark' const processor = remark().data('settings', { // Options from mdast-util-from-markdown can be passed here }) ``` -------------------------------- ### Write Custom Remark Plugins Source: https://github.com/remarkjs/remark/blob/main/_autodocs/quick-reference.md Create custom Remark plugins by defining a function that accepts options and returns a transformer function. This transformer function receives the AST and file object to perform transformations. ```javascript const myPlugin = (options = {}) => { return (tree, file) => { // Transform tree // Access processor via 'this' // Add messages via file.message() } } remark().use(myPlugin, {option: 'value'}).process(markdown) ``` -------------------------------- ### Import remark-parse in Deno Source: https://github.com/remarkjs/remark/blob/main/packages/remark-parse/readme.md Import remark-parse in Deno using esm.sh. This provides an ESM-compatible import for use in Deno projects. ```js import remarkParse from 'https://esm.sh/remark-parse@11' ```