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