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