Need help with markdown-magic?
Click the “chat” button below for chat support from the developer who created it, or find similar developers for support.

About the developer

DavidWells
626 Stars 209 Forks 270 Commits 12 Opened issues

Description

💫  Automatically format markdown files using comment blocks. Update contents via custom transforms, external data sources & your source code.

Services available

!
?

Need anything else?

Contributors list

# 2,434
Amazon ...
gatsby
hugo
serverl...
173 commits
# 192,669
TypeScr...
styleli...
ESLint
Git
10 commits
# 837
html5
async-f...
assert
CSS
9 commits
# 49,718
reactjs
Markdow...
Shell
contrib...
1 commit
# 63,309
optimis...
phantom...
Chrome
Electro...
1 commit
# 4,039
microse...
executa...
mongo
GraphQL
1 commit
# 469,368
JavaScr...
docs-ge...
Markdow...
dx
1 commit
# 470,278
JavaScr...
docs-ge...
Markdow...
dx
1 commit
# 36,379
Apache ...
cloudwa...
kinesis
s3
1 commit
# 3,289
TypeScr...
serverl...
netlify
netlify...
1 commit

Markdown Magic npm-version

✨ Add a little magic to your markdown ✨

About

Markdown magic uses comment blocks in markdown files to automatically sync or transform its contents.

  • Automatically keep markdown files up to date from local or remote code sources
  • Transform markdown content with custom transform functions
  • Render markdown with any template engine
  • Automatically generate a table of contents
  • ... etc

The comments markdown magic uses are hidden in markdown and when viewed as HTML.

This

README.md
is generated with
markdown-magic
view the raw file to see how.

Video demoExample Repo

Table of Contents

Click to expand

Install

npm install markdown-magic --save-dev

Usage

import path from 'path'
import markdownMagic from 'markdown-magic'

const markdownPath = path.join(__dirname, 'README.md')
markdownMagic(markdownPath)

API

markdownMagic(filePath, config, callback)
  • filePaths
    - String or Array - Path or glob pattern. Uses globby patterns
  • config
    - See configuration options below
  • callback
    - callback to run after markdown updates <!-- ⛔️ MD-MAGIC-EXAMPLE:END - Do not remove or modify this section -->

Configuration Options

  • transforms
    - object - (optional) Custom commands to transform block contents, see transforms & custom transforms sections below.
  • outputDir
    - string - (optional) Change output path of new content. Default behavior is replacing the original file
  • matchWord
    - string - (optional) Comment pattern to look for & replace inner contents. Default
    AUTO-GENERATED-CONTENT
  • DEBUG
    - Boolean - (optional) set debug flag to
    true
    to inspect the process <!-- ⛔️ MD-MAGIC-EXAMPLE:END - Do not remove or modify this section -->

CLI Usage

You can use

markdown-magic
as a CLI command. Run
markdown --help
to see all available CLI options
markdown --help
# or
md-magic

This is useful for adding the package quickly to your

package.json
npm scripts

CLI usage example with options

md-magic --path '**/*.md' --config ./config.file.js

In NPM scripts,

npm run docs
would run the markdown magic and parse all the
.md
files in the directory.
"scripts": {
  "docs": "md-magic --path '**/*.md' --ignore 'node_modules'"
},

If you have a

markdown.config.js
file where
markdown-magic
is invoked, it will automatically use that as the configuration unless otherwise specified by
--config
flag.
/* CLI markdown.config.js file example */
module.exports = {
  matchWord: 'MD-MAGIC-EXAMPLE',
  transforms: {
    /* Match  */
    LOLZ(content, options) {
      return `This section was generated by the cli config markdown.config.js file`
    }
  },
  callback: function () {
    console.log('markdown processing done')
  }
}

Transforms

Markdown Magic comes with a couple of built in transforms for you to use or you can extend it with your own transforms. See 'Custom Transforms' below.

> TOC

Generate table of contents from markdown file

Options: -

firsth1
- boolean - (optional): Show first h1 of doc in table of contents. Default
false
-
collapse
- boolean - (optional): Collapse the table of contents in a detail accordian. Default
false
-
collapseText
- string - (optional): Text the toc accordian summary -
excludeText
- string - (optional): Text to exclude in the table of contents. Default
Table of Contents
-
maxDepth
- number - (optional): Max depth of headings. Default 4

Example:

md

toc will be generated here

Default

MATCHWORD
is
AUTO-GENERATED-CONTENT

> CODE

Get code from file or URL and put in markdown

Options: -

