• Stars
    star
    247
  • Rank 164,117 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated almost 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

remark plugin to support directives

remark-directive

Build Coverage Downloads Size Sponsors Backers Chat

remark plugin to support the generic directives proposal (:cite[smith04], ::youtube[Video of a cat in a box]{v=01ab2cd3efg}, and such).

Contents

What is this?

This package is a unified (remark) plugin to add support for directives: one syntax for arbitrary extensions in markdown. You can use this with some more code to match your specific needs, to allow for anything from callouts, citations, styled blocks, forms, embeds, spoilers, etc.

unified is a project that transforms content with abstract syntax trees (ASTs). remark adds support for markdown to unified. mdast is the markdown AST that remark uses. micromark is the markdown parser we use. This is a remark plugin that adds support for the directives syntax and AST to remark.

When should I use this?

Directives are one of the four ways to extend markdown: an arbitrary extension syntax (see Extending markdown in micromark’s docs for the alternatives and more info). This mechanism works well when you control the content: who authors it, what tools handle it, and where it’s displayed. When authors can read a guide on how to embed a tweet but are not expected to know the ins and outs of HTML or JavaScript. Directives don’t work well if you don’t know who authors content, what tools handle it, and where it ends up. Example use cases are a docs website for a project or product, or blogging tools and static site generators.

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:

npm install remark-directive

In Deno with esm.sh:

import remarkDirective from 'https://esm.sh/remark-directive@2'

In browsers with esm.sh:

<script type="module">
  import remarkDirective from 'https://esm.sh/remark-directive@2?bundle'
</script>

Use

Say we have the following file, example.md:

