text = text.replace(/¨T/g, '¨');
// render a complete html document instead of a partial if the option is enabled
text = showdown.subParser('completeHTMLDocument')(text, options, globals);
showdown.helper.forEach(outputModifiers, function (ext) {
text = showdown.subParser('runExtension')(ext, text, options, globals);
metadata = globals.metadata;
* Converts an HTML string into a markdown string
* @param [HTMLParser] A WHATWG DOM and HTML parser, such as JSDOM. If none is supplied, window.document will be used.
this.makeMarkdown = this.makeMd = function (src, HTMLParser) {
src = src.replace(/\r\n/g, '\n');
src = src.replace(/\r/g, '\n'); // old macs
// due to an edge case, we need to find this: > <
// to prevent removing of non silent white spaces
// ex: <em>this is</em> <strong>sparta</strong>
src = src.replace(/>[ \t]+</, '>¨NBSP;<');
if (window && window.document) {
HTMLParser = window.document;
throw new Error('HTMLParser is undefined. If in a webworker or nodejs environment, you need to provide a WHATWG DOM and HTML such as JSDOM');
var doc = HTMLParser.createElement('div');
preList: substitutePreCodeTags(doc)
// remove all newlines and collapse spaces
// some stuff, like accidental reference links must now be escaped
// doc.innerHTML = doc.innerHTML.replace(/\[[\S\t ]]/);
var nodes = doc.childNodes,
for (var i = 0; i < nodes.length; i++) {
mdDoc += showdown.subParser('makeMarkdown.node')(nodes[i], globals);
for (var n = 0; n < node.childNodes.length; ++n) {
var child = node.childNodes[n];
if (child.nodeType === 3) {
if (!/\S/.test(child.nodeValue)) {
child.nodeValue = child.nodeValue.split('\n').join(' ');
child.nodeValue = child.nodeValue.replace(/(\s)+/g, '$1');
} else if (child.nodeType === 1) {
// find all pre tags and replace contents with placeholder
// we need this so that we can remove all indentation from html
function substitutePreCodeTags (doc) {
var pres = doc.querySelectorAll('pre'),
for (var i = 0; i < pres.length; ++i) {
if (pres[i].childElementCount === 1 && pres[i].firstChild.tagName.toLowerCase() === 'code') {
var content = pres[i].firstChild.innerHTML.trim(),
language = pres[i].firstChild.getAttribute('data-language') || '';
// if data-language attribute is not defined, then we look for class language-*
var classes = pres[i].firstChild.className.split(' ');
for (var c = 0; c < classes.length; ++c) {
var matches = classes[c].match(/^language-(.+)$/);
// unescape html entities in content
content = showdown.helper.unescapeHTMLEntities(content);
pres[i].outerHTML = '<precode language="' + language + '" precodenum="' + i.toString() + '"></precode>';
presPH.push(pres[i].innerHTML);
pres[i].setAttribute('prenum', i.toString());
* Set an option of this Converter instance
this.setOption = function (key, value) {
* Get the option of this Converter instance
this.getOption = function (key) {
* Get the options of this Converter instance
this.getOptions = function () {
* Add extension to THIS converter
* @param {string} [name=null]
this.addExtension = function (extension, name) {
_parseExtension(extension, name);
* Use a global registered extension with THIS converter
* @param {string} extensionName Name of the previously registered extension
this.useExtension = function (extensionName) {
_parseExtension(extensionName);
* Set the flavor THIS converter should use
this.setFlavor = function (name) {
if (!flavor.hasOwnProperty(name)) {
throw Error(name + ' flavor was not found');
var preset = flavor[name];
for (var option in preset) {
if (preset.hasOwnProperty(option)) {
options[option] = preset[option];
* Get the currently set flavor of this converter
this.getFlavor = function () {
* Remove an extension from THIS converter.
* Note: This is a costly operation. It's better to initialize a new converter
* and specify the extensions you wish to use
* @param {Array} extension
this.removeExtension = function (extension) {
if (!showdown.helper.isArray(extension)) {
for (var a = 0; a < extension.length; ++a) {
for (var i = 0; i < langExtensions.length; ++i) {
if (langExtensions[i] === ext) {
langExtensions[i].splice(i, 1);
for (var ii = 0; ii < outputModifiers.length; ++i) {
if (outputModifiers[ii] === ext) {
outputModifiers[ii].splice(i, 1);
* Get all extension of THIS converter
* @returns {{language: Array, output: Array}}
this.getAllExtensions = function () {
language: langExtensions,
* Get the metadata of the previously parsed document
this.getMetadata = function (raw) {
* Get the metadata format of the previously parsed document
this.getMetadataFormat = function () {
* Private: set a single key, value metadata pair
this._setMetadataPair = function (key, value) {
metadata.parsed[key] = value;
* Private: set metadata format
this._setMetadataFormat = function (format) {
metadata.format = format;
* Private: set metadata raw text
this._setMetadataRaw = function (raw) {
* Turn Markdown link shortcuts into XHTML <a> tags.
showdown.subParser('anchors', function (text, options, globals) {
text = globals.converter._dispatch('anchors.before', text, options, globals);
var writeAnchorTag = function (wholeMatch, linkText, linkId, url, m5, m6, title) {
if (showdown.helper.isUndefined(title)) {
linkId = linkId.toLowerCase();
// Special case for explicit empty url
if (wholeMatch.search(/\(<?\s*>? ?(['"].*['"])?\)$/m) > -1) {
// lower-case and turn embedded newlines into spaces
linkId = linkText.toLowerCase().replace(/ ?\n/g, ' ');
if (!showdown.helper.isUndefined(globals.gUrls[linkId])) {
url = globals.gUrls[linkId];
if (!showdown.helper.isUndefined(globals.gTitles[linkId])) {
title = globals.gTitles[linkId];
//url = showdown.helper.escapeCharacters(url, '*_', false); // replaced line to improve performance
url = url.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
var result = '<a href="' + url + '"';
if (title !== '' && title !== null) {
title = title.replace(/"/g, '"');
//title = showdown.helper.escapeCharacters(title, '*_', false); // replaced line to improve performance
title = title.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
result += ' title="' + title + '"';
// optionLinksInNewWindow only applies
// to external links. Hash links (#) open in same page
if (options.openLinksInNewWindow && !/^#/.test(url)) {
result += ' rel="noopener noreferrer" target="¨E95Eblank"';
result += '>' + linkText + '</a>';
// First, handle reference-style links: [link text] [id]
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)] ?(?:\n *)?\[(.*?)]()()()()/g, writeAnchorTag);
// Next, inline-style links: [link text](url "optional title")
// cases with crazy urls like ./image/cat1).png
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<([^>]*)>(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
text = text.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<?([\S]+?(?:\([\S]*?\)[\S]*?)?)>?(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,
// handle reference-style shortcuts: [link text]
// These must come last in case you've also got [link test][1]
text = text.replace(/\[([^\[\]]+)]()()()()()/g, writeAnchorTag);
// Lastly handle GithubMentions if option is enabled
if (options.ghMentions) {
text = text.replace(/(^|\s)(\\)?(@([a-z\d]+(?:[a-z\d.-]+?[a-z\d]+)*))/gmi, function (wm, st, escape, mentions, username) {
//check if options.ghMentionsLink is a string
if (!showdown.helper.isString(options.ghMentionsLink)) {
throw new Error('ghMentionsLink option must be a string');
var lnk = options.ghMentionsLink.replace(/\{u}/g, username),
if (options.openLinksInNewWindow) {
target = ' rel="noopener noreferrer" target="¨E95Eblank"';
return st + '<a href="' + lnk + '"' + target + '>' + mentions + '</a>';
text = globals.converter._dispatch('anchors.after', text, options, globals);
// url allowed chars [a-z\d_.~:/?#[]@!$&'()*+,;=-]
var simpleURLRegex = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+?\.[^'">\s]+?)()(\1)?(?=\s|$)(?!["<>])/gi,
simpleURLRegex2 = /([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?,()\[\]])?(\1)?(?=\s|$)(?!["<>])/gi,
delimUrlRegex = /()<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)()>()/gi,
simpleMailRegex = /(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gmi,
delimMailRegex = /<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,
replaceLink = function (options) {
return function (wm, leadingMagicChars, link, m2, m3, trailingPunctuation, trailingMagicChars) {
link = link.replace(showdown.helper.regexes.asteriskDashAndColon, showdown.helper.escapeCharactersCallback);
lmc = leadingMagicChars || '',
tmc = trailingMagicChars || '';
if (/^www\./i.test(link)) {
link = link.replace(/^www\./i, 'http://www.');
if (options.excludeTrailingPunctuationFromURLs && trailingPunctuation) {
append = trailingPunctuation;
if (options.openLinksInNewWindow) {
target = ' rel="noopener noreferrer" target="¨E95Eblank"';
return lmc + '<a href="' + link + '"' + target + '>' + lnkTxt + '</a>' + append + tmc;
replaceMail = function (options, globals) {
return function (wholeMatch, b, mail) {
mail = showdown.subParser('unescapeSpecialChars')(mail, options, globals);
if (options.encodeEmails) {
href = showdown.helper.encodeEmailAddress(href + mail);
mail = showdown.helper.encodeEmailAddress(mail);
return b + '<a href="' + href + '">' + mail + '</a>';
showdown.subParser('autoLinks', function (text, options, globals) {
text = globals.converter._dispatch('autoLinks.before', text, options, globals);
text = text.replace(delimUrlRegex, replaceLink(options));
text = text.replace(delimMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('autoLinks.after', text, options, globals);
showdown.subParser('simplifiedAutoLinks', function (text, options, globals) {
if (!options.simplifiedAutoLink) {
text = globals.converter._dispatch('simplifiedAutoLinks.before', text, options, globals);
if (options.excludeTrailingPunctuationFromURLs) {
text = text.replace(simpleURLRegex2, replaceLink(options));
text = text.replace(simpleURLRegex, replaceLink(options));
text = text.replace(simpleMailRegex, replaceMail(options, globals));
text = globals.converter._dispatch('simplifiedAutoLinks.after', text, options, globals);
* These are all the transformations that form block-level
* tags like paragraphs, headers, and list items.
showdown.subParser('blockGamut', function (text, options, globals) {
text = globals.converter._dispatch('blockGamut.before', text, options, globals);
// we parse blockquotes first so that we can have headings and hrs
text = showdown.subParser('blockQuotes')(text, options, globals);
text = showdown.subParser('headers')(text, options, globals);
text = showdown.subParser('horizontalRule')(text, options, globals);
text = showdown.subParser('lists')(text, options, globals);
text = showdown.subParser('codeBlocks')(text, options, globals);
text = showdown.subParser('tables')(text, options, globals);
// We already ran _HashHTMLBlocks() before, in Markdown(), but that
// was to escape raw HTML in the original Markdown source. This time,
// we're escaping the markup we've just created, so that we don't wrap
// <p> tags around block-level tags.
text = showdown.subParser('hashHTMLBlocks')(text, options, globals);
text = showdown.subParser('paragraphs')(text, options, globals);
text = globals.converter._dispatch('blockGamut.after', text, options, globals);
showdown.subParser('blockQuotes', function (text, options, globals) {
text = globals.converter._dispatch('blockQuotes.before', text, options, globals);
// add a couple extra lines after the text and endtext mark
var rgx = /(^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+/gm;
if (options.splitAdjacentBlockquotes) {
rgx = /^ {0,3}>[\s\S]*?(?:\n\n)/gm;
text = text.replace(rgx, function (bq) {