aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: 8001927e2f361e9784bae086634ca00561305ee3 (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. if (!(this.tip._open)) {
  116. throw { msg: "Attempted to add line (" + ln + ") to closed container." };
  117. }
  118. this.tip._strings.push(ln.slice(offset));
  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.type, 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, // lists are tight by default
  143. bulletChar: null,
  144. start: null,
  145. delimiter: null,
  146. padding: null,
  147. markerOffset: 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.bulletChar = 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.bulletChar === item_data.bulletChar);
  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. var parent = this.oldtip._parent;
  186. this.finalize(this.oldtip, this.lineNumber - 1);
  187. this.oldtip = parent;
  188. }
  189. return true;
  190. };
  191. // Analyze a line of text and update the document appropriately.
  192. // We parse markdown text by calling this on each line of input,
  193. // then finalizing the document.
  194. var incorporateLine = function(ln) {
  195. var all_matched = true;
  196. var first_nonspace;
  197. var offset = 0;
  198. var match;
  199. var data;
  200. var blank;
  201. var indent;
  202. var i;
  203. var CODE_INDENT = 4;
  204. var allClosed;
  205. var container = this.doc;
  206. this.oldtip = this.tip;
  207. // replace NUL characters for security
  208. if (ln.indexOf('\u0000') !== -1) {
  209. ln = ln.replace(/\0/g, '\uFFFD');
  210. }
  211. // Convert tabs to spaces:
  212. ln = detabLine(ln);
  213. // For each containing block, try to parse the associated line start.
  214. // Bail out on failure: container will point to the last matching block.
  215. // Set all_matched to false if not all containers match.
  216. var lastChild;
  217. while ((lastChild = container._lastChild) && lastChild._open) {
  218. container = lastChild;
  219. match = matchAt(reNonSpace, ln, offset);
  220. if (match === -1) {
  221. first_nonspace = ln.length;
  222. blank = true;
  223. } else {
  224. first_nonspace = match;
  225. blank = false;
  226. }
  227. indent = first_nonspace - offset;
  228. switch (container.type) {
  229. case 'BlockQuote':
  230. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  231. offset = first_nonspace + 1;
  232. if (ln.charCodeAt(offset) === C_SPACE) {
  233. offset++;
  234. }
  235. } else {
  236. all_matched = false;
  237. }
  238. break;
  239. case 'Item':
  240. if (blank) {
  241. offset = first_nonspace;
  242. } else if (indent >= container._listData.markerOffset +
  243. container._listData.padding) {
  244. offset += container._listData.markerOffset +
  245. container._listData.padding;
  246. } else {
  247. all_matched = false;
  248. }
  249. break;
  250. case 'Header':
  251. case 'HorizontalRule':
  252. // a header can never container > 1 line, so fail to match:
  253. all_matched = false;
  254. if (blank) {
  255. container._lastLineBlank = true;
  256. }
  257. break;
  258. case 'CodeBlock':
  259. if (container._isFenced) { // fenced
  260. if (container._fenceLength === -1) {
  261. all_matched = false;
  262. if (blank) {
  263. container._lastLineBlank = true;
  264. }
  265. } else {
  266. // skip optional spaces of fence offset
  267. i = container._fenceOffset;
  268. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  269. offset++;
  270. i--;
  271. }
  272. }
  273. } else { // indented
  274. if (indent >= CODE_INDENT) {
  275. offset += CODE_INDENT;
  276. } else if (blank) {
  277. offset = first_nonspace;
  278. } else {
  279. all_matched = false;
  280. }
  281. }
  282. break;
  283. case 'HtmlBlock':
  284. if (blank) {
  285. container._lastLineBlank = true;
  286. all_matched = false;
  287. }
  288. break;
  289. case 'Paragraph':
  290. if (blank) {
  291. container._lastLineBlank = true;
  292. all_matched = false;
  293. }
  294. break;
  295. default:
  296. }
  297. if (!all_matched) {
  298. container = container._parent; // back up to last matching block
  299. break;
  300. }
  301. }
  302. allClosed = (container === this.oldtip);
  303. this.lastMatchedContainer = container;
  304. // Check to see if we've hit 2nd blank line; if so break out of list:
  305. if (blank && container._lastLineBlank) {
  306. this.breakOutOfLists(container);
  307. }
  308. // Unless last matched container is a code block, try new container starts,
  309. // adding children to the last matched container:
  310. while (true) {
  311. var t = container.type;
  312. match = matchAt(reNonSpace, ln, offset);
  313. if (match === -1) {
  314. first_nonspace = ln.length;
  315. blank = true;
  316. break;
  317. } else {
  318. first_nonspace = match;
  319. blank = false;
  320. }
  321. indent = first_nonspace - offset;
  322. if (t === 'CodeBlock' || t === 'HtmlBlock') {
  323. break;
  324. }
  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. // this is a little performance optimization:
  336. if (matchAt(reMaybeSpecial, ln, first_nonspace) === -1) {
  337. break;
  338. }
  339. offset = first_nonspace;
  340. var cc = ln.charCodeAt(offset);
  341. if (cc === C_GREATERTHAN) {
  342. // blockquote
  343. offset += 1;
  344. // optional following space
  345. if (ln.charCodeAt(offset) === C_SPACE) {
  346. offset++;
  347. }
  348. allClosed = allClosed || this.closeUnmatchedBlocks();
  349. container = this.addChild('BlockQuote', first_nonspace);
  350. } else if ((match = ln.slice(offset).match(reATXHeaderMarker))) {
  351. // ATX header
  352. offset += match[0].length;
  353. allClosed = allClosed || this.closeUnmatchedBlocks();
  354. container = this.addChild('Header', first_nonspace);
  355. container.level = match[0].trim().length; // number of #s
  356. // remove trailing ###s:
  357. container._strings =
  358. [ln.slice(offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/, '')];
  359. break;
  360. } else if ((match = ln.slice(offset).match(reCodeFence))) {
  361. // fenced code block
  362. var fenceLength = match[0].length;
  363. allClosed = allClosed || this.closeUnmatchedBlocks();
  364. container = this.addChild('CodeBlock', first_nonspace);
  365. container._isFenced = true;
  366. container._fenceLength = fenceLength;
  367. container._fenceChar = match[0][0];
  368. container._fenceOffset = indent;
  369. offset += fenceLength;
  370. } else if (matchAt(reHtmlBlockOpen, ln, offset) !== -1) {
  371. // html block
  372. allClosed = allClosed || this.closeUnmatchedBlocks();
  373. container = this.addChild('HtmlBlock', offset);
  374. offset -= indent; // back up so spaces are part of block
  375. break;
  376. } else if (t === 'Paragraph' &&
  377. container._strings.length === 1 &&
  378. ((match = ln.slice(offset).match(reSetextHeaderLine)))) {
  379. // setext header line
  380. allClosed = allClosed || this.closeUnmatchedBlocks();
  381. var header = new Node('Header', container.sourcepos);
  382. header.level = match[0][0] === '=' ? 1 : 2;
  383. header._strings = container._strings;
  384. container.insertAfter(header);
  385. container.unlink();
  386. container = header;
  387. this.tip = header;
  388. offset = ln.length;
  389. break;
  390. } else if (matchAt(reHrule, ln, offset) !== -1) {
  391. // hrule
  392. allClosed = allClosed || this.closeUnmatchedBlocks();
  393. container = this.addChild('HorizontalRule', first_nonspace);
  394. offset = ln.length - 1;
  395. break;
  396. } else if ((data = parseListMarker(ln, offset, indent))) {
  397. // list item
  398. allClosed = allClosed || this.closeUnmatchedBlocks();
  399. offset += data.padding;
  400. // add the list if needed
  401. if (t !== 'List' ||
  402. !(listsMatch(container._listData, data))) {
  403. container = this.addChild('List', first_nonspace);
  404. container._listData = data;
  405. }
  406. // add the list item
  407. container = this.addChild('Item', first_nonspace);
  408. container._listData = data;
  409. } else {
  410. break;
  411. }
  412. }
  413. // What remains at the offset is a text line. Add the text to the
  414. // appropriate container.
  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._lastLineBlank = 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 _lastLineBlank
  429. // on an empty list item.
  430. container._lastLineBlank = blank &&
  431. !(t === 'BlockQuote' ||
  432. t === 'Header' ||
  433. (t === 'CodeBlock' && container._isFenced) ||
  434. (t === 'Item' &&
  435. !container._firstChild &&
  436. container.sourcepos[0][0] === this.lineNumber));
  437. var cont = container;
  438. while (cont._parent) {
  439. cont._parent._lastLineBlank = 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._isFenced) { // fenced
  448. // check for closing code fence:
  449. match = (indent <= 3 &&
  450. ln.charAt(first_nonspace) === container._fenceChar &&
  451. ln.slice(first_nonspace).match(reClosingCodeFence));
  452. if (match && match[0].length >= container._fenceLength) {
  453. // don't add closing fence to container; instead, close it:
  454. container._fenceLength = -1; // -1 means we've passed closer
  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._isFenced) { // 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. var item = block._firstChild;
  530. while (item) {
  531. // check for non-final list item ending with blank line:
  532. if (endsWithBlankLine(item) && item._next) {
  533. block._listData.tight = false;
  534. break;
  535. }
  536. // recurse into children of list item, to see if there are
  537. // spaces between any of them:
  538. var subitem = item._firstChild;
  539. while (subitem) {
  540. if (endsWithBlankLine(subitem) &&
  541. (item._next || subitem._next)) {
  542. block._listData.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;