Fork me on GitHub

markdown-it

Install

node.js:

npm install markdown-it

browser (CDN):

Usage examples

See also:

Simple

// node.js
// can use `require('markdown-it')` for CJS
import markdownit from 'markdown-it'
const md = markdownit()
const result = md.render('# markdown-it rulezz!');

// browser with UMD build, added to "window" on script load
// Note, there is no dash in "markdownit".
const md = window.markdownit();
const result = md.render('# markdown-it rulezz!');

Single line rendering, without paragraph wrap:

import markdownit from 'markdown-it'
const md = markdownit()
const result = md.renderInline('__markdown-it__ rulezz!');

Init with presets and options

(*) presets define combinations of active rules and options. Can be "commonmark", "zero" or "default" (if skipped). See API docs for more details.

import markdownit from 'markdown-it'

// commonmark mode
const md = markdownit('commonmark')

// default mode
const md = markdownit()

// enable everything
const md = markdownit({
  html: true,
  linkify: true,
  typographer: true
})

// full options list (defaults)
const md = markdownit({
  // Enable HTML tags in source
  html:         false,

  // Use '/' to close single tags (<br />).
  // This is only for full CommonMark compatibility.
  xhtmlOut:     false,

  // Convert '\n' in paragraphs into <br>
  breaks:       false,

  // CSS language prefix for fenced blocks. Can be
  // useful for external highlighters.
  langPrefix:   'language-',

  // Autoconvert URL-like text to links
  linkify:      false,

  // Enable some language-neutral replacement + quotes beautification
  // For the full list of replacements, see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.mjs
  typographer:  false,

  // Double + single quotes replacement pairs, when typographer enabled,
  // and smartquotes on. Could be either a String or an Array.
  //
  // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
  // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
  quotes: '“”‘’',

  // Highlighter function. Should return escaped HTML,
  // or '' if the source string is not changed and should be escaped externally.
  // If result starts with <pre... internal wrapper is skipped.
  highlight: function (/*str, lang*/) { return ''; }
});

Plugins load

import markdownit from 'markdown-it'

const md = markdownit
  .use(plugin1)
  .use(plugin2, opts, ...)
  .use(plugin3);

Syntax highlighting

Apply syntax highlighting to fenced code blocks with the highlight option:

import markdownit from 'markdown-it'
import hljs from 'highlight.js' // https://highlightjs.org

// Actual default values
const md = markdownit({
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value;
      } catch (__) {}
    }

    return ''; // use external default escaping
  }
});

Or with full wrapper override (if you need assign class to <pre> or <code>):

import markdownit from 'markdown-it'
import hljs from 'highlight.js' // https://highlightjs.org

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

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

Linkify

linkify: true uses linkify-it. To configure linkify-it, access the linkify instance through md.linkify:

md.linkify.set({ fuzzyEmail: false });  // disables converting email to link

Syntax extensions

Embedded (enabled by default):

Via plugins:

Manage rules

By default all rules are enabled, but can be restricted by options. On plugin load all its rules are enabled automatically.

import markdownit from 'markdown-it'

// Activate/deactivate rules, with currying
const md = markdownit()
  .disable(['link', 'image'])
  .enable(['link'])
  .enable('image');

// Enable everything
const md = markdownit({
  html: true,
  linkify: true,
  typographer: true,
});

Core

internal

Description

Top-level rules executor. Glues block/inline parsers and does intermediate transformations.

Constructor

Class methods

Instance properties

Core.new

    • new Core()

Core.process

    • Core.process(state)

Executes core chain rules.

Core#ruler

Ruler instance. Keep configuration of core rules.

MarkdownIt

Description

Main parser/renderer class.

Usage
// node.js, "classic" way:
var MarkdownIt = require('markdown-it'),
    md = new MarkdownIt();
var result = md.render('# markdown-it rulezz!');

// node.js, the same, but with sugar:
var md = require('markdown-it')();
var result = md.render('# markdown-it rulezz!');

// browser without AMD, added to "window" on script load
// Note, there are no dash.
var md = window.markdownit();
var result = md.render('# markdown-it rulezz!');

Single line rendering, without paragraph wrap:

