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