src
: The relative path to the code to pull in, or the
URL
where the raw code lives -
syntax
(optional): Syntax will be inferred by fileType if not specified -
header
(optional): Will add header comment to code snippet. Useful for pointing to relative source directory or adding live doc links -
lines
(optional): a range with lines of code which will then be replaced with code from the file. The line range should be defined as: "lines=startLine-EndLine" (for example: "lines=22-44"). Please see the example below

Example:

md

This content will be dynamically replaced with code from the file

 
 This content will be dynamically replaced with code from the file lines 22 through 44
 

Default

MATCHWORD
is
AUTO-GENERATED-CONTENT

> FILE

Get local file contents.

Options: -

src
: The relative path to the file to pull in

Example:

md

This content will be dynamically replaced from the local file

Default

MATCHWORD
is
AUTO-GENERATED-CONTENT

> REMOTE

Get any remote Data and put in markdown

Options: -

url
: The URL of the remote content to pull in

Example:

md

This content will be dynamically replaced from the remote url

Default

MATCHWORD
is
AUTO-GENERATED-CONTENT

Inline transforms

Any transform, including custom transforms can be used inline as well to insert content into paragraphs and other places.

The face symbol 👉 <!-- MD-MAGIC-EXAMPLE:START (INLINE_EXAMPLE) -->⊂◉‿◉つ<!-- MD-MAGIC-EXAMPLE:END --> is auto generated inline.

Example:

md
xyz

🔌 Markdown magic plugins

Adding Custom Transforms

Markdown Magic is extendable via plugins.

Plugins allow developers to add new transforms to the

config.transforms
object. This allows for things like using different rendering engines, custom formatting, or any other logic you might want.

Plugins run in order of registration.

The below code is used to generate this markdown file via the plugin system.

const fs = require('fs')
const path = require('path')
const markdownMagic = require('../index')
// const markdownMagic = require('markdown-magic')

const config = {
  matchWord: 'MD-MAGIC-EXAMPLE', // default matchWord is AUTO-GENERATED-CONTENT
  transforms: {
    /* Match  */
    customTransform(content, options) {
      console.log('original content in comment block', content)
      console.log('options defined on transform', options)
      // options = { optionOne: hi, optionOne: DUDE}
      return `This will replace all the contents of inside the comment ${options.optionOne}`
    },
    /* Match  */
    RENDERDOCS(content, options) {
      const fileContents = fs.readFileSync(options.path, 'utf8')
      const docBlocs = require('doxxx').parseComments(fileContents, { raw: true, skipSingleStar: true })
      let updatedContent = ''
      docBlocs.forEach((data) => {
        updatedContent += `${data.description.full}\n\n`
      })
      return updatedContent.replace(/^\s+|\s+$/g, '')
    },
    INLINE_EXAMPLE: () => {
      return '**⊂◉‿◉つ**'
    },
    /* Match  */
    pluginExample: require('./plugin-example')({ addNewLine: true }),
    /* Include plugins from NPM */
    // count: require('markdown-magic-wordcount'),
    // github: require('markdown-magic-github-contributors')
  }
}

const markdownPath = path.join(__dirname, '..', 'README.md')
markdownMagic(markdownPath, config, () => {
  console.log('Docs ready')
})

Plugin Example

Plugins must return a transform function with the following signature.

return function myCustomTransform (content, options)
/* Custom Transform Plugin example */
const merge = require('deepmerge')
module.exports = function customPlugin(pluginOptions) {
  // set plugin defaults
  const defaultOptions = {
    addNewLine: false
  }
  const userOptions = pluginOptions || {}
  const pluginConfig = merge(defaultOptions, userOptions)
  // return the transform function
  return function myCustomTransform (content, options) {
    const newLine = (pluginConfig.addNewLine) ? '\n' : ''
    const updatedContent = content + newLine
    return updatedContent
  }
}

View the raw file file and run

npm run docs
to see this plugin run <!-- ⛔️ MD-MAGIC-EXAMPLE:START (pluginExample) DO not edit ⛔️ --> This content is altered by the
pluginExample
plugin registered in
examples/generate-readme.js

Other usage examples

Custom Transform Demo

View the raw source of this

README.md
file to see the comment block and see how the
customTransform
function in
examples/generate-readme.js
works

This will replace all the contents of inside the comment DUDE <!-- ⛔️ MD-MAGIC-EXAMPLE:END - Do not remove or modify this section -->

Prior Art

This was inspired by Kent C Dodds and jfmengels's all contributors cli project.

This section was generated by the cli config markdown.config.js file <!-- MD-MAGIC-EXAMPLE:END (LOLZ)-->

License

MIT © DavidWells

Usage examples

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.