var md = require('markdown-it')();
var result = md.renderInline('__markdown-it__ rulezz!');

Constructor

MarkdownIt.new

    • new MarkdownIt([presetName][, options])
    • presetName
      • String
    • optional, commonmark / zero

    • options
      • Object

Creates parser instanse with given config. Can be called without new.

presetName

MarkdownIt provides named presets as a convenience to quickly enable/disable active syntax rules and options for common use cases.

  • "commonmark" - configures parser to strict CommonMark mode.
  • default - similar to GFM, used when no preset name given. Enables all available rules, but still without html, typographer & autolinker.
  • "zero" - all rules disabled. Useful to quickly setup your config via .enable(). For example, when you need only bold and italic markup and nothing else.
options:
  • html - false. Set true to enable HTML tags in source. Be careful! That's not safe! You may need external sanitizer to protect output from XSS. It's better to extend features via plugins, instead of enabling HTML.
  • xhtmlOut - false. Set true to add '/' when closing single tags (<br />). This is needed only for full CommonMark compatibility. In real world you will need HTML output.
  • breaks - false. Set true to convert \n in paragraphs into <br>.
  • langPrefix - language-. CSS language class prefix for fenced blocks. Can be useful for external highlighters.
  • linkify - false. Set true to autoconvert URL-like text to links.
  • typographer - false. Set true to enable some language-neutral replacement + quotes beautification (smartquotes).
  • quotes - “”‘’, String or Array. Double + single quotes replacement pairs, when typographer enabled and smartquotes on. For example, you can use '«»„“' for Russian, '„“‚‘' for German, and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
  • highlight - null. Highlighter function for fenced code blocks. Highlighter function (str, lang) should return escaped HTML. It can also return empty string if the source was not changed and should be escaped externaly. If result starts with <pre... internal wrapper is skipped.
Example
// commonmark mode
var md = require('markdown-it')('commonmark');

// default mode
var md = require('markdown-it')();

// enable everything
var md = require('markdown-it')({
  html: true,
  linkify: true,
  typographer: true
});
Syntax highlighting
var hljs = require('highlight.js') // https://highlightjs.org/

var md = require('markdown-it')({
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang, ignoreIllegals: true }).value;
      } catch (__) {}
    }

    return ''; // use external default escaping
  }
});

Or with full wrapper override (if you need assign class to <pre> or <code>):

var hljs = require('highlight.js') // https://highlightjs.org/

// Actual default values
var md = require('markdown-it')({
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre><code class="hljs">' +
               hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
               '</code></pre>';
      } catch (__) {}
    }

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

MarkdownIt.configure

chainableinternal
    • MarkdownIt.configure(presets)

Batch load of all options and compenent settings. This is internal method, and you probably will not need it. But if you will - see available presets and data structure here

We strongly recommend to use presets instead of direct config loads. That will give better compatibility with next versions.

MarkdownIt.disable

chainable
    • MarkdownIt.disable(list, ignoreInvalid)
    • list
      • String
      • Array
    • rule name or list of rule names to disable.

    • ignoreInvalid
      • Boolean
    • set true to ignore errors when rule not found.

The same as MarkdownIt.enable, but turn specified rules off.

MarkdownIt.enable

chainable
    • MarkdownIt.enable(list, ignoreInvalid)
    • list
      • String
      • Array
    • rule name or list of rule names to enable

    • ignoreInvalid
      • Boolean
    • set true to ignore errors when rule not found.

Enable list or rules. It will automatically find appropriate components, containing rules with given names. If rule not found, and ignoreInvalid not set - throws exception.

Example
var md = require('markdown-it')()
            .enable(['sub', 'sup'])
            .disable('smartquotes');

MarkdownIt.parse

internal
    • MarkdownIt.parse(src, env)
      • Array
    • src
      • String
    • source string

    • env
      • Object
    • environment sandbox

Parse input string and return list of block tokens (special token type "inline" will contain list of inline tokens). You should not call this method directly, until you write custom renderer (for example, to produce AST).

env is used to pass data between "distributed" rules and return additional metadata like reference info, needed for the renderer. It also can be used to inject data in specific cases. Usually, you will be ok to pass {}, and then pass updated object to renderer.

MarkdownIt.parseInline

