Markdown parser, done right. 100% CommonMark support, extensions, syntax plugins & high speed https://markdown-it.github.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.3 KiB

'use strict';
function escapeHtml(str) {
return str.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
var MD_UNESCAPE_RE = /\\([!"#$%&\'()*+,.\/:;<=>?@[\\\]^_`{|}~-])/g;
function unescapeMd(str) {
return str.replace(MD_UNESCAPE_RE, '$1');
}
var rules = {};
rules.blockquote_open = function (state /*, token*/) {
state.result += '<blockquote>';
};
rules.blockquote_close = function (state /*, token*/) {
state.result += '</blockquote>\n';
};
rules.bullet_list_open = function (state /*, token*/) {
state.result += '<ul>\n';
};
rules.bullet_list_close = function (state /*, token*/) {
state.result += '</ul>\n';
};
rules.code = function (state, token) {
state.result += '<pre><code>' + escapeHtml(token.content) + '</code></pre>\n';
};
rules.fence = function (state, token) {
var langMark = '';
var langPrefix = state.options.codeLangPrefix || '';
if (token.params.length) {
langMark = ' class="' + langPrefix + escapeHtml(token.params[0]) + '"';
}
state.result += '<pre><code' + langMark + '>' + escapeHtml(token.content) + '</code></pre>\n';
};
rules.heading_open = function (state, token) {
state.result += '<h' + token.level + '>';
};
rules.heading_close = function (state, token) {
state.result += '</h' + token.level + '>\n';
};
rules.hr = function (state/*, token*/) {
state.result += '<hr>\n';
};
rules.list_item_open = function (state /*, token*/) {
state.result += '<li>';
};
rules.list_item_close = function (state /*, token*/) {
state.result += '</li>\n';
};
rules.paragraph_open = function (state /*, token*/) {
state.result += '<p>';
};
rules.paragraph_close = function (state /*, token*/) {
state.result += '</p>\n';
};
rules.text = function (state, token) {
state.result += escapeHtml(unescapeMd(token.content));
};
// TODO: Stub. Do extendable.
function Renderer() {
}
Renderer.prototype.render = function (state) {
var i, len, rule,
tokens = state.tokens;
for (i = 0, len = tokens.length; i < len; i++) {
rule = rules[tokens[i].type];
// TODO: temporary check
if (!rule) {
throw new Error('Renderer error: unknown token ' + tokens[i].type);
}
rule(state, tokens[i]);
}
return state.result;
};
module.exports = Renderer;