markdown-it-named-code-blocks
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

markdown-it-named-code-blocks

A markdown-it plugin to create named code blocks.

CI NPM version Code Climate codecov License

🧐 About

With this plugin you can create named code blocks like:

```js:hello.js
console.log("Hello World!")
```

Rendered as:

<pre class="named-fence-block"><code class="language-js">console.log(&quot;Hello World!&quot;);
</code><div class="named-fence-filename">hello.js</div></pre>

After applying the css, it looks like this:

Rendered markdown

🏁 Getting Started

Prerequisites

Installing

npm install markdown-it-named-code-blocks

🎈 Usage

Use this same as a normal markdown-it plugin:

const md = require("markdown-it");
const hljs = require("highlight.js");
const namedCodeBlocks = require(".");

const parser = md({
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      return (
        '<pre class="hljs"><code>' +
        hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
        "</code></pre>"
      );
    }

    return (
      '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + "</code></pre>"
    );
  }
}).use(namedCodeBlocks);

const str = '```js:hello.js\nconsole.log("Hello World!");\n```';

const result = parser.render(str);

console.log(result);

Output:

<pre class="hljs named-fence-block"><code><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;Hello World!&quot;</span>);
</code><div class="named-fence-filename">hello.js</div></pre>

Apply CSS like this:

.named-fence-block {
  position: relative;
  padding-top: 2em;
}

.named-fence-filename {
  position: absolute;
  top: 0;
  left: 0;
  padding: 0 4px;
  font-weight: bold;
  color: #000000;
  background: #c0c0c0;
  opacity: 0.6;
}

Rendered:

Rendered markdown

If you want to enable inline CSS:

const parser = md().use(namedCodeBlocks, {isEnableInlineCss: true});

Output:

<pre class="hljs named-fence-block" style="position: relative; padding-top: 2em;"><code><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&quot;Hello World!&quot;</span>);
</code><div class="named-fence-filename" style="position: absolute; top: 0; left: 0; padding: 0 4px; font-weight: bold; color: #000000; background: #c0c0c0; opacity: .6;">hello.js</div></pre>

🎉 License

Distributed under the MIT License. See LICENSE for more information.

Package Sidebar

Install

npm i markdown-it-named-code-blocks

Weekly Downloads

520

Version

1.0.6

License

MIT

Unpacked Size

16.3 kB

Total Files

7

Last publish

Collaborators

  • tsutsu3