turndown.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. var TurndownService = (function () {
  2. 'use strict';
  3. function extend (destination) {
  4. for (var i = 1; i < arguments.length; i++) {
  5. var source = arguments[i];
  6. for (var key in source) {
  7. if (source.hasOwnProperty(key)) destination[key] = source[key];
  8. }
  9. }
  10. return destination
  11. }
  12. function repeat (character, count) {
  13. return Array(count + 1).join(character)
  14. }
  15. var blockElements = [
  16. 'address', 'article', 'aside', 'audio', 'blockquote', 'body', 'canvas',
  17. 'center', 'dd', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption',
  18. 'figure', 'footer', 'form', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  19. 'header', 'hgroup', 'hr', 'html', 'isindex', 'li', 'main', 'menu', 'nav',
  20. 'noframes', 'noscript', 'ol', 'output', 'p', 'pre', 'section', 'table',
  21. 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul'
  22. ];
  23. function isBlock (node) {
  24. return blockElements.indexOf(node.nodeName.toLowerCase()) !== -1
  25. }
  26. var voidElements = [
  27. 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input',
  28. 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'
  29. ];
  30. function isVoid (node) {
  31. return voidElements.indexOf(node.nodeName.toLowerCase()) !== -1
  32. }
  33. var voidSelector = voidElements.join();
  34. function hasVoid (node) {
  35. return node.querySelector && node.querySelector(voidSelector)
  36. }
  37. var rules = {};
  38. rules.paragraph = {
  39. filter: 'p',
  40. replacement: function (content) {
  41. return '\n\n' + content + '\n\n'
  42. }
  43. };
  44. rules.lineBreak = {
  45. filter: 'br',
  46. replacement: function (content, node, options) {
  47. return options.br + '\n'
  48. }
  49. };
  50. rules.heading = {
  51. filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
  52. replacement: function (content, node, options) {
  53. var hLevel = Number(node.nodeName.charAt(1));
  54. if (options.headingStyle === 'setext' && hLevel < 3) {
  55. var underline = repeat((hLevel === 1 ? '=' : '-'), content.length);
  56. return (
  57. '\n\n' + content + '\n' + underline + '\n\n'
  58. )
  59. } else {
  60. return '\n\n' + repeat('#', hLevel) + ' ' + content + '\n\n'
  61. }
  62. }
  63. };
  64. rules.blockquote = {
  65. filter: 'blockquote',
  66. replacement: function (content) {
  67. content = content.replace(/^\n+|\n+$/g, '');
  68. content = content.replace(/^/gm, '> ');
  69. return '\n\n' + content + '\n\n'
  70. }
  71. };
  72. rules.list = {
  73. filter: ['ul', 'ol'],
  74. replacement: function (content, node) {
  75. var parent = node.parentNode;
  76. if (parent.nodeName === 'LI' && parent.lastElementChild === node) {
  77. return '\n' + content
  78. } else {
  79. return '\n\n' + content + '\n\n'
  80. }
  81. }
  82. };
  83. rules.listItem = {
  84. filter: 'li',
  85. replacement: function (content, node, options) {
  86. content = content
  87. .replace(/^\n+/, '') // remove leading newlines
  88. .replace(/\n+$/, '\n') // replace trailing newlines with just a single one
  89. .replace(/\n/gm, '\n '); // indent
  90. var prefix = options.bulletListMarker + ' ';
  91. var parent = node.parentNode;
  92. if (parent.nodeName === 'OL') {
  93. var start = parent.getAttribute('start');
  94. var index = Array.prototype.indexOf.call(parent.children, node);
  95. prefix = (start ? Number(start) + index : index + 1) + '. ';
  96. }
  97. return (
  98. prefix + content + (node.nextSibling && !/\n$/.test(content) ? '\n' : '')
  99. )
  100. }
  101. };
  102. rules.indentedCodeBlock = {
  103. filter: function (node, options) {
  104. return (
  105. options.codeBlockStyle === 'indented' &&
  106. node.nodeName === 'PRE' &&
  107. node.firstChild &&
  108. node.firstChild.nodeName === 'CODE'
  109. )
  110. },
  111. replacement: function (content, node, options) {
  112. return (
  113. '\n\n ' +
  114. node.firstChild.textContent.replace(/\n/g, '\n ') +
  115. '\n\n'
  116. )
  117. }
  118. };
  119. rules.fencedCodeBlock = {
  120. filter: function (node, options) {
  121. return (
  122. options.codeBlockStyle === 'fenced' &&
  123. node.nodeName === 'PRE' &&
  124. node.firstChild &&
  125. node.firstChild.nodeName === 'CODE'
  126. )
  127. },
  128. replacement: function (content, node, options) {
  129. var className = node.firstChild.className || '';
  130. var language = (className.match(/language-(\S+)/) || [null, ''])[1];
  131. return (
  132. '\n\n' + options.fence + language + '\n' +
  133. node.firstChild.textContent +
  134. '\n' + options.fence + '\n\n'
  135. )
  136. }
  137. };
  138. rules.horizontalRule = {
  139. filter: 'hr',
  140. replacement: function (content, node, options) {
  141. return '\n\n' + options.hr + '\n\n'
  142. }
  143. };
  144. rules.inlineLink = {
  145. filter: function (node, options) {
  146. return (
  147. options.linkStyle === 'inlined' &&
  148. node.nodeName === 'A' &&
  149. node.getAttribute('href')
  150. )
  151. },
  152. replacement: function (content, node) {
  153. var href = node.getAttribute('href');
  154. var title = node.title ? ' "' + node.title + '"' : '';
  155. return '[' + content + '](' + href + title + ')'
  156. }
  157. };
  158. rules.referenceLink = {
  159. filter: function (node, options) {
  160. return (
  161. options.linkStyle === 'referenced' &&
  162. node.nodeName === 'A' &&
  163. node.getAttribute('href')
  164. )
  165. },
  166. replacement: function (content, node, options) {
  167. var href = node.getAttribute('href');
  168. var title = node.title ? ' "' + node.title + '"' : '';
  169. var replacement;
  170. var reference;
  171. switch (options.linkReferenceStyle) {
  172. case 'collapsed':
  173. replacement = '[' + content + '][]';
  174. reference = '[' + content + ']: ' + href + title;
  175. break
  176. case 'shortcut':
  177. replacement = '[' + content + ']';
  178. reference = '[' + content + ']: ' + href + title;
  179. break
  180. default:
  181. var id = this.references.length + 1;
  182. replacement = '[' + content + '][' + id + ']';
  183. reference = '[' + id + ']: ' + href + title;
  184. }
  185. this.references.push(reference);
  186. return replacement
  187. },
  188. references: [],
  189. append: function (options) {
  190. var references = '';
  191. if (this.references.length) {
  192. references = '\n\n' + this.references.join('\n') + '\n\n';
  193. this.references = []; // Reset references
  194. }
  195. return references
  196. }
  197. };
  198. rules.emphasis = {
  199. filter: ['em', 'i'],
  200. replacement: function (content, node, options) {
  201. if (!content.trim()) return ''
  202. return options.emDelimiter + content + options.emDelimiter
  203. }
  204. };
  205. rules.strong = {
  206. filter: ['strong', 'b'],
  207. replacement: function (content, node, options) {
  208. if (!content.trim()) return ''
  209. return options.strongDelimiter + content + options.strongDelimiter
  210. }
  211. };
  212. rules.code = {
  213. filter: function (node) {
  214. var hasSiblings = node.previousSibling || node.nextSibling;
  215. var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;
  216. return node.nodeName === 'CODE' && !isCodeBlock
  217. },
  218. replacement: function (content) {
  219. if (!content.trim()) return ''
  220. var delimiter = '`';
  221. var leadingSpace = '';
  222. var trailingSpace = '';
  223. var matches = content.match(/`+/gm);
  224. if (matches) {
  225. if (/^`/.test(content)) leadingSpace = ' ';
  226. if (/`$/.test(content)) trailingSpace = ' ';
  227. while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';
  228. }
  229. return delimiter + leadingSpace + content + trailingSpace + delimiter
  230. }
  231. };
  232. rules.image = {
  233. filter: 'img',
  234. replacement: function (content, node) {
  235. var alt = node.alt || '';
  236. var src = node.getAttribute('src') || '';
  237. var title = node.title || '';
  238. var titlePart = title ? ' "' + title + '"' : '';
  239. return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : ''
  240. }
  241. };
  242. /**
  243. * Manages a collection of rules used to convert HTML to Markdown
  244. */
  245. function Rules (options) {
  246. this.options = options;
  247. this._keep = [];
  248. this._remove = [];
  249. this.blankRule = {
  250. replacement: options.blankReplacement
  251. };
  252. this.keepReplacement = options.keepReplacement;
  253. this.defaultRule = {
  254. replacement: options.defaultReplacement
  255. };
  256. this.array = [];
  257. for (var key in options.rules) this.array.push(options.rules[key]);
  258. }
  259. Rules.prototype = {
  260. add: function (key, rule) {
  261. this.array.unshift(rule);
  262. },
  263. keep: function (filter) {
  264. this._keep.unshift({
  265. filter: filter,
  266. replacement: this.keepReplacement
  267. });
  268. },
  269. remove: function (filter) {
  270. this._remove.unshift({
  271. filter: filter,
  272. replacement: function () {
  273. return ''
  274. }
  275. });
  276. },
  277. forNode: function (node) {
  278. if (node.isBlank) return this.blankRule
  279. var rule;
  280. if ((rule = findRule(this.array, node, this.options))) return rule
  281. if ((rule = findRule(this._keep, node, this.options))) return rule
  282. if ((rule = findRule(this._remove, node, this.options))) return rule
  283. return this.defaultRule
  284. },
  285. forEach: function (fn) {
  286. for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);
  287. }
  288. };
  289. function findRule (rules, node, options) {
  290. for (var i = 0; i < rules.length; i++) {
  291. var rule = rules[i];
  292. if (filterValue(rule, node, options)) return rule
  293. }
  294. return void 0
  295. }
  296. function filterValue (rule, node, options) {
  297. var filter = rule.filter;
  298. if (typeof filter === 'string') {
  299. if (filter === node.nodeName.toLowerCase()) return true
  300. } else if (Array.isArray(filter)) {
  301. if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true
  302. } else if (typeof filter === 'function') {
  303. if (filter.call(rule, node, options)) return true
  304. } else {
  305. throw new TypeError('`filter` needs to be a string, array, or function')
  306. }
  307. }
  308. /**
  309. * collapseWhitespace(options) removes extraneous whitespace from an the given element.
  310. *
  311. * @param {Object} options
  312. */
  313. function collapseWhitespace (options) {
  314. var element = options.element;
  315. var isBlock = options.isBlock;
  316. var isVoid = options.isVoid;
  317. var isPre = options.isPre || function (node) {
  318. return node.nodeName === 'PRE'
  319. };
  320. if (!element.firstChild || isPre(element)) return
  321. var prevText = null;
  322. var prevVoid = false;
  323. var prev = null;
  324. var node = next(prev, element, isPre);
  325. while (node !== element) {
  326. if (node.nodeType === 3 || node.nodeType === 4) { // Node.TEXT_NODE or Node.CDATA_SECTION_NODE
  327. var text = node.data.replace(/[ \r\n\t]+/g, ' ');
  328. if ((!prevText || / $/.test(prevText.data)) &&
  329. !prevVoid && text[0] === ' ') {
  330. text = text.substr(1);
  331. }
  332. // `text` might be empty at this point.
  333. if (!text) {
  334. node = remove(node);
  335. continue
  336. }
  337. node.data = text;
  338. prevText = node;
  339. } else if (node.nodeType === 1) { // Node.ELEMENT_NODE
  340. if (isBlock(node) || node.nodeName === 'BR') {
  341. if (prevText) {
  342. prevText.data = prevText.data.replace(/ $/, '');
  343. }
  344. prevText = null;
  345. prevVoid = false;
  346. } else if (isVoid(node)) {
  347. // Avoid trimming space around non-block, non-BR void elements.
  348. prevText = null;
  349. prevVoid = true;
  350. }
  351. } else {
  352. node = remove(node);
  353. continue
  354. }
  355. var nextNode = next(prev, node, isPre);
  356. prev = node;
  357. node = nextNode;
  358. }
  359. if (prevText) {
  360. prevText.data = prevText.data.replace(/ $/, '');
  361. if (!prevText.data) {
  362. remove(prevText);
  363. }
  364. }
  365. }
  366. /**
  367. * remove(node) removes the given node from the DOM and returns the
  368. * next node in the sequence.
  369. *
  370. * @param {Node} node
  371. * @return {Node} node
  372. */
  373. function remove (node) {
  374. var next = node.nextSibling || node.parentNode;
  375. node.parentNode.removeChild(node);
  376. return next
  377. }
  378. /**
  379. * next(prev, current, isPre) returns the next node in the sequence, given the
  380. * current and previous nodes.
  381. *
  382. * @param {Node} prev
  383. * @param {Node} current
  384. * @param {Function} isPre
  385. * @return {Node}
  386. */
  387. function next (prev, current, isPre) {
  388. if ((prev && prev.parentNode === current) || isPre(current)) {
  389. return current.nextSibling || current.parentNode
  390. }
  391. return current.firstChild || current.nextSibling || current.parentNode
  392. }
  393. /*
  394. * Set up window for Node.js
  395. */
  396. var root = (typeof window !== 'undefined' ? window : {});
  397. /*
  398. * Parsing HTML strings
  399. */
  400. function canParseHTMLNatively () {
  401. var Parser = root.DOMParser;
  402. var canParse = false;
  403. // Adapted from https://gist.github.com/1129031
  404. // Firefox/Opera/IE throw errors on unsupported types
  405. try {
  406. // WebKit returns null on unsupported types
  407. if (new Parser().parseFromString('', 'text/html')) {
  408. canParse = true;
  409. }
  410. } catch (e) {}
  411. return canParse
  412. }
  413. function createHTMLParser () {
  414. var Parser = function () {};
  415. {
  416. if (shouldUseActiveX()) {
  417. Parser.prototype.parseFromString = function (string) {
  418. var doc = new window.ActiveXObject('htmlfile');
  419. doc.designMode = 'on'; // disable on-page scripts
  420. doc.open();
  421. doc.write(string);
  422. doc.close();
  423. return doc
  424. };
  425. } else {
  426. Parser.prototype.parseFromString = function (string) {
  427. var doc = document.implementation.createHTMLDocument('');
  428. doc.open();
  429. doc.write(string);
  430. doc.close();
  431. return doc
  432. };
  433. }
  434. }
  435. return Parser
  436. }
  437. function shouldUseActiveX () {
  438. var useActiveX = false;
  439. try {
  440. document.implementation.createHTMLDocument('').open();
  441. } catch (e) {
  442. if (window.ActiveXObject) useActiveX = true;
  443. }
  444. return useActiveX
  445. }
  446. var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();
  447. function RootNode (input) {
  448. var root;
  449. if (typeof input === 'string') {
  450. var doc = htmlParser().parseFromString(
  451. // DOM parsers arrange elements in the <head> and <body>.
  452. // Wrapping in a custom element ensures elements are reliably arranged in
  453. // a single element.
  454. '<x-turndown id="turndown-root">' + input + '</x-turndown>',
  455. 'text/html'
  456. );
  457. root = doc.getElementById('turndown-root');
  458. } else {
  459. root = input.cloneNode(true);
  460. }
  461. collapseWhitespace({
  462. element: root,
  463. isBlock: isBlock,
  464. isVoid: isVoid
  465. });
  466. return root
  467. }
  468. var _htmlParser;
  469. function htmlParser () {
  470. _htmlParser = _htmlParser || new HTMLParser();
  471. return _htmlParser
  472. }
  473. function Node (node) {
  474. node.isBlock = isBlock(node);
  475. node.isCode = node.nodeName.toLowerCase() === 'code' || node.parentNode.isCode;
  476. node.isBlank = isBlank(node);
  477. node.flankingWhitespace = flankingWhitespace(node);
  478. return node
  479. }
  480. function isBlank (node) {
  481. return (
  482. ['A', 'TH', 'TD'].indexOf(node.nodeName) === -1 &&
  483. /^\s*$/i.test(node.textContent) &&
  484. !isVoid(node) &&
  485. !hasVoid(node)
  486. )
  487. }
  488. function flankingWhitespace (node) {
  489. var leading = '';
  490. var trailing = '';
  491. if (!node.isBlock) {
  492. var hasLeading = /^[ \r\n\t]/.test(node.textContent);
  493. var hasTrailing = /[ \r\n\t]$/.test(node.textContent);
  494. if (hasLeading && !isFlankedByWhitespace('left', node)) {
  495. leading = ' ';
  496. }
  497. if (hasTrailing && !isFlankedByWhitespace('right', node)) {
  498. trailing = ' ';
  499. }
  500. }
  501. return { leading: leading, trailing: trailing }
  502. }
  503. function isFlankedByWhitespace (side, node) {
  504. var sibling;
  505. var regExp;
  506. var isFlanked;
  507. if (side === 'left') {
  508. sibling = node.previousSibling;
  509. regExp = / $/;
  510. } else {
  511. sibling = node.nextSibling;
  512. regExp = /^ /;
  513. }
  514. if (sibling) {
  515. if (sibling.nodeType === 3) {
  516. isFlanked = regExp.test(sibling.nodeValue);
  517. } else if (sibling.nodeType === 1 && !isBlock(sibling)) {
  518. isFlanked = regExp.test(sibling.textContent);
  519. }
  520. }
  521. return isFlanked
  522. }
  523. var reduce = Array.prototype.reduce;
  524. var leadingNewLinesRegExp = /^\n*/;
  525. var trailingNewLinesRegExp = /\n*$/;
  526. function TurndownService (options) {
  527. if (!(this instanceof TurndownService)) return new TurndownService(options)
  528. var defaults = {
  529. rules: rules,
  530. headingStyle: 'setext',
  531. hr: '* * *',
  532. bulletListMarker: '*',
  533. codeBlockStyle: 'indented',
  534. fence: '```',
  535. emDelimiter: '_',
  536. strongDelimiter: '**',
  537. linkStyle: 'inlined',
  538. linkReferenceStyle: 'full',
  539. br: ' ',
  540. blankReplacement: function (content, node) {
  541. return node.isBlock ? '\n\n' : ''
  542. },
  543. keepReplacement: function (content, node) {
  544. return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML
  545. },
  546. defaultReplacement: function (content, node) {
  547. return node.isBlock ? '\n\n' + content + '\n\n' : content
  548. }
  549. };
  550. this.options = extend({}, defaults, options);
  551. this.rules = new Rules(this.options);
  552. }
  553. TurndownService.prototype = {
  554. /**
  555. * The entry point for converting a string or DOM node to Markdown
  556. * @public
  557. * @param {String|HTMLElement} input The string or DOM node to convert
  558. * @returns A Markdown representation of the input
  559. * @type String
  560. */
  561. turndown: function (input) {
  562. if (!canConvert(input)) {
  563. throw new TypeError(
  564. input + ' is not a string, or an element/document/fragment node.'
  565. )
  566. }
  567. if (input === '') return ''
  568. var output = process.call(this, new RootNode(input));
  569. return postProcess.call(this, output)
  570. },
  571. /**
  572. * Add one or more plugins
  573. * @public
  574. * @param {Function|Array} plugin The plugin or array of plugins to add
  575. * @returns The Turndown instance for chaining
  576. * @type Object
  577. */
  578. use: function (plugin) {
  579. if (Array.isArray(plugin)) {
  580. for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);
  581. } else if (typeof plugin === 'function') {
  582. plugin(this);
  583. } else {
  584. throw new TypeError('plugin must be a Function or an Array of Functions')
  585. }
  586. return this
  587. },
  588. /**
  589. * Adds a rule
  590. * @public
  591. * @param {String} key The unique key of the rule
  592. * @param {Object} rule The rule
  593. * @returns The Turndown instance for chaining
  594. * @type Object
  595. */
  596. addRule: function (key, rule) {
  597. this.rules.add(key, rule);
  598. return this
  599. },
  600. /**
  601. * Keep a node (as HTML) that matches the filter
  602. * @public
  603. * @param {String|Array|Function} filter The unique key of the rule
  604. * @returns The Turndown instance for chaining
  605. * @type Object
  606. */
  607. keep: function (filter) {
  608. this.rules.keep(filter);
  609. return this
  610. },
  611. /**
  612. * Remove a node that matches the filter
  613. * @public
  614. * @param {String|Array|Function} filter The unique key of the rule
  615. * @returns The Turndown instance for chaining
  616. * @type Object
  617. */
  618. remove: function (filter) {
  619. this.rules.remove(filter);
  620. return this
  621. },
  622. /**
  623. * Escapes Markdown syntax
  624. * @public
  625. * @param {String} string The string to escape
  626. * @returns A string with Markdown syntax escaped
  627. * @type String
  628. */
  629. escape: function (string) {
  630. return (
  631. string
  632. // Escape backslash escapes!
  633. .replace(/\\(\S)/g, '\\\\$1')
  634. // Escape headings
  635. .replace(/^(#{1,6} )/gm, '\\$1')
  636. // Escape hr
  637. .replace(/^([-*_] *){3,}$/gm, function (match, character) {
  638. return match.split(character).join('\\' + character)
  639. })
  640. // Escape ol bullet points
  641. .replace(/^(\W* {0,3})(\d+)\. /gm, '$1$2\\. ')
  642. // Escape ul bullet points
  643. .replace(/^([^\\\w]*)[*+-] /gm, function (match) {
  644. return match.replace(/([*+-])/g, '\\$1')
  645. })
  646. // Escape blockquote indents
  647. .replace(/^(\W* {0,3})> /gm, '$1\\> ')
  648. // Escape em/strong *
  649. .replace(/\*+(?![*\s\W]).+?\*+/g, function (match) {
  650. return match.replace(/\*/g, '\\*')
  651. })
  652. // Escape em/strong _
  653. .replace(/_+(?![_\s\W]).+?_+/g, function (match) {
  654. return match.replace(/_/g, '\\_')
  655. })
  656. // Escape code _
  657. .replace(/`+(?![`\s\W]).+?`+/g, function (match) {
  658. return match.replace(/`/g, '\\`')
  659. })
  660. // Escape link brackets
  661. .replace(/[\[\]]/g, '\\$&') // eslint-disable-line no-useless-escape
  662. )
  663. }
  664. };
  665. /**
  666. * Reduces a DOM node down to its Markdown string equivalent
  667. * @private
  668. * @param {HTMLElement} parentNode The node to convert
  669. * @returns A Markdown representation of the node
  670. * @type String
  671. */
  672. function process (parentNode) {
  673. var self = this;
  674. return reduce.call(parentNode.childNodes, function (output, node) {
  675. node = new Node(node);
  676. var replacement = '';
  677. if (node.nodeType === 3) {
  678. replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
  679. } else if (node.nodeType === 1) {
  680. replacement = replacementForNode.call(self, node);
  681. }
  682. return join(output, replacement)
  683. }, '')
  684. }
  685. /**
  686. * Appends strings as each rule requires and trims the output
  687. * @private
  688. * @param {String} output The conversion output
  689. * @returns A trimmed version of the ouput
  690. * @type String
  691. */
  692. function postProcess (output) {
  693. var self = this;
  694. this.rules.forEach(function (rule) {
  695. if (typeof rule.append === 'function') {
  696. output = join(output, rule.append(self.options));
  697. }
  698. });
  699. return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
  700. }
  701. /**
  702. * Converts an element node to its Markdown equivalent
  703. * @private
  704. * @param {HTMLElement} node The node to convert
  705. * @returns A Markdown representation of the node
  706. * @type String
  707. */
  708. function replacementForNode (node) {
  709. var rule = this.rules.forNode(node);
  710. var content = process.call(this, node);
  711. var whitespace = node.flankingWhitespace;
  712. if (whitespace.leading || whitespace.trailing) content = content.trim();
  713. return (
  714. whitespace.leading +
  715. rule.replacement(content, node, this.options) +
  716. whitespace.trailing
  717. )
  718. }
  719. /**
  720. * Determines the new lines between the current output and the replacement
  721. * @private
  722. * @param {String} output The current conversion output
  723. * @param {String} replacement The string to append to the output
  724. * @returns The whitespace to separate the current output and the replacement
  725. * @type String
  726. */
  727. function separatingNewlines (output, replacement) {
  728. var newlines = [
  729. output.match(trailingNewLinesRegExp)[0],
  730. replacement.match(leadingNewLinesRegExp)[0]
  731. ].sort();
  732. var maxNewlines = newlines[newlines.length - 1];
  733. return maxNewlines.length < 2 ? maxNewlines : '\n\n'
  734. }
  735. function join (string1, string2) {
  736. var separator = separatingNewlines(string1, string2);
  737. // Remove trailing/leading newlines and replace with separator
  738. string1 = string1.replace(trailingNewLinesRegExp, '');
  739. string2 = string2.replace(leadingNewLinesRegExp, '');
  740. return string1 + separator + string2
  741. }
  742. /**
  743. * Determines whether an input can be converted
  744. * @private
  745. * @param {String|HTMLElement} input Describe this parameter
  746. * @returns Describe what it returns
  747. * @type String|Object|Array|Boolean|Number
  748. */
  749. function canConvert (input) {
  750. return (
  751. input != null && (
  752. typeof input === 'string' ||
  753. (input.nodeType && (
  754. input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11
  755. ))
  756. )
  757. )
  758. }
  759. return TurndownService;
  760. }());