aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: 590852af28b48bd1eee35b1fa27384431b961e0a (plain)
  1. "use strict";
  2. var Node = require('./node');
  3. var unescapeString = require('./common').unescapeString;
  4. var C_GREATERTHAN = 62;
  5. var C_NEWLINE = 10;
  6. var C_SPACE = 32;
  7. var C_OPEN_BRACKET = 91;
  8. var InlineParser = require('./inlines');
  9. var BLOCKTAGNAME = '(?:article|header|aside|hgroup|iframe|blockquote|hr|body|li|map|button|object|canvas|ol|caption|output|col|p|colgroup|pre|dd|progress|div|section|dl|table|td|dt|tbody|embed|textarea|fieldset|tfoot|figcaption|th|figure|thead|footer|footer|tr|form|ul|h1|h2|h3|h4|h5|h6|video|script|style)';
  10. var HTMLBLOCKOPEN = "<(?:" + BLOCKTAGNAME + "[\\s/>]" + "|" +
  11. "/" + BLOCKTAGNAME + "[\\s>]" + "|" + "[?!])";
  12. var reHtmlBlockOpen = new RegExp('^' + HTMLBLOCKOPEN, 'i');
  13. var reHrule = /^(?:(?:\* *){3,}|(?:_ *){3,}|(?:- *){3,}) *$/;
  14. var reMaybeSpecial = /^[ #`~*+_=<>0-9-]/;
  15. var reNonSpace = /[^ \t\n]/;
  16. var reBulletListMarker = /^[*+-]( +|$)/;
  17. var reOrderedListMarker = /^(\d+)([.)])( +|$)/;
  18. var reATXHeaderMarker = /^#{1,6}(?: +|$)/;
  19. var reCodeFence = /^`{3,}(?!.*`)|^~{3,}(?!.*~)/;
  20. var reClosingCodeFence = /^(?:`{3,}|~{3,})(?= *$)/;
  21. var reSetextHeaderLine = /^(?:=+|-+) *$/;
  22. var reLineEnding = /\r\n|\n|\r/;
  23. // Returns true if string contains only space characters.
  24. var isBlank = function(s) {
  25. return !(reNonSpace.test(s));
  26. };
  27. var tabSpaces = [' ', ' ', ' ', ' '];
  28. // Convert tabs to spaces on each line using a 4-space tab stop.
  29. var detabLine = function(text) {
  30. var start = 0;
  31. var offset;
  32. var lastStop = 0;
  33. while ((offset = text.indexOf('\t', start)) !== -1) {
  34. var numspaces = (offset - lastStop) % 4;
  35. var spaces = tabSpaces[numspaces];
  36. text = text.slice(0, offset) + spaces + text.slice(offset + 1);
  37. lastStop = offset + numspaces;
  38. start = lastStop;
  39. }
  40. return text;
  41. };
  42. // Attempt to match a regex in string s at offset offset.
  43. // Return index of match or -1.
  44. var matchAt = function(re, s, offset) {
  45. var res = s.slice(offset).match(re);
  46. if (res === null) {
  47. return -1;
  48. } else {
  49. return offset + res.index;
  50. }
  51. };
  52. // destructively trip final blank lines in an array of strings
  53. var stripFinalBlankLines = function(lns) {
  54. var i = lns.length - 1;
  55. while (!reNonSpace.test(lns[i])) {
  56. lns.pop();
  57. i--;
  58. }
  59. };
  60. // DOC PARSER
  61. // These are methods of a DocParser object, defined below.
  62. // Returns true if parent block can contain child block.
  63. var canContain = function(parent_type, child_type) {
  64. return ( parent_type === 'Document' ||
  65. parent_type === 'BlockQuote' ||
  66. parent_type === 'Item' ||
  67. (parent_type === 'List' && child_type === 'Item') );
  68. };
  69. // Returns true if block type can accept lines of text.
  70. var acceptsLines = function(block_type) {
  71. return ( block_type === 'Paragraph' ||
  72. block_type === 'IndentedCode' ||
  73. block_type === 'FencedCode' );
  74. };
  75. // Returns true if block ends with a blank line, descending if needed
  76. // into lists and sublists.
  77. var endsWithBlankLine = function(block) {
  78. while (block) {
  79. if (block.last_line_blank) {
  80. return true;
  81. }
  82. if (block.t === 'List' || block.t === 'Item') {
  83. block = block.lastChild;
  84. } else {
  85. break;
  86. }
  87. }
  88. return false;
  89. };
  90. // Break out of all containing lists, resetting the tip of the
  91. // document to the parent of the highest list, and finalizing
  92. // all the lists. (This is used to implement the "two blank lines
  93. // break of of all lists" feature.)
  94. var breakOutOfLists = function(block) {
  95. var b = block;
  96. var last_list = null;
  97. do {
  98. if (b.t === 'List') {
  99. last_list = b;
  100. }
  101. b = b.parent;
  102. } while (b);
  103. if (last_list) {
  104. while (block !== last_list) {
  105. this.finalize(block, this.lineNumber);
  106. block = block.parent;
  107. }
  108. this.finalize(last_list, this.lineNumber);
  109. this.tip = last_list.parent;
  110. }
  111. };
  112. // Add a line to the block at the tip. We assume the tip
  113. // can accept lines -- that check should be done before calling this.
  114. var addLine = function(ln, offset) {
  115. var s = ln.slice(offset);
  116. if (!(this.tip.open)) {
  117. throw { msg: "Attempted to add line (" + ln + ") to closed container." };
  118. }
  119. this.tip.strings.push(s);
  120. };
  121. // Add block of type tag as a child of the tip. If the tip can't
  122. // accept children, close and finalize it and try its parent,
  123. // and so on til we find a block that can accept children.
  124. var addChild = function(tag, offset) {
  125. while (!canContain(this.tip.t, tag)) {
  126. this.finalize(this.tip, this.lineNumber - 1);
  127. }
  128. var column_number = offset + 1; // offset 0 = column 1
  129. var newBlock = new Node(tag, [[this.lineNumber, column_number], [0, 0]]);
  130. newBlock.strings = [];
  131. newBlock.string_content = null;
  132. this.tip.appendChild(newBlock);
  133. this.tip = newBlock;
  134. return newBlock;
  135. };
  136. // Parse a list marker and return data on the marker (type,
  137. // start, delimiter, bullet character, padding) or null.
  138. var parseListMarker = function(ln, offset, indent) {
  139. var rest = ln.slice(offset);
  140. var match;
  141. var spaces_after_marker;
  142. var data = { type: null,
  143. tight: true,
  144. bullet_char: null,
  145. start: null,
  146. delimiter: null,
  147. padding: null,
  148. marker_offset: indent };
  149. if (rest.match(reHrule)) {
  150. return null;
  151. }
  152. if ((match = rest.match(reBulletListMarker))) {
  153. spaces_after_marker = match[1].length;
  154. data.type = 'Bullet';
  155. data.bullet_char = match[0][0];
  156. } else if ((match = rest.match(reOrderedListMarker))) {
  157. spaces_after_marker = match[3].length;
  158. data.type = 'Ordered';
  159. data.start = parseInt(match[1]);
  160. data.delimiter = match[2];
  161. } else {
  162. return null;
  163. }
  164. var blank_item = match[0].length === rest.length;
  165. if (spaces_after_marker >= 5 ||
  166. spaces_after_marker < 1 ||
  167. blank_item) {
  168. data.padding = match[0].length - spaces_after_marker + 1;
  169. } else {
  170. data.padding = match[0].length;
  171. }
  172. return data;
  173. };
  174. // Returns true if the two list items are of the same type,
  175. // with the same delimiter and bullet character. This is used
  176. // in agglomerating list items into lists.
  177. var listsMatch = function(list_data, item_data) {
  178. return (list_data.type === item_data.type &&
  179. list_data.delimiter === item_data.delimiter &&
  180. list_data.bullet_char === item_data.bullet_char);
  181. };
  182. // Finalize and close any unmatched blocks. Returns true.
  183. var closeUnmatchedBlocks = function() {
  184. // finalize any blocks not matched
  185. while (this.oldtip !== this.lastMatchedContainer) {
  186. this.finalize(this.oldtip, this.lineNumber - 1);
  187. this.oldtip = this.oldtip.parent;
  188. }
  189. return true;
  190. };
  191. // Analyze a line of text and update the document appropriately.
  192. // We parse markdown text by calling this on each line of input,
  193. // then finalizing the document.
  194. var incorporateLine = function(ln) {
  195. var all_matched = true;
  196. var first_nonspace;
  197. var offset = 0;
  198. var match;
  199. var data;
  200. var blank;
  201. var indent;
  202. var i;
  203. var CODE_INDENT = 4;
  204. var allClosed;
  205. var container = this.doc;
  206. this.oldtip = this.tip;
  207. // replace NUL characters for security
  208. if (ln.indexOf('\u0000') !== -1) {
  209. ln = ln.replace(/\0/g, '\uFFFD');
  210. }
  211. // Convert tabs to spaces:
  212. ln = detabLine(ln);
  213. // For each containing block, try to parse the associated line start.
  214. // Bail out on failure: container will point to the last matching block.
  215. // Set all_matched to false if not all containers match.
  216. while (container.lastChild) {
  217. if (!container.lastChild.open) {
  218. break;
  219. }
  220. container = container.lastChild;
  221. match = matchAt(reNonSpace, ln, offset);
  222. if (match === -1) {
  223. first_nonspace = ln.length;
  224. blank = true;
  225. } else {
  226. first_nonspace = match;
  227. blank = false;
  228. }
  229. indent = first_nonspace - offset;
  230. switch (container.t) {
  231. case 'BlockQuote':
  232. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  233. offset = first_nonspace + 1;
  234. if (ln.charCodeAt(offset) === C_SPACE) {
  235. offset++;
  236. }
  237. } else {
  238. all_matched = false;
  239. }
  240. break;
  241. case 'Item':
  242. if (indent >= container.list_data.marker_offset +
  243. container.list_data.padding) {
  244. offset += container.list_data.marker_offset +
  245. container.list_data.padding;
  246. } else if (blank) {
  247. offset = first_nonspace;
  248. } else {
  249. all_matched = false;
  250. }
  251. break;
  252. case 'IndentedCode':
  253. if (indent >= CODE_INDENT) {
  254. offset += CODE_INDENT;
  255. } else if (blank) {
  256. offset = first_nonspace;
  257. } else {
  258. all_matched = false;
  259. }
  260. break;
  261. case 'Header':
  262. case 'HorizontalRule':
  263. // a header can never container > 1 line, so fail to match:
  264. all_matched = false;
  265. if (blank) {
  266. container.last_line_blank = true;
  267. }
  268. break;
  269. case 'FencedCode':
  270. // skip optional spaces of fence offset
  271. i = container.fence_offset;
  272. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  273. offset++;
  274. i--;
  275. }
  276. break;
  277. case 'HtmlBlock':
  278. if (blank) {
  279. container.last_line_blank = true;
  280. all_matched = false;
  281. }
  282. break;
  283. case 'Paragraph':
  284. if (blank) {
  285. container.last_line_blank = true;
  286. all_matched = false;
  287. }
  288. break;
  289. default:
  290. }
  291. if (!all_matched) {
  292. container = container.parent; // back up to last matching block
  293. break;
  294. }
  295. }
  296. allClosed = (container === this.oldtip);
  297. this.lastMatchedContainer = container;
  298. // Check to see if we've hit 2nd blank line; if so break out of list:
  299. if (blank && container.last_line_blank) {
  300. this.breakOutOfLists(container);
  301. }
  302. // Unless last matched container is a code block, try new container starts,
  303. // adding children to the last matched container:
  304. while (container.t !== 'FencedCode' &&
  305. container.t !== 'IndentedCode' &&
  306. container.t !== 'HtmlBlock' &&
  307. // this is a little performance optimization:
  308. matchAt(reMaybeSpecial, ln, offset) !== -1) {
  309. match = matchAt(reNonSpace, ln, offset);
  310. if (match === -1) {
  311. first_nonspace = ln.length;
  312. blank = true;
  313. break;
  314. } else {
  315. first_nonspace = match;
  316. blank = false;
  317. }
  318. indent = first_nonspace - offset;
  319. if (indent >= CODE_INDENT) {
  320. // indented code
  321. if (this.tip.t !== 'Paragraph' && !blank) {
  322. offset += CODE_INDENT;
  323. allClosed = allClosed ||
  324. this.closeUnmatchedBlocks();
  325. container = this.addChild('IndentedCode', offset);
  326. }
  327. break;
  328. }
  329. offset = first_nonspace;
  330. var cc = ln.charCodeAt(offset);
  331. if (cc === C_GREATERTHAN) {
  332. // blockquote
  333. offset += 1;
  334. // optional following space
  335. if (ln.charCodeAt(offset) === C_SPACE) {
  336. offset++;
  337. }
  338. allClosed = allClosed || this.closeUnmatchedBlocks();
  339. container = this.addChild('BlockQuote', first_nonspace);
  340. } else if ((match = ln.slice(offset).match(reATXHeaderMarker))) {
  341. // ATX header
  342. offset += match[0].length;
  343. allClosed = allClosed || this.closeUnmatchedBlocks();
  344. container = this.addChild('Header', first_nonspace);
  345. container.level = match[0].trim().length; // number of #s
  346. // remove trailing ###s:
  347. container.strings =
  348. [ln.slice(offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/, '')];
  349. break;
  350. } else if ((match = ln.slice(offset).match(reCodeFence))) {
  351. // fenced code block
  352. var fence_length = match[0].length;
  353. allClosed = allClosed || this.closeUnmatchedBlocks();
  354. container = this.addChild('FencedCode', first_nonspace);
  355. container.fence_length = fence_length;
  356. container.fence_char = match[0][0];
  357. container.fence_offset = indent;
  358. offset += fence_length;
  359. break;
  360. } else if (matchAt(reHtmlBlockOpen, ln, offset) !== -1) {
  361. // html block
  362. allClosed = allClosed || this.closeUnmatchedBlocks();
  363. container = this.addChild('HtmlBlock', offset);
  364. offset -= indent; // back up so spaces are part of block
  365. break;
  366. } else if (container.t === 'Paragraph' &&
  367. container.strings.length === 1 &&
  368. ((match = ln.slice(offset).match(reSetextHeaderLine)))) {
  369. // setext header line
  370. allClosed = allClosed || this.closeUnmatchedBlocks();
  371. container.t = 'Header'; // convert Paragraph to SetextHeader
  372. container.level = match[0][0] === '=' ? 1 : 2;
  373. offset = ln.length;
  374. break;
  375. } else if (matchAt(reHrule, ln, offset) !== -1) {
  376. // hrule
  377. allClosed = allClosed || this.closeUnmatchedBlocks();
  378. container = this.addChild('HorizontalRule', first_nonspace);
  379. offset = ln.length - 1;
  380. break;
  381. } else if ((data = parseListMarker(ln, offset, indent))) {
  382. // list item
  383. allClosed = allClosed || this.closeUnmatchedBlocks();
  384. offset += data.padding;
  385. // add the list if needed
  386. if (container.t !== 'List' ||
  387. !(listsMatch(container.list_data, data))) {
  388. container = this.addChild('List', first_nonspace);
  389. container.list_data = data;
  390. }
  391. // add the list item
  392. container = this.addChild('Item', first_nonspace);
  393. container.list_data = data;
  394. } else {
  395. break;
  396. }
  397. }
  398. // What remains at the offset is a text line. Add the text to the
  399. // appropriate container.
  400. match = matchAt(reNonSpace, ln, offset);
  401. if (match === -1) {
  402. first_nonspace = ln.length;
  403. blank = true;
  404. } else {
  405. first_nonspace = match;
  406. blank = false;
  407. }
  408. indent = first_nonspace - offset;
  409. // First check for a lazy paragraph continuation:
  410. if (!allClosed && !blank &&
  411. this.tip.t === 'Paragraph' &&
  412. this.tip.strings.length > 0) {
  413. // lazy paragraph continuation
  414. this.last_line_blank = false;
  415. this.addLine(ln, offset);
  416. } else { // not a lazy continuation
  417. // finalize any blocks not matched
  418. allClosed = allClosed || this.closeUnmatchedBlocks();
  419. // Block quote lines are never blank as they start with >
  420. // and we don't count blanks in fenced code for purposes of tight/loose
  421. // lists or breaking out of lists. We also don't set last_line_blank
  422. // on an empty list item.
  423. container.last_line_blank = blank &&
  424. !(container.t === 'BlockQuote' ||
  425. container.t === 'Header' ||
  426. container.t === 'FencedCode' ||
  427. (container.t === 'Item' &&
  428. !container.firstChild &&
  429. container.sourcepos[0][0] === this.lineNumber));
  430. var cont = container;
  431. while (cont.parent) {
  432. cont.parent.last_line_blank = false;
  433. cont = cont.parent;
  434. }
  435. switch (container.t) {
  436. case 'IndentedCode':
  437. case 'HtmlBlock':
  438. this.addLine(ln, offset);
  439. break;
  440. case 'FencedCode':
  441. // check for closing code fence:
  442. match = (indent <= 3 &&
  443. ln.charAt(first_nonspace) === container.fence_char &&
  444. ln.slice(first_nonspace).match(reClosingCodeFence));
  445. if (match && match[0].length >= container.fence_length) {
  446. // don't add closing fence to container; instead, close it:
  447. this.finalize(container, this.lineNumber);
  448. } else {
  449. this.addLine(ln, offset);
  450. }
  451. break;
  452. case 'Header':
  453. case 'HorizontalRule':
  454. // nothing to do; we already added the contents.
  455. break;
  456. default:
  457. if (acceptsLines(container.t)) {
  458. this.addLine(ln, first_nonspace);
  459. } else if (blank) {
  460. break;
  461. } else {
  462. // create paragraph container for line
  463. container = this.addChild('Paragraph', this.lineNumber, first_nonspace);
  464. this.addLine(ln, first_nonspace);
  465. }
  466. }
  467. }
  468. this.lastLineLength = ln.length - 1; // -1 for newline
  469. };
  470. // Finalize a block. Close it and do any necessary postprocessing,
  471. // e.g. creating string_content from strings, setting the 'tight'
  472. // or 'loose' status of a list, and parsing the beginnings
  473. // of paragraphs for reference definitions. Reset the tip to the
  474. // parent of the closed block.
  475. var finalize = function(block, lineNumber) {
  476. var pos;
  477. // don't do anything if the block is already closed
  478. if (!block.open) {
  479. return 0;
  480. }
  481. block.open = false;
  482. block.sourcepos[1] = [lineNumber, this.lastLineLength + 1];
  483. switch (block.t) {
  484. case 'Paragraph':
  485. block.string_content = block.strings.join('\n');
  486. // try parsing the beginning as link reference definitions:
  487. while (block.string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  488. (pos = this.inlineParser.parseReference(block.string_content,
  489. this.refmap))) {
  490. block.string_content = block.string_content.slice(pos);
  491. if (isBlank(block.string_content)) {
  492. block.t = 'ReferenceDef';
  493. break;
  494. }
  495. }
  496. break;
  497. case 'Header':
  498. block.string_content = block.strings.join('\n');
  499. break;
  500. case 'HtmlBlock':
  501. block.literal = block.strings.join('\n');
  502. break;
  503. case 'IndentedCode':
  504. stripFinalBlankLines(block.strings);
  505. block.literal = block.strings.join('\n') + '\n';
  506. block.t = 'CodeBlock';
  507. break;
  508. case 'FencedCode':
  509. // first line becomes info string
  510. block.info = unescapeString(block.strings[0].trim());
  511. if (block.strings.length === 1) {
  512. block.literal = '';
  513. } else {
  514. block.literal = block.strings.slice(1).join('\n') + '\n';
  515. }
  516. block.t = 'CodeBlock';
  517. break;
  518. case 'List':
  519. block.list_data.tight = true; // tight by default
  520. var item = block.firstChild;
  521. while (item) {
  522. // check for non-final list item ending with blank line:
  523. if (endsWithBlankLine(item) && item.next) {
  524. block.list_data.tight = false;
  525. break;
  526. }
  527. // recurse into children of list item, to see if there are
  528. // spaces between any of them:
  529. var subitem = item.firstChild;
  530. while (subitem) {
  531. if (endsWithBlankLine(subitem) && (item.next || subitem.next)) {
  532. block.list_data.tight = false;
  533. break;
  534. }
  535. subitem = subitem.next;
  536. }
  537. item = item.next;
  538. }
  539. break;
  540. default:
  541. break;
  542. }
  543. this.tip = block.parent || this.top;
  544. };
  545. // Walk through a block & children recursively, parsing string content
  546. // into inline content where appropriate. Returns new object.
  547. var processInlines = function(block) {
  548. var node, event;
  549. var walker = block.walker();
  550. while ((event = walker.next())) {
  551. node = event.node;
  552. if (!event.entering && (node.t === 'Paragraph' ||
  553. node.t === 'Header')) {
  554. this.inlineParser.parse(node, this.refmap);
  555. }
  556. }
  557. };
  558. var Document = function() {
  559. var doc = new Node('Document', [[1, 1], [0, 0]]);
  560. doc.string_content = null;
  561. doc.strings = [];
  562. return doc;
  563. };
  564. // The main parsing function. Returns a parsed document AST.
  565. var parse = function(input) {
  566. this.doc = new Document();
  567. this.tip = this.doc;
  568. this.refmap = {};
  569. if (this.options.time) { console.time("preparing input"); }
  570. var lines = input.split(reLineEnding);
  571. var len = lines.length;
  572. if (input.charCodeAt(input.length - 1) === C_NEWLINE) {
  573. // ignore last blank line created by final newline
  574. len -= 1;
  575. }
  576. if (this.options.time) { console.timeEnd("preparing input"); }
  577. if (this.options.time) { console.time("block parsing"); }
  578. for (var i = 0; i < len; i++) {
  579. this.lineNumber += 1;
  580. this.incorporateLine(lines[i]);
  581. }
  582. while (this.tip) {
  583. this.finalize(this.tip, len);
  584. }
  585. if (this.options.time) { console.timeEnd("block parsing"); }
  586. if (this.options.time) { console.time("inline parsing"); }
  587. this.processInlines(this.doc);
  588. if (this.options.time) { console.timeEnd("inline parsing"); }
  589. return this.doc;
  590. };
  591. // The DocParser object.
  592. function DocParser(options){
  593. return {
  594. doc: new Document(),
  595. tip: this.doc,
  596. oldtip: this.doc,
  597. lineNumber: 0,
  598. lastMatchedContainer: this.doc,
  599. refmap: {},
  600. lastLineLength: 0,
  601. inlineParser: new InlineParser(),
  602. breakOutOfLists: breakOutOfLists,
  603. addLine: addLine,
  604. addChild: addChild,
  605. incorporateLine: incorporateLine,
  606. finalize: finalize,
  607. processInlines: processInlines,
  608. closeUnmatchedBlocks: closeUnmatchedBlocks,
  609. parse: parse,
  610. options: options || {}
  611. };
  612. }
  613. module.exports = DocParser;