:::main{#readme}

Lorem:br
ipsum.

::hr{.red}

A :i[lovely] language know as :abbr[HTML]{title="HyperText Markup Language"}.

:::

And our module, example.js, looks as follows:

import {read} from 'to-vfile'
import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkDirective from 'remark-directive'
import remarkRehype from 'remark-rehype'
import rehypeFormat from 'rehype-format'
import rehypeStringify from 'rehype-stringify'
import {visit} from 'unist-util-visit'
import {h} from 'hastscript'

main()

async function main() {
  const file = await unified()
    .use(remarkParse)
    .use(remarkDirective)
    .use(myRemarkPlugin)
    .use(remarkRehype)
    .use(rehypeFormat)
    .use(rehypeStringify)
    .process(await read('example.md'))

  console.log(String(file))
}

// This plugin is an example to let users write HTML with directives.
// It’s informative but rather useless.
// See below for others examples.
/** @type {import('unified').Plugin<[], import('mdast').Root>} */
function myRemarkPlugin() {
  return (tree) => {
    visit(tree, (node) => {
      if (
        node.type === 'textDirective' ||
        node.type === 'leafDirective' ||
        node.type === 'containerDirective'
      ) {
        const data = node.data || (node.data = {})
        const hast = h(node.name, node.attributes)

        data.hName = hast.tagName
        data.hProperties = hast.properties
      }
    })
  }
}

Now, running node example yields:

<main id="readme">
  <p>Lorem<br>ipsum.</p>
  <hr class="red">
  <p>A <i>lovely</i> language know as <abbr title="HyperText Markup Language">HTML</abbr>.</p>
</main>

API

This package exports no identifiers. The default export is remarkDirective.

unified().use(remarkDirective)

Configures remark so that it can parse and serialize directives. Doesn’t handle the directives: create your own plugin to do that.

Examples

Example: YouTube

This example shows how directives can be used for YouTube embeds. It’s based on the example in Use above. If myRemarkPlugin was replaced with this function:

// This plugin is an example to turn `::youtube` into iframes.
/** @type {import('unified').Plugin<[], import('mdast').Root>} */
function myRemarkPlugin() {
  return (tree, file) => {
    visit(tree, (node) => {
      if (
        node.type === 'textDirective' ||
        node.type === 'leafDirective' ||
        node.type === 'containerDirective'
      ) {
        if (node.name !== 'youtube') return

        const data = node.data || (node.data = {})
        const attributes = node.attributes || {}
        const id = attributes.id

        if (node.type === 'textDirective') file.fail('Text directives for `youtube` not supported', node)
        if (!id) file.fail('Missing video id', node)

        data.hName = 'iframe'
        data.hProperties = {
          src: 'https://www.youtube.com/embed/' + id,
          width: 200,
          height: 200,
          frameBorder: 0,
          allow: 'picture-in-picture',
          allowFullScreen: true
        }
      }
    })
  }
}

…and example.md contains:

# Cat videos

::youtube[Video of a cat in a box]{#01ab2cd3efg}

…then running node example yields:

<h1>Cat videos</h1>
<iframe src="https://www.youtube.com/embed/01ab2cd3efg" width="200" height="200" frameborder="0" allow="picture-in-picture" allowfullscreen>Video of a cat in a box</iframe>

Example: Styled blocks

Note: This is sometimes called admonitions, callouts, etc.

This example shows how directives can be used to style blocks. It’s based on the example in Use above. If myRemarkPlugin was replaced with this function:

// This plugin is an example to turn `::note` into divs, passing arbitrary
// attributes.
/** @type {import('unified').Plugin<[], import('mdast').Root>} */
function myRemarkPlugin() {
  return (tree) => {
    visit(tree, (node) => {
      if (
        node.type === 'textDirective' ||
        node.type === 'leafDirective' ||
        node.type === 'containerDirective'
      ) {
        if (node.name !== 'note') return

        const data = node.data || (node.data = {})
        const tagName = node.type === 'textDirective' ? 'span' : 'div'

        data.hName = tagName
        data.hProperties = h(tagName, node.attributes).properties
      }
    })
  }
}

…and example.md contains:

# How to use xxx

You can use xxx.

:::note{.warning}
if you chose xxx, you should also use yyy somewhere…
:::

…then running node example yields:

<h1>How to use xxx</h1>
<p>You can use xxx.</p>
<div class="warning">
  <p>if you chose xxx, you should also use yyy somewhere…</p>
</div>

Syntax

This plugin applies a micromark extensions to parse the syntax. See its readme for parse details:

Syntax tree

This plugin applies one mdast utility to build and serialize the AST. See its readme for the node types supported in the tree:

Types

This package is fully typed with TypeScript. If you’re working with the syntax tree, make sure to import this plugin somewhere in your types, as that registers the new node types in the tree.

/** @typedef {import('remark-directive')} */

import {visit} from 'unist-util-visit'

/** @type {import('unified').Plugin<[], import('mdast').Root>} */
export default function myRemarkPlugin() {
  return (tree) => {
    visit(tree, (node) => {
      // `node` can now be one of the nodes for directives.
    })
  }
}

Compatibility

Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.

This plugin works with unified version 9+ and remark version 14+.

Security

Use of remark-directive does not involve rehype (hast) or user content so there are no openings for cross-site scripting (XSS) attacks.

Related

  • remark-gfm β€” support GFM (autolink literals, footnotes, strikethrough, tables, tasklists)
  • remark-frontmatter β€” support frontmatter (YAML, TOML, and more)
  • remark-math β€” support math
  • remark-mdx β€” support MDX (JSX, expressions, ESM)

Contribute

See contributing.md in remarkjs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT Β© Titus Wormer

More Repositories

1

react-markdown

Markdown component for React
JavaScript
12,885
star
2

remark

markdown processor powered by plugins part of the @unifiedjs collective
JavaScript
7,513
star
3

remark-lint

plugins to check (lint) markdown code style
JavaScript
936
star
4

remark-gfm

remark plugin to support GFM (autolink literals, footnotes, strikethrough, tables, tasklists)
JavaScript
701
star
5

remark-react

Legacy plugin to transform to React β€” please use `remark-rehype` and `rehype-react` instead
JavaScript
524
star
6

remark-toc

plugin to generate a table of contents (TOC)
JavaScript
408
star
7

awesome-remark

Curated list of awesome remark resources
374
star
8

remark-math

remark and rehype plugins to support math
JavaScript
364
star
9

remark-html

plugin to add support for serializing HTML
JavaScript
312
star
10

remark-rehype

plugin that turns markdown into HTML to support rehype
JavaScript
258
star
11

remark-frontmatter

remark plugin to support frontmatter (YAML, TOML, and more)
JavaScript
253
star
12

react-remark

React component and hook to use remark to render markdown
TypeScript
201
star
13

remark-github

remark plugin to link references to commits, issues, pull-requests, and users, like on GitHub
JavaScript
173
star
14

strip-markdown

plugin remove Markdown formatting
JavaScript
134
star
15

remark-breaks

plugin to add break support, without needing spaces
JavaScript
116
star
16

remark-validate-links

plugin to check that Markdown links and images reference existing files and headings
JavaScript
109
star
17

remark-man

plugin to compile markdown to man pages
JavaScript
93
star
18

remark-slug

Legacy plugin to add `id`s to headings β€” please use `rehype-slug`
JavaScript
89
star
19

remark-lint-no-dead-urls

Ensure that external links in your Markdown are alive
JavaScript
77
star
20

remark-unwrap-images

plugin to remove the wrapping paragraph for images
JavaScript
75
star
21

remark-highlight.js

Legacy plugin to highlight code blocks with highlight.js β€” please use `rehype-highlight` instead
JavaScript
70
star
22

remark-autolink-headings

Legacy remark plugin to automatically add links to headings β€” please use `rehype-autolink-headings` instead
JavaScript
64
star
23

remark-external-links

Legacy plugin to automatically add target and rel attributes to external links β€” please use `rehype-external-links` instead
JavaScript
56
star
24

vscode-remark

Lint and format markdown code with remark
JavaScript
54
star
25

remark-vdom

Legacy plugin to compile Markdown to Virtual DOM β€” please use `remark-rehype` and then something like `rehype-react`
JavaScript
45
star
26

remark-usage

plugin to add a usage example to your readme
JavaScript
42
star
27

remark-gemoji

plugin to turn gemoji shortcodes into emoji πŸ‘
JavaScript
41
star
28

remark-footnotes

Legacy plugin to add support for pandoc footnotes β€” please use `remark-gfm` instead
JavaScript
40
star
29

remark-images

plugin to add a simpler image syntax
JavaScript
35
star
30

remark-textr

plugin to make your typography better with Textr
JavaScript
35
star
31

remark-language-server

A language server to lint and format markdown files with remark
JavaScript
33
star
32

remark-embed-images

plugin to embed local images as data URIs
HTML
33
star
33

remark-jsx

A simple way to use React inside Markdown.
JavaScript
28
star
34

remark-reference-links

plugin to change links and images to references with separate definitions
JavaScript
25
star
35

remark-retext

plugin to transform from remark (Markdown) to retext (natural language)
JavaScript
25
star
36

remark-inline-links

plugin to change references and definitions into normal links and images
JavaScript
23
star
37

remark-contributors

plugin to generate a list of contributors
JavaScript
22
star
38

remark-license

plugin to generate a license section
JavaScript
19
star
39

remark-defsplit

plugin to change links and images to references with separate definitions
JavaScript
19
star
40

remark-bookmarks

plugin to manage links
JavaScript
15
star
41

remark-comment-config

plugin to configure remark with comments
JavaScript
14
star
42

remark-git-contributors

plugin to generate a list of Git contributors
JavaScript
12
star
43

remark-normalize-headings

plugin to make sure there is a single top level heading in a document by adjusting heading ranks accordingly
JavaScript
11
star
44

remark-squeeze-paragraphs

plugin to remove empty (or white-space only) paragraphs
JavaScript
10
star
45

remark-strip-badges

plugin to strip badges (such as shields.io)
JavaScript
9
star
46

gulp-remark

Legacy Gulp plugin for remark β€” please use npm scripts and the like
JavaScript
9
star
47

remark-yaml-config

plugin to configure remark with YAML frontmatter
JavaScript
8
star
48

remark-message-control

plugin to enable, disable, and ignore messages
JavaScript
8
star
49

.github

Community health files for remark
TypeScript
7
star
50

remark-unlink

plugin to remove all links, images, references, and definitions
JavaScript
6
star
51

remark-heading-gap

plugin to adjust the gap between headings in markdown
JavaScript
6
star
52

ideas

Share ideas for new utilities and tools built with @remarkjs
5
star
53

remark-word-wrap

Please use something like https://github.com/prettier/prettier instead
JavaScript
4
star
54

grunt-remark

Grunt task for remark
4
star
55

remark-midas

plugin to highlight CSS code blocks with midas
3
star
56

remark-comment-blocks

Use something like https://github.com/3rd-Eden/commenting instead
JavaScript
2
star
57

governance

How @remarkjs and the projects under it are governed
2
star