aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: 9055377126bb95f779377546b71372505d3a0423 (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) {
  47. return offset + res.index;
  48. } else {
  49. return -1;
  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, line_number) {
  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, line_number);
  106. block = block.parent;
  107. }
  108. this.finalize(last_list, line_number);
  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, line_number, offset) {
  125. while (!canContain(this.tip.t, tag)) {
  126. this.finalize(this.tip, line_number - 1);
  127. }
  128. var column_number = offset + 1; // offset 0 = column 1
  129. var newBlock = new Node(tag, [[line_number, column_number], [0, 0]]);
  130. newBlock.strings = [];
  131. newBlock.string_content = undefined;
  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) {
  139. var rest = ln.slice(offset);
  140. var match;
  141. var spaces_after_marker;
  142. var data = { type: undefined,
  143. tight: true,
  144. bullet_char: undefined,
  145. start: undefined,
  146. delimiter: undefined,
  147. padding: undefined };
  148. if (rest.match(reHrule)) {
  149. return null;
  150. }
  151. if ((match = rest.match(reBulletListMarker))) {
  152. spaces_after_marker = match[1].length;
  153. data.type = 'Bullet';
  154. data.bullet_char = match[0][0];
  155. } else if ((match = rest.match(reOrderedListMarker))) {
  156. spaces_after_marker = match[3].length;
  157. data.type = 'Ordered';
  158. data.start = parseInt(match[1]);
  159. data.delimiter = match[2];
  160. } else {
  161. return null;
  162. }
  163. var blank_item = match[0].length === rest.length;
  164. if (spaces_after_marker >= 5 ||
  165. spaces_after_marker < 1 ||
  166. blank_item) {
  167. data.padding = match[0].length - spaces_after_marker + 1;
  168. } else {
  169. data.padding = match[0].length;
  170. }
  171. return data;
  172. };
  173. // Returns true if the two list items are of the same type,
  174. // with the same delimiter and bullet character. This is used
  175. // in agglomerating list items into lists.
  176. var listsMatch = function(list_data, item_data) {
  177. return (list_data.type === item_data.type &&
  178. list_data.delimiter === item_data.delimiter &&
  179. list_data.bullet_char === item_data.bullet_char);
  180. };
  181. // Finalize and close any unmatched blocks.
  182. var closeUnmatchedBlocks = function() {
  183. // finalize any blocks not matched
  184. while (this.oldtip !== this.last_matched_container) {
  185. this.finalize(this.oldtip, this.line_number - 1);
  186. this.oldtip = this.oldtip.parent;
  187. }
  188. };
  189. // Analyze a line of text and update the document appropriately.
  190. // We parse markdown text by calling this on each line of input,
  191. // then finalizing the document.
  192. var incorporateLine = function(ln, line_number) {
  193. var all_matched = true;
  194. var first_nonspace;
  195. var offset = 0;
  196. var match;
  197. var data;
  198. var blank;
  199. var indent;
  200. var i;
  201. var CODE_INDENT = 4;
  202. var container = this.doc;
  203. this.oldtip = this.tip;
  204. // replace NUL characters for security
  205. if (ln.indexOf('\u0000') !== -1) {
  206. ln = ln.replace(/\0/g, '\uFFFD');
  207. }
  208. // Convert tabs to spaces:
  209. ln = detabLine(ln);
  210. // For each containing block, try to parse the associated line start.
  211. // Bail out on failure: container will point to the last matching block.
  212. // Set all_matched to false if not all containers match.
  213. while (container.lastChild) {
  214. if (!container.lastChild.open) {
  215. break;
  216. }
  217. container = container.lastChild;
  218. match = matchAt(reNonSpace, ln, offset);
  219. if (match === -1) {
  220. first_nonspace = ln.length;
  221. blank = true;
  222. } else {
  223. first_nonspace = match;
  224. blank = false;
  225. }
  226. indent = first_nonspace - offset;
  227. switch (container.t) {
  228. case 'BlockQuote':
  229. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  230. offset = first_nonspace + 1;
  231. if (ln.charCodeAt(offset) === C_SPACE) {
  232. offset++;
  233. }
  234. } else {
  235. all_matched = false;
  236. }
  237. break;
  238. case 'Item':
  239. if (indent >= container.list_data.marker_offset +
  240. container.list_data.padding) {
  241. offset += container.list_data.marker_offset +
  242. container.list_data.padding;
  243. } else if (blank) {
  244. offset = first_nonspace;
  245. } else {
  246. all_matched = false;
  247. }
  248. break;
  249. case 'IndentedCode':
  250. if (indent >= CODE_INDENT) {
  251. offset += CODE_INDENT;
  252. } else if (blank) {
  253. offset = first_nonspace;
  254. } else {
  255. all_matched = false;
  256. }
  257. break;
  258. case 'Header':
  259. case 'HorizontalRule':
  260. // a header can never container > 1 line, so fail to match:
  261. all_matched = false;
  262. if (blank) {
  263. container.last_line_blank = true;
  264. }
  265. break;
  266. case 'FencedCode':
  267. // skip optional spaces of fence offset
  268. i = container.fence_offset;
  269. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  270. offset++;
  271. i--;
  272. }
  273. break;
  274. case 'HtmlBlock':
  275. if (blank) {
  276. container.last_line_blank = true;
  277. all_matched = false;
  278. }
  279. break;
  280. case 'Paragraph':
  281. if (blank) {
  282. container.last_line_blank = true;
  283. all_matched = false;
  284. }
  285. break;
  286. default:
  287. }
  288. if (!all_matched) {
  289. container = container.parent; // back up to last matching block
  290. break;
  291. }
  292. }
  293. this.last_matched_container = container;
  294. // Check to see if we've hit 2nd blank line; if so break out of list:
  295. if (blank && container.last_line_blank) {
  296. this.breakOutOfLists(container, line_number);
  297. }
  298. // Unless last matched container is a code block, try new container starts,
  299. // adding children to the last matched container:
  300. while (container.t !== 'FencedCode' &&
  301. container.t !== 'IndentedCode' &&
  302. container.t !== 'HtmlBlock' &&
  303. // this is a little performance optimization:
  304. matchAt(reMaybeSpecial, ln, offset) !== -1) {
  305. match = matchAt(reNonSpace, ln, offset);
  306. if (match === -1) {
  307. first_nonspace = ln.length;
  308. blank = true;
  309. } else {
  310. first_nonspace = match;
  311. blank = false;
  312. }
  313. indent = first_nonspace - offset;
  314. if (indent >= CODE_INDENT) {
  315. // indented code
  316. if (this.tip.t !== 'Paragraph' && !blank) {
  317. offset += CODE_INDENT;
  318. this.closeUnmatchedBlocks();
  319. container = this.addChild('IndentedCode', line_number, offset);
  320. } else { // indent > 4 in a lazy paragraph continuation
  321. break;
  322. }
  323. } else if (ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  324. // blockquote
  325. offset = first_nonspace + 1;
  326. // optional following space
  327. if (ln.charCodeAt(offset) === C_SPACE) {
  328. offset++;
  329. }
  330. this.closeUnmatchedBlocks();
  331. container = this.addChild('BlockQuote', line_number, offset);
  332. } else if ((match = ln.slice(first_nonspace).match(reATXHeaderMarker))) {
  333. // ATX header
  334. offset = first_nonspace + match[0].length;
  335. this.closeUnmatchedBlocks();
  336. container = this.addChild('Header', line_number, first_nonspace);
  337. container.level = match[0].trim().length; // number of #s
  338. // remove trailing ###s:
  339. container.strings =
  340. [ln.slice(offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/, '')];
  341. break;
  342. } else if ((match = ln.slice(first_nonspace).match(reCodeFence))) {
  343. // fenced code block
  344. var fence_length = match[0].length;
  345. this.closeUnmatchedBlocks();
  346. container = this.addChild('FencedCode', line_number, first_nonspace);
  347. container.fence_length = fence_length;
  348. container.fence_char = match[0][0];
  349. container.fence_offset = first_nonspace - offset;
  350. offset = first_nonspace + fence_length;
  351. break;
  352. } else if (matchAt(reHtmlBlockOpen, ln, first_nonspace) !== -1) {
  353. // html block
  354. this.closeUnmatchedBlocks();
  355. container = this.addChild('HtmlBlock', line_number, first_nonspace);
  356. // note, we don't adjust offset because the tag is part of the text
  357. break;
  358. } else if (container.t === 'Paragraph' &&
  359. container.strings.length === 1 &&
  360. ((match = ln.slice(first_nonspace).match(reSetextHeaderLine)))) {
  361. // setext header line
  362. this.closeUnmatchedBlocks();
  363. container.t = 'Header'; // convert Paragraph to SetextHeader
  364. container.level = match[0][0] === '=' ? 1 : 2;
  365. offset = ln.length;
  366. } else if (matchAt(reHrule, ln, first_nonspace) !== -1) {
  367. // hrule
  368. this.closeUnmatchedBlocks();
  369. container = this.addChild('HorizontalRule', line_number, first_nonspace);
  370. offset = ln.length - 1;
  371. break;
  372. } else if ((data = parseListMarker(ln, first_nonspace))) {
  373. // list item
  374. this.closeUnmatchedBlocks();
  375. data.marker_offset = indent;
  376. offset = first_nonspace + data.padding;
  377. // add the list if needed
  378. if (container.t !== 'List' ||
  379. !(listsMatch(container.list_data, data))) {
  380. container = this.addChild('List', line_number, first_nonspace);
  381. container.list_data = data;
  382. }
  383. // add the list item
  384. container = this.addChild('Item', line_number, first_nonspace);
  385. container.list_data = data;
  386. } else {
  387. break;
  388. }
  389. if (acceptsLines(container.t)) {
  390. // if it's a line container, it can't contain other containers
  391. break;
  392. }
  393. }
  394. // What remains at the offset is a text line. Add the text to the
  395. // appropriate container.
  396. match = matchAt(reNonSpace, ln, offset);
  397. if (match === -1) {
  398. first_nonspace = ln.length;
  399. blank = true;
  400. } else {
  401. first_nonspace = match;
  402. blank = false;
  403. }
  404. indent = first_nonspace - offset;
  405. // First check for a lazy paragraph continuation:
  406. if (this.tip !== this.last_matched_container &&
  407. !blank &&
  408. this.tip.t === 'Paragraph' &&
  409. this.tip.strings.length > 0) {
  410. // lazy paragraph continuation
  411. this.last_line_blank = false;
  412. this.addLine(ln, offset);
  413. } else { // not a lazy continuation
  414. // finalize any blocks not matched
  415. this.closeUnmatchedBlocks();
  416. // Block quote lines are never blank as they start with >
  417. // and we don't count blanks in fenced code for purposes of tight/loose
  418. // lists or breaking out of lists. We also don't set last_line_blank
  419. // on an empty list item.
  420. container.last_line_blank = blank &&
  421. !(container.t === 'BlockQuote' ||
  422. container.t === 'Header' ||
  423. container.t === 'FencedCode' ||
  424. (container.t === 'Item' &&
  425. !container.firstChild &&
  426. container.sourcepos[0][0] === line_number));
  427. var cont = container;
  428. while (cont.parent) {
  429. cont.parent.last_line_blank = false;
  430. cont = cont.parent;
  431. }
  432. switch (container.t) {
  433. case 'IndentedCode':
  434. case 'HtmlBlock':
  435. this.addLine(ln, offset);
  436. break;
  437. case 'FencedCode':
  438. // check for closing code fence:
  439. match = (indent <= 3 &&
  440. ln.charAt(first_nonspace) === container.fence_char &&
  441. ln.slice(first_nonspace).match(reClosingCodeFence));
  442. if (match && match[0].length >= container.fence_length) {
  443. // don't add closing fence to container; instead, close it:
  444. this.finalize(container, line_number);
  445. } else {
  446. this.addLine(ln, offset);
  447. }
  448. break;
  449. case 'Header':
  450. case 'HorizontalRule':
  451. // nothing to do; we already added the contents.
  452. break;
  453. default:
  454. if (acceptsLines(container.t)) {
  455. this.addLine(ln, first_nonspace);
  456. } else if (blank) {
  457. break;
  458. } else {
  459. // create paragraph container for line
  460. container = this.addChild('Paragraph', line_number, first_nonspace);
  461. this.addLine(ln, first_nonspace);
  462. }
  463. }
  464. }
  465. this.lastLineLength = ln.length - 1; // -1 for newline
  466. };
  467. // Finalize a block. Close it and do any necessary postprocessing,
  468. // e.g. creating string_content from strings, setting the 'tight'
  469. // or 'loose' status of a list, and parsing the beginnings
  470. // of paragraphs for reference definitions. Reset the tip to the
  471. // parent of the closed block.
  472. var finalize = function(block, line_number) {
  473. var pos;
  474. // don't do anything if the block is already closed
  475. if (!block.open) {
  476. return 0;
  477. }
  478. block.open = false;
  479. block.sourcepos[1] = [line_number, this.lastLineLength + 1];
  480. switch (block.t) {
  481. case 'Paragraph':
  482. block.string_content = block.strings.join('\n');
  483. // try parsing the beginning as link reference definitions:
  484. while (block.string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  485. (pos = this.inlineParser.parseReference(block.string_content,
  486. this.refmap))) {
  487. block.string_content = block.string_content.slice(pos);
  488. if (isBlank(block.string_content)) {
  489. block.t = 'ReferenceDef';
  490. break;
  491. }
  492. }
  493. break;
  494. case 'Header':
  495. block.string_content = block.strings.join('\n');
  496. break;
  497. case 'HtmlBlock':
  498. block.literal = block.strings.join('\n');
  499. break;
  500. case 'IndentedCode':
  501. stripFinalBlankLines(block.strings);
  502. block.literal = block.strings.join('\n') + '\n';
  503. block.t = 'CodeBlock';
  504. break;
  505. case 'FencedCode':
  506. // first line becomes info string
  507. block.info = unescapeString(block.strings[0].trim());
  508. if (block.strings.length === 1) {
  509. block.literal = '';
  510. } else {
  511. block.literal = block.strings.slice(1).join('\n') + '\n';
  512. }
  513. block.t = 'CodeBlock';
  514. break;
  515. case 'List':
  516. block.list_data.tight = true; // tight by default
  517. var item = block.firstChild;
  518. while (item) {
  519. // check for non-final list item ending with blank line:
  520. if (endsWithBlankLine(item) && item.next) {
  521. block.list_data.tight = false;
  522. break;
  523. }
  524. // recurse into children of list item, to see if there are
  525. // spaces between any of them:
  526. var subitem = item.firstChild;
  527. while (subitem) {
  528. if (endsWithBlankLine(subitem) && (item.next || subitem.next)) {
  529. block.list_data.tight = false;
  530. break;
  531. }
  532. subitem = subitem.next;
  533. }
  534. item = item.next;
  535. }
  536. break;
  537. default:
  538. break;
  539. }
  540. this.tip = block.parent || this.top;
  541. };
  542. // Walk through a block & children recursively, parsing string content
  543. // into inline content where appropriate. Returns new object.
  544. var processInlines = function(block) {
  545. var node, event;
  546. var walker = block.walker();
  547. while ((event = walker.next())) {
  548. node = event.node;
  549. if (!event.entering && (node.t === 'Paragraph' ||
  550. node.t === 'Header')) {
  551. this.inlineParser.parse(node, this.refmap);
  552. }
  553. }
  554. };
  555. var Document = function() {
  556. var doc = new Node('Document', [[1, 1], [0, 0]]);
  557. doc.string_content = undefined;
  558. doc.strings = [];
  559. return doc;
  560. };
  561. // The main parsing function. Returns a parsed document AST.
  562. var parse = function(input) {
  563. this.doc = new Document();
  564. this.tip = this.doc;
  565. this.refmap = {};
  566. if (this.options.time) { console.time("preparing input"); }
  567. var lines = input.split(reLineEnding);
  568. var len = lines.length;
  569. if (input.charCodeAt(input.length - 1) === C_NEWLINE) {
  570. // ignore last blank line created by final newline
  571. len -= 1;
  572. }
  573. if (this.options.time) { console.timeEnd("preparing input"); }
  574. if (this.options.time) { console.time("block parsing"); }
  575. for (var i = 0; i < len; i++) {
  576. this.incorporateLine(lines[i], i + 1);
  577. }
  578. while (this.tip) {
  579. this.finalize(this.tip, len);
  580. }
  581. if (this.options.time) { console.timeEnd("block parsing"); }
  582. if (this.options.time) { console.time("inline parsing"); }
  583. this.processInlines(this.doc);
  584. if (this.options.time) { console.timeEnd("inline parsing"); }
  585. return this.doc;
  586. };
  587. // The DocParser object.
  588. function DocParser(options){
  589. return {
  590. doc: new Document(),
  591. tip: this.doc,
  592. oldtip: this.doc,
  593. last_matched_container: this.doc,
  594. refmap: {},
  595. lastLineLength: 0,
  596. inlineParser: new InlineParser(),
  597. breakOutOfLists: breakOutOfLists,
  598. addLine: addLine,
  599. addChild: addChild,
  600. incorporateLine: incorporateLine,
  601. finalize: finalize,
  602. processInlines: processInlines,
  603. closeUnmatchedBlocks: closeUnmatchedBlocks,
  604. parse: parse,
  605. options: options || {}
  606. };
  607. }
  608. module.exports = DocParser;