internal
    • MarkdownIt.parseInline(src, env)
      • Array
    • src
      • String
    • source string

    • env
      • Object
    • environment sandbox

The same as MarkdownIt.parse but skip all block rules. It returns the block tokens list with the single inline element, containing parsed inline tokens in children property. Also updates env object.

MarkdownIt.render

    • MarkdownIt.render(src[, env])
      • String
    • src
      • String
    • source string

    • env
      • Object
    • environment sandbox

Render markdown string into html. It does all magic for you :).

env can be used to inject additional metadata ({} by default). But you will not need it with high probability. See also comment in MarkdownIt.parse.

MarkdownIt.renderInline

    • MarkdownIt.renderInline(src[, env])
      • String
    • src
      • String
    • source string

    • env
      • Object
    • environment sandbox

Similar to MarkdownIt.render but for single paragraph content. Result will NOT be wrapped into <p> tags.

MarkdownIt.set

chainable
    • MarkdownIt.set(options)

Set parser options (in the same format as in constructor). Probably, you will never need it, but you can change options after constructor call.

Example
var md = require('markdown-it')()
            .set({ html: true, breaks: true })
            .set({ typographer, true });

Note: To achieve the best possible performance, don't modify a markdown-it instance options on the fly. If you need multiple configurations it's best to create multiple instances and initialize each with separate config.

MarkdownIt.use

chainable
    • MarkdownIt.use(plugin, params)

Load specified plugin with given params into current parser instance. It's just a sugar to call plugin(md, params) with curring.

Example
var iterator = require('markdown-it-for-inline');
var md = require('markdown-it')()
            .use(iterator, 'foo_replace', 'text', function (tokens, idx) {
              tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
            });

MarkdownIt#normalizeLinkText

    • MarkdownIt#normalizeLinkText(url)
      • String

