literate-md

1.0.1 • Public • Published

/*

Literate Markdown

A tiny little function to extract code from Fenced Code Blocks in Markdown documents.

Inspired by Literate Programming.

Fun fact: This README file is the actual source code for this module, and is parseable / executable javascript. Apologies for the weird comment artifacts, a few tricks with multiline comments were used.

Fun fact #2: This module is not javascript specific, although it is implemented in javascript. You can embed any language in your code blocks.

Implementation

This is the regular expression used to extract the contents of fenced code blocks:

/**/
var re = /^```[ \t]*\w+?\s*\n\s*([\w\W]+?)\s*(?:\n```)/gm;
/*

Here's the actual implementation of the extraction:

/**/
function extractFencedCodeBlocks(src) {
    if (typeof this.cacheable === 'function')
      this.cacheable(); // Allow for use as a webpack-loader
      
    const blocks = [];
    let match = null;
    while (match = re.exec(src)) {
      blocks.push(match[1]);
    }
    return blocks.join('\n\n');   
};
 
module.exports = extractFencedCodeBlocks;
 
/*

As mentioned above, it's quite tiny :)

*/

Readme

Keywords

none

Package Sidebar

Install

npm i literate-md

Weekly Downloads

1

Version

1.0.1

License

MIT

Last publish

Collaborators

  • rossipedia