aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: d8c25a118895478459d77e79ebecec6421e9bb7a (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.getType();
  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.getType() === '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.getType(), 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.getType()) {
  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.getType();
  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.getType() !== '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 (container.getType() === 'Paragraph' &&
  368. container.strings.length === 1 &&
  369. ((match = ln.slice(offset).match(reSetextHeaderLine)))) {
  370. // setext header line
  371. allClosed = allClosed || this.closeUnmatchedBlocks();
  372. container.setType('Header'); // convert Paragraph to SetextHeader
  373. container.level = match[0][0] === '=' ? 1 : 2;
  374. offset = ln.length;
  375. break;
  376. } else if (matchAt(reHrule, ln, offset) !== -1) {
  377. // hrule
  378. allClosed = allClosed || this.closeUnmatchedBlocks();
  379. container = this.addChild('HorizontalRule', first_nonspace);
  380. offset = ln.length - 1;
  381. break;
  382. } else if ((data = parseListMarker(ln, offset, indent))) {
  383. // list item
  384. allClosed = allClosed || this.closeUnmatchedBlocks();
  385. offset += data.padding;
  386. // add the list if needed
  387. if (container.getType() !== 'List' ||
  388. !(listsMatch(container.list_data, data))) {
  389. container = this.addChild('List', first_nonspace);
  390. container.list_data = data;
  391. }
  392. // add the list item
  393. container = this.addChild('Item', first_nonspace);
  394. container.list_data = data;
  395. } else {
  396. break;
  397. }
  398. }
  399. // What remains at the offset is a text line. Add the text to the
  400. // appropriate container.
  401. match = matchAt(reNonSpace, ln, offset);
  402. if (match === -1) {
  403. first_nonspace = ln.length;
  404. blank = true;
  405. } else {
  406. first_nonspace = match;
  407. blank = false;
  408. }
  409. indent = first_nonspace - offset;
  410. // First check for a lazy paragraph continuation:
  411. if (!allClosed && !blank &&
  412. this.tip.getType() === 'Paragraph' &&
  413. this.tip.strings.length > 0) {
  414. // lazy paragraph continuation
  415. this.last_line_blank = false;
  416. this.addLine(ln, offset);
  417. } else { // not a lazy continuation
  418. // finalize any blocks not matched
  419. allClosed = allClosed || this.closeUnmatchedBlocks();
  420. // Block quote lines are never blank as they start with >
  421. // and we don't count blanks in fenced code for purposes of tight/loose
  422. // lists or breaking out of lists. We also don't set last_line_blank
  423. // on an empty list item.
  424. var t = container.getType();
  425. container.last_line_blank = blank &&
  426. !(t === 'BlockQuote' ||
  427. t === 'Header' ||
  428. (t === 'CodeBlock' && container.fence_length > 0) ||
  429. (t === 'Item' &&
  430. !container.firstChild &&
  431. container.sourcepos[0][0] === this.lineNumber));
  432. var cont = container;
  433. while (cont.parent) {
  434. cont.parent.last_line_blank = false;
  435. cont = cont.parent;
  436. }
  437. switch (container.getType()) {
  438. case 'HtmlBlock':
  439. this.addLine(ln, offset);
  440. break;
  441. case 'CodeBlock':
  442. if (container.fence_length > 0) { // fenced
  443. // check for closing code fence:
  444. match = (indent <= 3 &&
  445. ln.charAt(first_nonspace) === container.fence_char &&
  446. ln.slice(first_nonspace).match(reClosingCodeFence));
  447. if (match && match[0].length >= container.fence_length) {
  448. // don't add closing fence to container; instead, close it:
  449. this.finalize(container, this.lineNumber);
  450. } else {
  451. this.addLine(ln, offset);
  452. }
  453. } else { // indented
  454. this.addLine(ln, offset);
  455. }
  456. break;
  457. case 'Header':
  458. case 'HorizontalRule':
  459. // nothing to do; we already added the contents.
  460. break;
  461. default:
  462. if (acceptsLines(container.getType())) {
  463. this.addLine(ln, first_nonspace);
  464. } else if (blank) {
  465. break;
  466. } else {
  467. // create paragraph container for line
  468. container = this.addChild('Paragraph', this.lineNumber, first_nonspace);
  469. this.addLine(ln, first_nonspace);
  470. }
  471. }
  472. }
  473. this.lastLineLength = ln.length - 1; // -1 for newline
  474. };
  475. // Finalize a block. Close it and do any necessary postprocessing,
  476. // e.g. creating string_content from strings, setting the 'tight'
  477. // or 'loose' status of a list, and parsing the beginnings
  478. // of paragraphs for reference definitions. Reset the tip to the
  479. // parent of the closed block.
  480. var finalize = function(block, lineNumber) {
  481. var pos;
  482. var above = block.parent || this.top;
  483. // don't do anything if the block is already closed
  484. if (!block.open) {
  485. return 0;
  486. }
  487. block.open = false;
  488. block.sourcepos[1] = [lineNumber, this.lastLineLength + 1];
  489. switch (block.getType()) {
  490. case 'Paragraph':
  491. block.string_content = block.strings.join('\n');
  492. // try parsing the beginning as link reference definitions:
  493. while (block.string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  494. (pos = this.inlineParser.parseReference(block.string_content,
  495. this.refmap))) {
  496. block.string_content = block.string_content.slice(pos);
  497. if (isBlank(block.string_content)) {
  498. block.unlink();
  499. break;
  500. }
  501. }
  502. break;
  503. case 'Header':
  504. block.string_content = block.strings.join('\n');
  505. break;
  506. case 'HtmlBlock':
  507. block.literal = block.strings.join('\n');
  508. break;
  509. case 'CodeBlock':
  510. if (block.fence_length > 0) { // fenced
  511. // first line becomes info string
  512. block.info = unescapeString(block.strings[0].trim());
  513. if (block.strings.length === 1) {
  514. block.literal = '';
  515. } else {
  516. block.literal = block.strings.slice(1).join('\n') + '\n';
  517. }
  518. } else { // indented
  519. stripFinalBlankLines(block.strings);
  520. block.literal = block.strings.join('\n') + '\n';
  521. }
  522. break;
  523. case 'List':
  524. block.list_data.tight = true; // tight by default
  525. var item = block.firstChild;
  526. while (item) {
  527. // check for non-final list item ending with blank line:
  528. if (endsWithBlankLine(item) && item.next) {
  529. block.list_data.tight = false;
  530. break;
  531. }
  532. // recurse into children of list item, to see if there are
  533. // spaces between any of them:
  534. var subitem = item.firstChild;
  535. while (subitem) {
  536. if (endsWithBlankLine(subitem) && (item.next || subitem.next)) {
  537. block.list_data.tight = false;
  538. break;
  539. }
  540. subitem = subitem.next;
  541. }
  542. item = item.next;
  543. }
  544. break;
  545. default:
  546. break;
  547. }
  548. this.tip = above;
  549. };
  550. // Walk through a block & children recursively, parsing string content
  551. // into inline content where appropriate. Returns new object.
  552. var processInlines = function(block) {
  553. var node, event, t;
  554. var walker = block.walker();
  555. while ((event = walker.next())) {
  556. node = event.node;
  557. t = node.getType();
  558. if (!event.entering && (t === 'Paragraph' || t === 'Header')) {
  559. this.inlineParser.parse(node, this.refmap);
  560. }
  561. }
  562. };
  563. var Document = function() {
  564. var doc = new Node('Document', [[1, 1], [0, 0]]);
  565. doc.string_content = null;
  566. doc.strings = [];
  567. return doc;
  568. };
  569. // The main parsing function. Returns a parsed document AST.
  570. var parse = function(input) {
  571. this.doc = new Document();
  572. this.tip = this.doc;
  573. this.refmap = {};
  574. if (this.options.time) { console.time("preparing input"); }
  575. var lines = input.split(reLineEnding);
  576. var len = lines.length;
  577. if (input.charCodeAt(input.length - 1) === C_NEWLINE) {
  578. // ignore last blank line created by final newline
  579. len -= 1;
  580. }
  581. if (this.options.time) { console.timeEnd("preparing input"); }
  582. if (this.options.time) { console.time("block parsing"); }
  583. for (var i = 0; i < len; i++) {
  584. this.lineNumber += 1;
  585. this.incorporateLine(lines[i]);
  586. }
  587. while (this.tip) {
  588. this.finalize(this.tip, len);
  589. }
  590. if (this.options.time) { console.timeEnd("block parsing"); }
  591. if (this.options.time) { console.time("inline parsing"); }
  592. this.processInlines(this.doc);
  593. if (this.options.time) { console.timeEnd("inline parsing"); }
  594. return this.doc;
  595. };
  596. // The DocParser object.
  597. function DocParser(options){
  598. return {
  599. doc: new Document(),
  600. tip: this.doc,
  601. oldtip: this.doc,
  602. lineNumber: 0,
  603. lastMatchedContainer: this.doc,
  604. refmap: {},
  605. lastLineLength: 0,
  606. inlineParser: new InlineParser(),
  607. breakOutOfLists: breakOutOfLists,
  608. addLine: addLine,
  609. addChild: addChild,
  610. incorporateLine: incorporateLine,
  611. finalize: finalize,
  612. processInlines: processInlines,
  613. closeUnmatchedBlocks: closeUnmatchedBlocks,
  614. parse: parse,
  615. options: options || {}
  616. };
  617. }
  618. module.exports = DocParser;