turndown.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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. var code = node.firstChild.textContent;
  132. var fenceChar = options.fence.charAt(0);
  133. var fenceSize = 3;
  134. var fenceInCodeRegex = new RegExp('^' + fenceChar + '{3,}', 'gm');
  135. var match;
  136. while ((match = fenceInCodeRegex.exec(code))) {
  137. if (match[0].length >= fenceSize) {
  138. fenceSize = match[0].length + 1;
  139. }
  140. }
  141. var fence = repeat(fenceChar, fenceSize);
  142. return (
  143. '\n\n' + fence + language + '\n' +
  144. code.replace(/\n$/, '') +
  145. '\n' + fence + '\n\n'
  146. )
  147. }
  148. };
  149. rules.horizontalRule = {
  150. filter: 'hr',
  151. replacement: function (content, node, options) {
  152. return '\n\n' + options.hr + '\n\n'
  153. }
  154. };
  155. rules.inlineLink = {
  156. filter: function (node, options) {
  157. return (
  158. options.linkStyle === 'inlined' &&
  159. node.nodeName === 'A' &&
  160. node.getAttribute('href')
  161. )
  162. },
  163. replacement: function (content, node) {
  164. var href = node.getAttribute('href');
  165. var title = node.title ? ' "' + node.title + '"' : '';
  166. return '[' + content + '](' + href + title + ')'
  167. }
  168. };
  169. rules.referenceLink = {
  170. filter: function (node, options) {
  171. return (
  172. options.linkStyle === 'referenced' &&
  173. node.nodeName === 'A' &&
  174. node.getAttribute('href')
  175. )
  176. },
  177. replacement: function (content, node, options) {
  178. var href = node.getAttribute('href');
  179. var title = node.title ? ' "' + node.title + '"' : '';
  180. var replacement;
  181. var reference;
  182. switch (options.linkReferenceStyle) {
  183. case 'collapsed':
  184. replacement = '[' + content + '][]';
  185. reference = '[' + content + ']: ' + href + title;
  186. break
  187. case 'shortcut':
  188. replacement = '[' + content + ']';
  189. reference = '[' + content + ']: ' + href + title;
  190. break
  191. default:
  192. var id = this.references.length + 1;
  193. replacement = '[' + content + '][' + id + ']';
  194. reference = '[' + id + ']: ' + href + title;
  195. }
  196. this.references.push(reference);
  197. return replacement
  198. },
  199. references: [],
  200. append: function (options) {
  201. var references = '';
  202. if (this.references.length) {
  203. references = '\n\n' + this.references.join('\n') + '\n\n';
  204. this.references = []; // Reset references
  205. }
  206. return references
  207. }
  208. };
  209. rules.emphasis = {
  210. filter: ['em', 'i'],
  211. replacement: function (content, node, options) {
  212. if (!content.trim()) return ''
  213. return options.emDelimiter + content + options.emDelimiter
  214. }
  215. };
  216. rules.strong = {
  217. filter: ['strong', 'b'],
  218. replacement: function (content, node, options) {
  219. if (!content.trim()) return ''
  220. return options.strongDelimiter + content + options.strongDelimiter
  221. }
  222. };
  223. rules.code = {
  224. filter: function (node) {
  225. var hasSiblings = node.previousSibling || node.nextSibling;
  226. var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;
  227. return node.nodeName === 'CODE' && !isCodeBlock
  228. },
  229. replacement: function (content) {
  230. if (!content.trim()) return ''
  231. var delimiter = '`';
  232. var leadingSpace = '';
  233. var trailingSpace = '';
  234. var matches = content.match(/`+/gm);
  235. if (matches) {
  236. if (/^`/.test(content)) leadingSpace = ' ';
  237. if (/`$/.test(content)) trailingSpace = ' ';
  238. while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';
  239. }
  240. return delimiter + leadingSpace + content + trailingSpace + delimiter
  241. }
  242. };
  243. rules.image = {
  244. filter: 'img',
  245. replacement: function (content, node) {
  246. var alt = node.alt || '';
  247. var src = node.getAttribute('src') || '';
  248. var title = node.title || '';
  249. var titlePart = title ? ' "' + title + '"' : '';
  250. return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : ''
  251. }
  252. };
  253. /**
  254. * Manages a collection of rules used to convert HTML to Markdown
  255. */
  256. function Rules (options) {
  257. this.options = options;
  258. this._keep = [];
  259. this._remove = [];
  260. this.blankRule = {
  261. replacement: options.blankReplacement
  262. };
  263. this.keepReplacement = options.keepReplacement;
  264. this.defaultRule = {
  265. replacement: options.defaultReplacement
  266. };
  267. this.array = [];
  268. for (var key in options.rules) this.array.push(options.rules[key]);
  269. }
  270. Rules.prototype = {
  271. add: function (key, rule) {
  272. this.array.unshift(rule);
  273. },
  274. keep: function (filter) {
  275. this._keep.unshift({
  276. filter: filter,
  277. replacement: this.keepReplacement
  278. });
  279. },
  280. remove: function (filter) {
  281. this._remove.unshift({
  282. filter: filter,
  283. replacement: function () {
  284. return ''
  285. }
  286. });
  287. },
  288. forNode: function (node) {
  289. if (node.isBlank) return this.blankRule
  290. var rule;
  291. if ((rule = findRule(this.array, node, this.options))) return rule
  292. if ((rule = findRule(this._keep, node, this.options))) return rule
  293. if ((rule = findRule(this._remove, node, this.options))) return rule
  294. return this.defaultRule
  295. },
  296. forEach: function (fn) {
  297. for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);
  298. }
  299. };
  300. function findRule (rules, node, options) {
  301. for (var i = 0; i < rules.length; i++) {
  302. var rule = rules[i];
  303. if (filterValue(rule, node, options)) return rule
  304. }
  305. return void 0
  306. }
  307. function filterValue (rule, node, options) {
  308. var filter = rule.filter;
  309. if (typeof filter === 'string') {
  310. if (filter === node.nodeName.toLowerCase()) return true
  311. } else if (Array.isArray(filter)) {
  312. if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true
  313. } else if (typeof filter === 'function') {
  314. if (filter.call(rule, node, options)) return true
  315. } else {
  316. throw new TypeError('`filter` needs to be a string, array, or function')
  317. }
  318. }
  319. /**
  320. * The collapseWhitespace function is adapted from collapse-whitespace
  321. * by Luc Thevenard.
  322. *
  323. * The MIT License (MIT)
  324. *
  325. * Copyright (c) 2014 Luc Thevenard <lucthevenard@gmail.com>
  326. *
  327. * Permission is hereby granted, free of charge, to any person obtaining a copy
  328. * of this software and associated documentation files (the "Software"), to deal
  329. * in the Software without restriction, including without limitation the rights
  330. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  331. * copies of the Software, and to permit persons to whom the Software is
  332. * furnished to do so, subject to the following conditions:
  333. *
  334. * The above copyright notice and this permission notice shall be included in
  335. * all copies or substantial portions of the Software.
  336. *
  337. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  338. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  339. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  340. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  341. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  342. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  343. * THE SOFTWARE.
  344. */
  345. /**
  346. * collapseWhitespace(options) removes extraneous whitespace from an the given element.
  347. *
  348. * @param {Object} options
  349. */
  350. function collapseWhitespace (options) {
  351. var element = options.element;
  352. var isBlock = options.isBlock;
  353. var isVoid = options.isVoid;
  354. var isPre = options.isPre || function (node) {
  355. return node.nodeName === 'PRE'
  356. };
  357. if (!element.firstChild || isPre(element)) return
  358. var prevText = null;
  359. var prevVoid = false;
  360. var prev = null;
  361. var node = next(prev, element, isPre);
  362. while (node !== element) {
  363. if (node.nodeType === 3 || node.nodeType === 4) { // Node.TEXT_NODE or Node.CDATA_SECTION_NODE
  364. var text = node.data.replace(/[ \r\n\t]+/g, ' ');
  365. if ((!prevText || / $/.test(prevText.data)) &&
  366. !prevVoid && text[0] === ' ') {
  367. text = text.substr(1);
  368. }
  369. // `text` might be empty at this point.
  370. if (!text) {
  371. node = remove(node);
  372. continue
  373. }
  374. node.data = text;
  375. prevText = node;
  376. } else if (node.nodeType === 1) { // Node.ELEMENT_NODE
  377. if (isBlock(node) || node.nodeName === 'BR') {
  378. if (prevText) {
  379. prevText.data = prevText.data.replace(/ $/, '');
  380. }
  381. prevText = null;
  382. prevVoid = false;
  383. } else if (isVoid(node)) {
  384. // Avoid trimming space around non-block, non-BR void elements.
  385. prevText = null;
  386. prevVoid = true;
  387. }
  388. } else {
  389. node = remove(node);
  390. continue
  391. }
  392. var nextNode = next(prev, node, isPre);
  393. prev = node;
  394. node = nextNode;
  395. }
  396. if (prevText) {
  397. prevText.data = prevText.data.replace(/ $/, '');
  398. if (!prevText.data) {
  399. remove(prevText);
  400. }
  401. }
  402. }
  403. /**
  404. * remove(node) removes the given node from the DOM and returns the
  405. * next node in the sequence.
  406. *
  407. * @param {Node} node
  408. * @return {Node} node
  409. */
  410. function remove (node) {
  411. var next = node.nextSibling || node.parentNode;
  412. node.parentNode.removeChild(node);
  413. return next
  414. }
  415. /**
  416. * next(prev, current, isPre) returns the next node in the sequence, given the
  417. * current and previous nodes.
  418. *
  419. * @param {Node} prev
  420. * @param {Node} current
  421. * @param {Function} isPre
  422. * @return {Node}
  423. */
  424. function next (prev, current, isPre) {
  425. if ((prev && prev.parentNode === current) || isPre(current)) {
  426. return current.nextSibling || current.parentNode
  427. }
  428. return current.firstChild || current.nextSibling || current.parentNode
  429. }
  430. /*
  431. * Set up window for Node.js
  432. */
  433. var root = (typeof window !== 'undefined' ? window : {});
  434. /*
  435. * Parsing HTML strings
  436. */
  437. function canParseHTMLNatively () {
  438. var Parser = root.DOMParser;
  439. var canParse = false;
  440. // Adapted from https://gist.github.com/1129031
  441. // Firefox/Opera/IE throw errors on unsupported types
  442. try {
  443. // WebKit returns null on unsupported types
  444. if (new Parser().parseFromString('', 'text/html')) {
  445. canParse = true;
  446. }
  447. } catch (e) {}
  448. return canParse
  449. }
  450. function createHTMLParser () {
  451. var Parser = function () {};
  452. {
  453. if (shouldUseActiveX()) {
  454. Parser.prototype.parseFromString = function (string) {
  455. var doc = new window.ActiveXObject('htmlfile');
  456. doc.designMode = 'on'; // disable on-page scripts
  457. doc.open();
  458. doc.write(string);
  459. doc.close();
  460. return doc
  461. };
  462. } else {
  463. Parser.prototype.parseFromString = function (string) {
  464. var doc = document.implementation.createHTMLDocument('');
  465. doc.open();
  466. doc.write(string);
  467. doc.close();
  468. return doc
  469. };
  470. }
  471. }
  472. return Parser
  473. }
  474. function shouldUseActiveX () {
  475. var useActiveX = false;
  476. try {
  477. document.implementation.createHTMLDocument('').open();
  478. } catch (e) {
  479. if (window.ActiveXObject) useActiveX = true;
  480. }
  481. return useActiveX
  482. }
  483. var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();
  484. function RootNode (input) {
  485. var root;
  486. if (typeof input === 'string') {
  487. var doc = htmlParser().parseFromString(
  488. // DOM parsers arrange elements in the <head> and <body>.
  489. // Wrapping in a custom element ensures elements are reliably arranged in
  490. // a single element.
  491. '<x-turndown id="turndown-root">' + input + '</x-turndown>',
  492. 'text/html'
  493. );
  494. root = doc.getElementById('turndown-root');
  495. } else {
  496. root = input.cloneNode(true);
  497. }
  498. collapseWhitespace({
  499. element: root,
  500. isBlock: isBlock,
  501. isVoid: isVoid
  502. });
  503. return root
  504. }
  505. var _htmlParser;
  506. function htmlParser () {
  507. _htmlParser = _htmlParser || new HTMLParser();
  508. return _htmlParser
  509. }
  510. function Node (node) {
  511. node.isBlock = isBlock(node);
  512. node.isCode = node.nodeName.toLowerCase() === 'code' || node.parentNode.isCode;
  513. node.isBlank = isBlank(node);
  514. node.flankingWhitespace = flankingWhitespace(node);
  515. return node
  516. }
  517. function isBlank (node) {
  518. return (
  519. ['A', 'TH', 'TD', 'IFRAME', 'SCRIPT', 'AUDIO', 'VIDEO'].indexOf(node.nodeName) === -1 &&
  520. /^\s*$/i.test(node.textContent) &&
  521. !isVoid(node) &&
  522. !hasVoid(node)
  523. )
  524. }
  525. function flankingWhitespace (node) {
  526. var leading = '';
  527. var trailing = '';
  528. if (!node.isBlock) {
  529. var hasLeading = /^\s/.test(node.textContent);
  530. var hasTrailing = /\s$/.test(node.textContent);
  531. var blankWithSpaces = node.isBlank && hasLeading && hasTrailing;
  532. if (hasLeading && !isFlankedByWhitespace('left', node)) {
  533. leading = ' ';
  534. }
  535. if (!blankWithSpaces && hasTrailing && !isFlankedByWhitespace('right', node)) {
  536. trailing = ' ';
  537. }
  538. }
  539. return { leading: leading, trailing: trailing }
  540. }
  541. function isFlankedByWhitespace (side, node) {
  542. var sibling;
  543. var regExp;
  544. var isFlanked;
  545. if (side === 'left') {
  546. sibling = node.previousSibling;
  547. regExp = / $/;
  548. } else {
  549. sibling = node.nextSibling;
  550. regExp = /^ /;
  551. }
  552. if (sibling) {
  553. if (sibling.nodeType === 3) {
  554. isFlanked = regExp.test(sibling.nodeValue);
  555. } else if (sibling.nodeType === 1 && !isBlock(sibling)) {
  556. isFlanked = regExp.test(sibling.textContent);
  557. }
  558. }
  559. return isFlanked
  560. }
  561. var reduce = Array.prototype.reduce;
  562. var leadingNewLinesRegExp = /^\n*/;
  563. var trailingNewLinesRegExp = /\n*$/;
  564. var escapes = [
  565. [/\\/g, '\\\\'],
  566. [/\*/g, '\\*'],
  567. [/^-/g, '\\-'],
  568. [/^\+ /g, '\\+ '],
  569. [/^(=+)/g, '\\$1'],
  570. [/^(#{1,6}) /g, '\\$1 '],
  571. [/`/g, '\\`'],
  572. [/^~~~/g, '\\~~~'],
  573. [/\[/g, '\\['],
  574. [/\]/g, '\\]'],
  575. [/^>/g, '\\>'],
  576. [/_/g, '\\_'],
  577. [/^(\d+)\. /g, '$1\\. ']
  578. ];
  579. function TurndownService (options) {
  580. if (!(this instanceof TurndownService)) return new TurndownService(options)
  581. var defaults = {
  582. rules: rules,
  583. headingStyle: 'setext',
  584. hr: '* * *',
  585. bulletListMarker: '*',
  586. codeBlockStyle: 'indented',
  587. fence: '```',
  588. emDelimiter: '_',
  589. strongDelimiter: '**',
  590. linkStyle: 'inlined',
  591. linkReferenceStyle: 'full',
  592. br: ' ',
  593. blankReplacement: function (content, node) {
  594. return node.isBlock ? '\n\n' : ''
  595. },
  596. keepReplacement: function (content, node) {
  597. return node.isBlock ? '\n\n' + node.outerHTML + '\n\n' : node.outerHTML
  598. },
  599. defaultReplacement: function (content, node) {
  600. return node.isBlock ? '\n\n' + content + '\n\n' : content
  601. }
  602. };
  603. this.options = extend({}, defaults, options);
  604. this.rules = new Rules(this.options);
  605. }
  606. TurndownService.prototype = {
  607. /**
  608. * The entry point for converting a string or DOM node to Markdown
  609. * @public
  610. * @param {String|HTMLElement} input The string or DOM node to convert
  611. * @returns A Markdown representation of the input
  612. * @type String
  613. */
  614. turndown: function (input) {
  615. if (!canConvert(input)) {
  616. throw new TypeError(
  617. input + ' is not a string, or an element/document/fragment node.'
  618. )
  619. }
  620. if (input === '') return ''
  621. var output = process.call(this, new RootNode(input));
  622. return postProcess.call(this, output)
  623. },
  624. /**
  625. * Add one or more plugins
  626. * @public
  627. * @param {Function|Array} plugin The plugin or array of plugins to add
  628. * @returns The Turndown instance for chaining
  629. * @type Object
  630. */
  631. use: function (plugin) {
  632. if (Array.isArray(plugin)) {
  633. for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);
  634. } else if (typeof plugin === 'function') {
  635. plugin(this);
  636. } else {
  637. throw new TypeError('plugin must be a Function or an Array of Functions')
  638. }
  639. return this
  640. },
  641. /**
  642. * Adds a rule
  643. * @public
  644. * @param {String} key The unique key of the rule
  645. * @param {Object} rule The rule
  646. * @returns The Turndown instance for chaining
  647. * @type Object
  648. */
  649. addRule: function (key, rule) {
  650. this.rules.add(key, rule);
  651. return this
  652. },
  653. /**
  654. * Keep a node (as HTML) that matches the filter
  655. * @public
  656. * @param {String|Array|Function} filter The unique key of the rule
  657. * @returns The Turndown instance for chaining
  658. * @type Object
  659. */
  660. keep: function (filter) {
  661. this.rules.keep(filter);
  662. return this
  663. },
  664. /**
  665. * Remove a node that matches the filter
  666. * @public
  667. * @param {String|Array|Function} filter The unique key of the rule
  668. * @returns The Turndown instance for chaining
  669. * @type Object
  670. */
  671. remove: function (filter) {
  672. this.rules.remove(filter);
  673. return this
  674. },
  675. /**
  676. * Escapes Markdown syntax
  677. * @public
  678. * @param {String} string The string to escape
  679. * @returns A string with Markdown syntax escaped
  680. * @type String
  681. */
  682. escape: function (string) {
  683. return escapes.reduce(function (accumulator, escape) {
  684. return accumulator.replace(escape[0], escape[1])
  685. }, string)
  686. }
  687. };
  688. /**
  689. * Reduces a DOM node down to its Markdown string equivalent
  690. * @private
  691. * @param {HTMLElement} parentNode The node to convert
  692. * @returns A Markdown representation of the node
  693. * @type String
  694. */
  695. function process (parentNode) {
  696. var self = this;
  697. return reduce.call(parentNode.childNodes, function (output, node) {
  698. node = new Node(node);
  699. var replacement = '';
  700. if (node.nodeType === 3) {
  701. replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
  702. } else if (node.nodeType === 1) {
  703. replacement = replacementForNode.call(self, node);
  704. }
  705. return join(output, replacement)
  706. }, '')
  707. }
  708. /**
  709. * Appends strings as each rule requires and trims the output
  710. * @private
  711. * @param {String} output The conversion output
  712. * @returns A trimmed version of the ouput
  713. * @type String
  714. */
  715. function postProcess (output) {
  716. var self = this;
  717. this.rules.forEach(function (rule) {
  718. if (typeof rule.append === 'function') {
  719. output = join(output, rule.append(self.options));
  720. }
  721. });
  722. return output.replace(/^[\t\r\n]+/, '').replace(/[\t\r\n\s]+$/, '')
  723. }
  724. /**
  725. * Converts an element node to its Markdown equivalent
  726. * @private
  727. * @param {HTMLElement} node The node to convert
  728. * @returns A Markdown representation of the node
  729. * @type String
  730. */
  731. function replacementForNode (node) {
  732. var rule = this.rules.forNode(node);
  733. var content = process.call(this, node);
  734. var whitespace = node.flankingWhitespace;
  735. if (whitespace.leading || whitespace.trailing) content = content.trim();
  736. return (
  737. whitespace.leading +
  738. rule.replacement(content, node, this.options) +
  739. whitespace.trailing
  740. )
  741. }
  742. /**
  743. * Determines the new lines between the current output and the replacement
  744. * @private
  745. * @param {String} output The current conversion output
  746. * @param {String} replacement The string to append to the output
  747. * @returns The whitespace to separate the current output and the replacement
  748. * @type String
  749. */
  750. function separatingNewlines (output, replacement) {
  751. var newlines = [
  752. output.match(trailingNewLinesRegExp)[0],
  753. replacement.match(leadingNewLinesRegExp)[0]
  754. ].sort();
  755. var maxNewlines = newlines[newlines.length - 1];
  756. return maxNewlines.length < 2 ? maxNewlines : '\n\n'
  757. }
  758. function join (string1, string2) {
  759. var separator = separatingNewlines(string1, string2);
  760. // Remove trailing/leading newlines and replace with separator
  761. string1 = string1.replace(trailingNewLinesRegExp, '');
  762. string2 = string2.replace(leadingNewLinesRegExp, '');
  763. return string1 + separator + string2
  764. }
  765. /**
  766. * Determines whether an input can be converted
  767. * @private
  768. * @param {String|HTMLElement} input Describe this parameter
  769. * @returns Describe what it returns
  770. * @type String|Object|Array|Boolean|Number
  771. */
  772. function canConvert (input) {
  773. return (
  774. input != null && (
  775. typeof input === 'string' ||
  776. (input.nodeType && (
  777. input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11
  778. ))
  779. )
  780. )
  781. }
  782. return TurndownService;
  783. }());