aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: 511acb42268a23e9f1e6e3ba7f573c1d66ff2faf (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 === 'CodeBlock' );
  73. };
  74. // Returns true if block ends with a blank line, descending if needed
  75. // into lists and sublists.
  76. var endsWithBlankLine = function(block) {
  77. while (block) {
  78. if (block.last_line_blank) {
  79. return true;
  80. }
  81. if (block.t === 'List' || block.t === 'Item') {
  82. block = block.lastChild;
  83. } else {
  84. break;
  85. }
  86. }
  87. return false;
  88. };
  89. // Break out of all containing lists, resetting the tip of the
  90. // document to the parent of the highest list, and finalizing
  91. // all the lists. (This is used to implement the "two blank lines
  92. // break of of all lists" feature.)
  93. var breakOutOfLists = function(block) {
  94. var b = block;
  95. var last_list = null;
  96. do {
  97. if (b.t === 'List') {
  98. last_list = b;
  99. }
  100. b = b.parent;
  101. } while (b);
  102. if (last_list) {
  103. while (block !== last_list) {
  104. this.finalize(block, this.lineNumber);
  105. block = block.parent;
  106. }
  107. this.finalize(last_list, this.lineNumber);
  108. this.tip = last_list.parent;
  109. }
  110. };
  111. // Add a line to the block at the tip. We assume the tip
  112. // can accept lines -- that check should be done before calling this.
  113. var addLine = function(ln, offset) {
  114. var s = ln.slice(offset);
  115. if (!(this.tip.open)) {
  116. throw { msg: "Attempted to add line (" + ln + ") to closed container." };
  117. }
  118. this.tip.strings.push(s);
  119. };
  120. // Add block of type tag as a child of the tip. If the tip can't
  121. // accept children, close and finalize it and try its parent,
  122. // and so on til we find a block that can accept children.
  123. var addChild = function(tag, offset) {
  124. while (!canContain(this.tip.t, tag)) {
  125. this.finalize(this.tip, this.lineNumber - 1);
  126. }
  127. var column_number = offset + 1; // offset 0 = column 1
  128. var newBlock = new Node(tag, [[this.lineNumber, column_number], [0, 0]]);
  129. newBlock.strings = [];
  130. newBlock.string_content = null;
  131. this.tip.appendChild(newBlock);
  132. this.tip = newBlock;
  133. return newBlock;
  134. };
  135. // Parse a list marker and return data on the marker (type,
  136. // start, delimiter, bullet character, padding) or null.
  137. var parseListMarker = function(ln, offset, indent) {
  138. var rest = ln.slice(offset);
  139. var match;
  140. var spaces_after_marker;
  141. var data = { type: null,
  142. tight: true,
  143. bullet_char: null,
  144. start: null,
  145. delimiter: null,
  146. padding: null,
  147. marker_offset: indent };
  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. Returns true.
  182. var closeUnmatchedBlocks = function() {
  183. // finalize any blocks not matched
  184. while (this.oldtip !== this.lastMatchedContainer) {
  185. this.finalize(this.oldtip, this.lineNumber - 1);
  186. this.oldtip = this.oldtip.parent;
  187. }
  188. return true;
  189. };
  190. // Analyze a line of text and update the document appropriately.
  191. // We parse markdown text by calling this on each line of input,
  192. // then finalizing the document.
  193. var incorporateLine = function(ln) {
  194. var all_matched = true;
  195. var first_nonspace;
  196. var offset = 0;
  197. var match;
  198. var data;
  199. var blank;
  200. var indent;
  201. var i;
  202. var CODE_INDENT = 4;
  203. var allClosed;
  204. var container = this.doc;
  205. this.oldtip = this.tip;
  206. // replace NUL characters for security
  207. if (ln.indexOf('\u0000') !== -1) {
  208. ln = ln.replace(/\0/g, '\uFFFD');
  209. }
  210. // Convert tabs to spaces:
  211. ln = detabLine(ln);
  212. // For each containing block, try to parse the associated line start.
  213. // Bail out on failure: container will point to the last matching block.
  214. // Set all_matched to false if not all containers match.
  215. while (container.lastChild) {
  216. if (!container.lastChild.open) {
  217. break;
  218. }
  219. container = container.lastChild;
  220. match = matchAt(reNonSpace, ln, offset);
  221. if (match === -1) {
  222. first_nonspace = ln.length;
  223. blank = true;
  224. } else {
  225. first_nonspace = match;
  226. blank = false;
  227. }
  228. indent = first_nonspace - offset;
  229. switch (container.t) {
  230. case 'BlockQuote':
  231. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  232. offset = first_nonspace + 1;
  233. if (ln.charCodeAt(offset) === C_SPACE) {
  234. offset++;
  235. }
  236. } else {
  237. all_matched = false;
  238. }
  239. break;
  240. case 'Item':
  241. if (indent >= container.list_data.marker_offset +
  242. container.list_data.padding) {
  243. offset += container.list_data.marker_offset +
  244. container.list_data.padding;
  245. } else if (blank) {
  246. offset = first_nonspace;
  247. } else {
  248. all_matched = false;
  249. }
  250. break;
  251. case 'Header':
  252. case 'HorizontalRule':
  253. // a header can never container > 1 line, so fail to match:
  254. all_matched = false;
  255. if (blank) {
  256. container.last_line_blank = true;
  257. }
  258. break;
  259. case 'CodeBlock':
  260. if (container.fence_length > 0) { // fenced
  261. // skip optional spaces of fence offset
  262. i = container.fence_offset;
  263. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  264. offset++;
  265. i--;
  266. }
  267. } else { // indented
  268. if (indent >= CODE_INDENT) {
  269. offset += CODE_INDENT;
  270. } else if (blank) {
  271. offset = first_nonspace;
  272. } else {
  273. all_matched = false;
  274. }
  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 !== 'CodeBlock' &&
  305. container.t !== 'HtmlBlock' &&
  306. // this is a little performance optimization:
  307. matchAt(reMaybeSpecial, ln, offset) !== -1) {
  308. match = matchAt(reNonSpace, ln, offset);
  309. if (match === -1) {
  310. first_nonspace = ln.length;
  311. blank = true;
  312. break;
  313. } else {
  314. first_nonspace = match;
  315. blank = false;
  316. }
  317. indent = first_nonspace - offset;
  318. if (indent >= CODE_INDENT) {
  319. // indented code
  320. if (this.tip.t !== 'Paragraph' && !blank) {
  321. offset += CODE_INDENT;
  322. allClosed = allClosed ||
  323. this.closeUnmatchedBlocks();
  324. container = this.addChild('CodeBlock', offset);
  325. }
  326. break;
  327. }
  328. offset = first_nonspace;
  329. var cc = ln.charCodeAt(offset);
  330. if (cc === C_GREATERTHAN) {
  331. // blockquote
  332. offset += 1;
  333. // optional following space
  334. if (ln.charCodeAt(offset) === C_SPACE) {
  335. offset++;
  336. }
  337. allClosed = allClosed || this.closeUnmatchedBlocks();
  338. container = this.addChild('BlockQuote', first_nonspace);
  339. } else if ((match = ln.slice(offset).match(reATXHeaderMarker))) {
  340. // ATX header
  341. offset += match[0].length;
  342. allClosed = allClosed || this.closeUnmatchedBlocks();
  343. container = this.addChild('Header', first_nonspace);
  344. container.level = match[0].trim().length; // number of #s
  345. // remove trailing ###s:
  346. container.strings =
  347. [ln.slice(offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/, '')];
  348. break;
  349. } else if ((match = ln.slice(offset).match(reCodeFence))) {
  350. // fenced code block
  351. var fence_length = match[0].length;
  352. allClosed = allClosed || this.closeUnmatchedBlocks();
  353. container = this.addChild('CodeBlock', first_nonspace);
  354. container.fence_length = fence_length;
  355. container.fence_char = match[0][0];
  356. container.fence_offset = indent;
  357. offset += fence_length;
  358. break;
  359. } else if (matchAt(reHtmlBlockOpen, ln, offset) !== -1) {
  360. // html block
  361. allClosed = allClosed || this.closeUnmatchedBlocks();
  362. container = this.addChild('HtmlBlock', offset);
  363. offset -= indent; // back up so spaces are part of block
  364. break;
  365. } else if (container.t === 'Paragraph' &&
  366. container.strings.length === 1 &&
  367. ((match = ln.slice(offset).match(reSetextHeaderLine)))) {
  368. // setext header line
  369. allClosed = allClosed || this.closeUnmatchedBlocks();
  370. container.t = 'Header'; // convert Paragraph to SetextHeader
  371. container.level = match[0][0] === '=' ? 1 : 2;
  372. offset = ln.length;
  373. break;
  374. } else if (matchAt(reHrule, ln, offset) !== -1) {
  375. // hrule
  376. allClosed = allClosed || this.closeUnmatchedBlocks();
  377. container = this.addChild('HorizontalRule', first_nonspace);
  378. offset = ln.length - 1;
  379. break;
  380. } else if ((data = parseListMarker(ln, offset, indent))) {
  381. // list item
  382. allClosed = allClosed || this.closeUnmatchedBlocks();
  383. offset += data.padding;
  384. // add the list if needed
  385. if (container.t !== 'List' ||
  386. !(listsMatch(container.list_data, data))) {
  387. container = this.addChild('List', first_nonspace);
  388. container.list_data = data;
  389. }
  390. // add the list item
  391. container = this.addChild('Item', first_nonspace);
  392. container.list_data = data;
  393. } else {
  394. break;
  395. }
  396. }
  397. // What remains at the offset is a text line. Add the text to the
  398. // appropriate container.
  399. match = matchAt(reNonSpace, ln, offset);
  400. if (match === -1) {
  401. first_nonspace = ln.length;
  402. blank = true;
  403. } else {
  404. first_nonspace = match;
  405. blank = false;
  406. }
  407. indent = first_nonspace - offset;
  408. // First check for a lazy paragraph continuation:
  409. if (!allClosed && !blank &&
  410. this.tip.t === 'Paragraph' &&
  411. this.tip.strings.length > 0) {
  412. // lazy paragraph continuation
  413. this.last_line_blank = false;
  414. this.addLine(ln, offset);
  415. } else { // not a lazy continuation
  416. // finalize any blocks not matched
  417. allClosed = allClosed || this.closeUnmatchedBlocks();
  418. // Block quote lines are never blank as they start with >
  419. // and we don't count blanks in fenced code for purposes of tight/loose
  420. // lists or breaking out of lists. We also don't set last_line_blank
  421. // on an empty list item.
  422. var t = container.t;
  423. container.last_line_blank = blank &&
  424. !(t === 'BlockQuote' ||
  425. t === 'Header' ||
  426. (t === 'CodeBlock' && container.fence_length > 0) ||
  427. (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 'HtmlBlock':
  437. this.addLine(ln, offset);
  438. break;
  439. case 'CodeBlock':
  440. if (container.fence_length > 0) { // fenced
  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. } else { // indented
  452. this.addLine(ln, offset);
  453. }
  454. break;
  455. case 'Header':
  456. case 'HorizontalRule':
  457. // nothing to do; we already added the contents.
  458. break;
  459. default:
  460. if (acceptsLines(container.t)) {
  461. this.addLine(ln, first_nonspace);
  462. } else if (blank) {
  463. break;
  464. } else {
  465. // create paragraph container for line
  466. container = this.addChild('Paragraph', this.lineNumber, first_nonspace);
  467. this.addLine(ln, first_nonspace);
  468. }
  469. }
  470. }
  471. this.lastLineLength = ln.length - 1; // -1 for newline
  472. };
  473. // Finalize a block. Close it and do any necessary postprocessing,
  474. // e.g. creating string_content from strings, setting the 'tight'
  475. // or 'loose' status of a list, and parsing the beginnings
  476. // of paragraphs for reference definitions. Reset the tip to the
  477. // parent of the closed block.
  478. var finalize = function(block, lineNumber) {
  479. var pos;
  480. // don't do anything if the block is already closed
  481. if (!block.open) {
  482. return 0;
  483. }
  484. block.open = false;
  485. block.sourcepos[1] = [lineNumber, this.lastLineLength + 1];
  486. switch (block.t) {
  487. case 'Paragraph':
  488. block.string_content = block.strings.join('\n');
  489. // try parsing the beginning as link reference definitions:
  490. while (block.string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  491. (pos = this.inlineParser.parseReference(block.string_content,
  492. this.refmap))) {
  493. block.string_content = block.string_content.slice(pos);
  494. if (isBlank(block.string_content)) {
  495. block.t = 'ReferenceDef';
  496. break;
  497. }
  498. }
  499. break;
  500. case 'Header':
  501. block.string_content = block.strings.join('\n');
  502. break;
  503. case 'HtmlBlock':
  504. block.literal = block.strings.join('\n');
  505. break;
  506. case 'CodeBlock':
  507. if (block.fence_length > 0) { // fenced
  508. // first line becomes info string
  509. block.info = unescapeString(block.strings[0].trim());
  510. if (block.strings.length === 1) {
  511. block.literal = '';
  512. } else {
  513. block.literal = block.strings.slice(1).join('\n') + '\n';
  514. }
  515. } else { // indented
  516. stripFinalBlankLines(block.strings);
  517. block.literal = block.strings.join('\n') + '\n';
  518. }
  519. break;
  520. case 'List':
  521. block.list_data.tight = true; // tight by default
  522. var item = block.firstChild;
  523. while (item) {
  524. // check for non-final list item ending with blank line:
  525. if (endsWithBlankLine(item) && item.next) {
  526. block.list_data.tight = false;
  527. break;
  528. }
  529. // recurse into children of list item, to see if there are
  530. // spaces between any of them:
  531. var subitem = item.firstChild;
  532. while (subitem) {
  533. if (endsWithBlankLine(subitem) && (item.next || subitem.next)) {
  534. block.list_data.tight = false;
  535. break;
  536. }
  537. subitem = subitem.next;
  538. }
  539. item = item.next;
  540. }
  541. break;
  542. default:
  543. break;
  544. }
  545. this.tip = block.parent || this.top;
  546. };
  547. // Walk through a block & children recursively, parsing string content
  548. // into inline content where appropriate. Returns new object.
  549. var processInlines = function(block) {
  550. var node, event;
  551. var walker = block.walker();
  552. while ((event = walker.next())) {
  553. node = event.node;
  554. if (!event.entering && (node.t === 'Paragraph' ||
  555. node.t === 'Header')) {
  556. this.inlineParser.parse(node, this.refmap);
  557. }
  558. }
  559. };
  560. var Document = function() {
  561. var doc = new Node('Document', [[1, 1], [0, 0]]);
  562. doc.string_content = null;
  563. doc.strings = [];
  564. return doc;
  565. };
  566. // The main parsing function. Returns a parsed document AST.
  567. var parse = function(input) {
  568. this.doc = new Document();
  569. this.tip = this.doc;
  570. this.refmap = {};
  571. if (this.options.time) { console.time("preparing input"); }
  572. var lines = input.split(reLineEnding);
  573. var len = lines.length;
  574. if (input.charCodeAt(input.length - 1) === C_NEWLINE) {
  575. // ignore last blank line created by final newline
  576. len -= 1;
  577. }
  578. if (this.options.time) { console.timeEnd("preparing input"); }
  579. if (this.options.time) { console.time("block parsing"); }
  580. for (var i = 0; i < len; i++) {
  581. this.lineNumber += 1;
  582. this.incorporateLine(lines[i]);
  583. }
  584. while (this.tip) {
  585. this.finalize(this.tip, len);
  586. }
  587. if (this.options.time) { console.timeEnd("block parsing"); }
  588. if (this.options.time) { console.time("inline parsing"); }
  589. this.processInlines(this.doc);
  590. if (this.options.time) { console.timeEnd("inline parsing"); }
  591. return this.doc;
  592. };
  593. // The DocParser object.
  594. function DocParser(options){
  595. return {
  596. doc: new Document(),
  597. tip: this.doc,
  598. oldtip: this.doc,
  599. lineNumber: 0,
  600. lastMatchedContainer: this.doc,
  601. refmap: {},
  602. lastLineLength: 0,
  603. inlineParser: new InlineParser(),
  604. breakOutOfLists: breakOutOfLists,
  605. addLine: addLine,
  606. addChild: addChild,
  607. incorporateLine: incorporateLine,
  608. finalize: finalize,
  609. processInlines: processInlines,
  610. closeUnmatchedBlocks: closeUnmatchedBlocks,
  611. parse: parse,
  612. options: options || {}
  613. };
  614. }
  615. module.exports = DocParser;