Function used to decode link url to a human-readable format`

MarkdownIt#block

Instance of ParserBlock. You may need it to add new rules when writing plugins. For simple rules control use MarkdownIt.disable and MarkdownIt.enable.

MarkdownIt#core

Instance of Core chain executor. You may need it to add new rules when writing plugins. For simple rules control use MarkdownIt.disable and MarkdownIt.enable.

MarkdownIt#helpers

    • MarkdownIt#helpers
      • helpers

Link components parser functions, useful to write plugins. See details here.

MarkdownIt#inline

Instance of ParserInline. You may need it to add new rules when writing plugins. For simple rules control use MarkdownIt.disable and MarkdownIt.enable.

MarkdownIt#linkify

    • MarkdownIt#linkify
      • LinkifyIt

linkify-it instance. Used by linkify rule.

MarkdownIt#renderer

Instance of Renderer. Use it to modify output look. Or to add rendering rules for new token types, generated by plugins.

Example
var md = require('markdown-it')();

function myToken(tokens, idx, options, env, self) {
  //...
  return result;
};

md.renderer.rules['my_token'] = myToken

See Renderer docs and source code.

MarkdownIt#utils

    • MarkdownIt#utils
      • utils

Assorted utility functions, useful to write plugins. See details here.

ParserBlock

internal

Description

Block-level tokenizer.

Constructor

Class methods

Instance properties

ParserBlock.new

    • new ParserBlock()

ParserBlock.parse

    • ParserBlock.parse(str, md, env, outTokens)

Process input string and push block tokens into outTokens

ParserBlock#ruler

Ruler instance. Keep configuration of block rules.

ParserInline

internal

Description

Tokenizes paragraph content.

Constructor

Class methods

Instance properties

ParserInline.new

    • new ParserInline()

ParserInline.parse

    • ParserInline.parse(str, md, env, outTokens)

Process input string and push inline tokens into outTokens

ParserInline#ruler

Ruler instance. Keep configuration of inline rules.

ParserInline#ruler2

Ruler instance. Second ruler used for post-processing (e.g. in emphasis-like rules).

Renderer

Description

Generates HTML from parsed token stream. Each instance has independent copy of rules. Those can be rewritten with ease. Also, you can add new rules if you create plugin and adds new token types.

Constructor

Instance properties

Renderer.new

    • new Renderer()

Creates new Renderer instance and fill Renderer#rules with defaults.

Renderer.render

    • Renderer.render(tokens, options, env)
      • String
    • tokens
      • Array
    • list on block tokens to render

    • options
      • Object
    • params of parser instance

    • env
      • Object
    • additional data from parsed input (references, for example)

Takes token stream and generates HTML. Probably, you will never need to call this method directly.

Renderer.renderAttrs

    • Renderer.renderAttrs(token)
      • String

Render token attributes to string.

Renderer.renderInline

    • Renderer.renderInline(tokens, options, env)
      • String
    • tokens
      • Array
    • list on block tokens to render

    • options
      • Object
    • params of parser instance

    • env
      • Object
    • additional data from parsed input (references, for example)

The same as Renderer.render, but for single token of inline type.

Renderer.renderInlineAsText

internal
    • Renderer.renderInlineAsText(tokens, options, env)
      • String
    • tokens
      • Array
    • list on block tokens to render

    • options
      • Object
    • params of parser instance

    • env
      • Object
    • additional data from parsed input (references, for example)

Special kludge for image alt attributes to conform CommonMark spec. Don't try to use it! Spec requires to show alt content with stripped markup, instead of simple escaping.

Renderer.renderToken

    • Renderer.renderToken(tokens, idx, options)
      • String
    • tokens
      • Array
    • list of tokens

    • idx
      • Numbed
    • token index to render

    • options
      • Object
    • params of parser instance

Default token renderer. Can be overriden by custom function in Renderer#rules.

Renderer#rules

    • Renderer#rules
      • Object

Contains render rules for tokens. Can be updated and extended.

Example
var md = require('markdown-it')();

md.renderer.rules.strong_open  = function () { return '<b>'; };
md.renderer.rules.strong_close = function () { return '</b>'; };

var result = md.renderInline(...);

Each rule is called as independent static function with fixed signature:

function my_token_render(tokens, idx, options, env, renderer) {
  // ...
  return renderedHTML;
}

See source code for more details and examples.

Ruler

Description

Helper class, used by MarkdownIt#core, MarkdownIt#block and MarkdownIt#inline to manage sequences of functions (rules):

  • keep rules in defined order
  • assign the name to each rule
  • enable/disable rules
  • add/replace rules
  • allow assign rules to additional named chains (in the same)
  • cacheing lists of active rules

You will not need use this class directly until write plugins. For simple rules control use MarkdownIt.disable, MarkdownIt.enable and MarkdownIt.use.

Constructor

Ruler.new

    • new Ruler()

Ruler.after

    • Ruler.after(afterName, ruleName, fn[, options])
    • afterName
      • String
    • new rule will be added after this one.

    • ruleName
      • String
    • name of added rule.

    • fn
      • Function
    • rule function.

    • options
      • Object
    • rule options (not mandatory).

Add new rule to chain after one with given name. See also Ruler.before, Ruler.push.

Options:
  • alt - array with names of "alternate" chains.
Example
var md = require('markdown-it')();

md.inline.ruler.after('text', 'my_rule', function replace(state) {
  //...
});

Ruler.at

    • Ruler.at(name, fn[, options])
    • name
      • String
    • rule name to replace.

    • fn
      • Function
    • new rule function.

    • options
      • Object
    • new rule options (not mandatory).

Replace rule by name with new function & options. Throws error if name not found.

Options:
  • alt - array with names of "alternate" chains.
Example

Replace existing typographer replacement rule with new one:

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

md.core.ruler.at('replacements', function replace(state) {
  //...
});

Ruler.before

    • Ruler.before(beforeName, ruleName, fn[, options])
    • beforeName
      • String
    • new rule will be added before this one.

    • ruleName
      • String
    • name of added rule.

    • fn
      • Function
    • rule function.

    • options
      • Object
    • rule options (not mandatory).

Add new rule to chain before one with given name. See also Ruler.after, Ruler.push.

Options:
  • alt - array with names of "alternate" chains.
Example
var md = require('markdown-it')();

md.block.ruler.before('paragraph', 'my_rule', function replace(state) {
  //...
});

Ruler.disable

    • Ruler.disable(list[, ignoreInvalid])
      • Array
    • list
      • String
      • Array
    • list of rule names to disable.

    • ignoreInvalid
      • Boolean
    • set true to ignore errors when rule not found.

Disable rules with given names. If any rule name not found - throw Error. Errors can be disabled by second param.

Returns list of found rule names (if no exception happened).

See also Ruler.enable, Ruler.enableOnly.

Ruler.enable

    • Ruler.enable(list[, ignoreInvalid])
      • Array
    • list
      • String
      • Array
    • list of rule names to enable.

    • ignoreInvalid
      • Boolean
    • set true to ignore errors when rule not found.

Enable rules with given names. If any rule name not found - throw Error. Errors can be disabled by second param.

Returns list of found rule names (if no exception happened).

See also Ruler.disable, Ruler.enableOnly.

Ruler.enableOnly

    • Ruler.enableOnly(list[, ignoreInvalid])
    • list
      • String
      • Array
    • list of rule names to enable (whitelist).

    • ignoreInvalid
      • Boolean
    • set true to ignore errors when rule not found.

Enable rules with given names, and disable everything else. If any rule name not found - throw Error. Errors can be disabled by second param.

See also Ruler.disable, Ruler.enable.

Ruler.getRules

    • Ruler.getRules(chainName)
      • Array

Return array of active functions (rules) for given chain name. It analyzes rules configuration, compiles caches if not exists and returns result.

Default chain name is '' (empty string). It can't be skipped. That's done intentionally, to keep signature monomorphic for high speed.

Ruler.push

    • Ruler.push(ruleName, fn[, options])
    • ruleName
      • String
    • name of added rule.

    • fn
      • Function
    • rule function.

    • options
      • Object
    • rule options (not mandatory).

Push new rule to the end of chain. See also Ruler.before, Ruler.after.

Options:
  • alt - array with names of "alternate" chains.
Example
var md = require('markdown-it')();

md.core.ruler.push('my_rule', function replace(state) {
  //...
});

Token

Constructor

Token.new

    • new Token(type, tag, nesting)

Create new token and fill passed properties.

Token.attrGet

    • Token.attrGet(name)

Get the value of attribute name, or null if it does not exist.

Token.attrIndex

    • Token.attrIndex(name)
      • Number

Search attribute index by name.

Token.attrJoin

    • Token.attrJoin(name, value)

Join value to existing attribute via space. Or create new attribute if not exists. Useful to operate with token classes.

Token.attrPush

    • Token.attrPush(attrData)

Add [ name, value ] attribute to list. Init attrs if necessary

Token.attrSet

    • Token.attrSet(name, value)

Set name attribute to value. Override old value if exists.

Token#attrs

    • Token#attrs
      • Array

Html attributes. Format: [ [ name1, value1 ], [ name2, value2 ] ]

Token#block

    • Token#block
      • Boolean

True for block-level tokens, false for inline tokens. Used in renderer to calculate line breaks

Token#children

    • Token#children
      • Array

An array of child nodes (inline and img tokens)

Token#content

    • Token#content
      • String

In a case of self-closing tag (code, html, fence, etc.), it has contents of this tag.

Token#hidden

    • Token#hidden
      • Boolean

If it's true, ignore this element when rendering. Used for tight lists to hide paragraphs.

Token#info

    • Token#info
      • String

Additional information:

  • Info string for "fence" tokens
  • The value "auto" for autolink "link_open" and "link_close" tokens
  • The string value of the item marker for ordered-list "list_item_open" tokens

Token#level

    • Token#level
      • Number

nesting level, the same as state.level

Token#map

    • Token#map
      • Array

Source map info. Format: [ line_begin, line_end ]

Token#markup

    • Token#markup
      • String

'*' or '_' for emphasis, fence string for fence, etc.

Token#meta

    • Token#meta
      • Object

A place for plugins to store an arbitrary data

Token#nesting

    • Token#nesting
      • Number

Level change (number in {-1, 0, 1} set), where:

  • 1 means the tag is opening
  • 0 means the tag is self-closing
  • -1 means the tag is closing

Token#tag

    • Token#tag
      • String

html tag name, e.g. "p"

Token#type

    • Token#type
      • String

Type of the token (string, e.g. "paragraph_open")