aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: cf64652f0c638985a45baa41097581b9eab55930 (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 Parser 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) {
  115. this.tip._strings.push(ln.slice(this.offset));
  116. };
  117. // Add block of type tag as a child of the tip. If the tip can't
  118. // accept children, close and finalize it and try its parent,
  119. // and so on til we find a block that can accept children.
  120. var addChild = function(tag, offset) {
  121. while (!canContain(this.tip.type, tag)) {
  122. this.finalize(this.tip, this.lineNumber - 1);
  123. }
  124. var column_number = offset + 1; // offset 0 = column 1
  125. var newBlock = new Node(tag, [[this.lineNumber, column_number], [0, 0]]);
  126. newBlock._strings = [];
  127. newBlock._string_content = null;
  128. this.tip.appendChild(newBlock);
  129. this.tip = newBlock;
  130. return newBlock;
  131. };
  132. // Parse a list marker and return data on the marker (type,
  133. // start, delimiter, bullet character, padding) or null.
  134. var parseListMarker = function(ln, offset, indent) {
  135. var rest = ln.slice(offset);
  136. var match;
  137. var spaces_after_marker;
  138. var data = { type: null,
  139. tight: true, // lists are tight by default
  140. bulletChar: null,
  141. start: null,
  142. delimiter: null,
  143. padding: null,
  144. markerOffset: indent };
  145. if (rest.match(reHrule)) {
  146. return null;
  147. }
  148. if ((match = rest.match(reBulletListMarker))) {
  149. spaces_after_marker = match[1].length;
  150. data.type = 'Bullet';
  151. data.bulletChar = match[0][0];
  152. } else if ((match = rest.match(reOrderedListMarker))) {
  153. spaces_after_marker = match[3].length;
  154. data.type = 'Ordered';
  155. data.start = parseInt(match[1]);
  156. data.delimiter = match[2];
  157. } else {
  158. return null;
  159. }
  160. var blank_item = match[0].length === rest.length;
  161. if (spaces_after_marker >= 5 ||
  162. spaces_after_marker < 1 ||
  163. blank_item) {
  164. data.padding = match[0].length - spaces_after_marker + 1;
  165. } else {
  166. data.padding = match[0].length;
  167. }
  168. return data;
  169. };
  170. // Returns true if the two list items are of the same type,
  171. // with the same delimiter and bullet character. This is used
  172. // in agglomerating list items into lists.
  173. var listsMatch = function(list_data, item_data) {
  174. return (list_data.type === item_data.type &&
  175. list_data.delimiter === item_data.delimiter &&
  176. list_data.bulletChar === item_data.bulletChar);
  177. };
  178. // Finalize and close any unmatched blocks. Returns true.
  179. var closeUnmatchedBlocks = function() {
  180. // finalize any blocks not matched
  181. while (this.oldtip !== this.lastMatchedContainer) {
  182. var parent = this.oldtip._parent;
  183. this.finalize(this.oldtip, this.lineNumber - 1);
  184. this.oldtip = parent;
  185. }
  186. return true;
  187. };
  188. // Analyze a line of text and update the document appropriately.
  189. // We parse markdown text by calling this on each line of input,
  190. // then finalizing the document.
  191. var incorporateLine = function(ln) {
  192. var all_matched = true;
  193. var first_nonspace;
  194. var match;
  195. var data;
  196. var blank;
  197. var indent;
  198. var i;
  199. var CODE_INDENT = 4;
  200. var allClosed;
  201. var container = this.doc;
  202. this.oldtip = this.tip;
  203. this.offset = 0;
  204. this.lineNumber += 1;
  205. // replace NUL characters for security
  206. if (ln.indexOf('\u0000') !== -1) {
  207. ln = ln.replace(/\0/g, '\uFFFD');
  208. }
  209. // Convert tabs to spaces:
  210. ln = detabLine(ln);
  211. // For each containing block, try to parse the associated line start.
  212. // Bail out on failure: container will point to the last matching block.
  213. // Set all_matched to false if not all containers match.
  214. var lastChild;
  215. while ((lastChild = container._lastChild) && lastChild._open) {
  216. container = lastChild;
  217. match = matchAt(reNonSpace, ln, this.offset);
  218. if (match === -1) {
  219. first_nonspace = ln.length;
  220. blank = true;
  221. } else {
  222. first_nonspace = match;
  223. blank = false;
  224. }
  225. indent = first_nonspace - this.offset;
  226. switch (container.type) {
  227. case 'BlockQuote':
  228. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  229. this.offset = first_nonspace + 1;
  230. if (ln.charCodeAt(this.offset) === C_SPACE) {
  231. this.offset++;
  232. }
  233. } else {
  234. all_matched = false;
  235. }
  236. break;
  237. case 'Item':
  238. if (blank) {
  239. this.offset = first_nonspace;
  240. } else if (indent >= container._listData.markerOffset +
  241. container._listData.padding) {
  242. this.offset += container._listData.markerOffset +
  243. container._listData.padding;
  244. } else {
  245. all_matched = false;
  246. }
  247. break;
  248. case 'Header':
  249. case 'HorizontalRule':
  250. // a header can never container > 1 line, so fail to match:
  251. all_matched = false;
  252. break;
  253. case 'CodeBlock':
  254. if (container._isFenced) { // fenced
  255. match = (indent <= 3 &&
  256. ln.charAt(first_nonspace) === container._fenceChar &&
  257. ln.slice(first_nonspace).match(reClosingCodeFence));
  258. if (match && match[0].length >= container._fenceLength) {
  259. // closing fence - we're at end of line, so we can return
  260. all_matched = false;
  261. this.finalize(container, this.lineNumber);
  262. this.lastLineLength = ln.length - 1; // -1 for newline
  263. return;
  264. } else {
  265. // skip optional spaces of fence offset
  266. i = container._fenceOffset;
  267. while (i > 0 && ln.charCodeAt(this.offset) === C_SPACE) {
  268. this.offset++;
  269. i--;
  270. }
  271. }
  272. } else { // indented
  273. if (indent >= CODE_INDENT) {
  274. this.offset += CODE_INDENT;
  275. } else if (blank) {
  276. this.offset = first_nonspace;
  277. } else {
  278. all_matched = false;
  279. }
  280. }
  281. break;
  282. case 'HtmlBlock':
  283. if (blank) {
  284. all_matched = false;
  285. }
  286. break;
  287. case 'Paragraph':
  288. if (blank) {
  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. while (true) {
  308. var t = container.type;
  309. match = matchAt(reNonSpace, ln, this.offset);
  310. if (match === -1) {
  311. first_nonspace = ln.length;
  312. blank = true;
  313. break;
  314. } else {
  315. first_nonspace = match;
  316. blank = false;
  317. }
  318. indent = first_nonspace - this.offset;
  319. if (t === 'CodeBlock' || t === 'HtmlBlock') {
  320. break;
  321. }
  322. if (indent >= CODE_INDENT) {
  323. // indented code
  324. if (this.tip.type !== 'Paragraph' && !blank) {
  325. this.offset += CODE_INDENT;
  326. allClosed = allClosed ||
  327. this.closeUnmatchedBlocks();
  328. container = this.addChild('CodeBlock', this.offset);
  329. }
  330. break;
  331. }
  332. // this is a little performance optimization:
  333. if (matchAt(reMaybeSpecial, ln, first_nonspace) === -1) {
  334. break;
  335. }
  336. this.offset = first_nonspace;
  337. var cc = ln.charCodeAt(this.offset);
  338. if (cc === C_GREATERTHAN) {
  339. // blockquote
  340. this.offset += 1;
  341. // optional following space
  342. if (ln.charCodeAt(this.offset) === C_SPACE) {
  343. this.offset++;
  344. }
  345. allClosed = allClosed || this.closeUnmatchedBlocks();
  346. container = this.addChild('BlockQuote', first_nonspace);
  347. } else if ((match = ln.slice(this.offset).match(reATXHeaderMarker))) {
  348. // ATX header
  349. this.offset += match[0].length;
  350. allClosed = allClosed || this.closeUnmatchedBlocks();
  351. container = this.addChild('Header', first_nonspace);
  352. container.level = match[0].trim().length; // number of #s
  353. // remove trailing ###s:
  354. container._strings =
  355. [ln.slice(this.offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/, '')];
  356. break;
  357. } else if ((match = ln.slice(this.offset).match(reCodeFence))) {
  358. // fenced code block
  359. var fenceLength = match[0].length;
  360. allClosed = allClosed || this.closeUnmatchedBlocks();
  361. container = this.addChild('CodeBlock', first_nonspace);
  362. container._isFenced = true;
  363. container._fenceLength = fenceLength;
  364. container._fenceChar = match[0][0];
  365. container._fenceOffset = indent;
  366. this.offset += fenceLength;
  367. } else if (matchAt(reHtmlBlockOpen, ln, this.offset) !== -1) {
  368. // html block
  369. allClosed = allClosed || this.closeUnmatchedBlocks();
  370. container = this.addChild('HtmlBlock', this.offset);
  371. this.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(this.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. this.offset = ln.length;
  386. break;
  387. } else if (matchAt(reHrule, ln, this.offset) !== -1) {
  388. // hrule
  389. allClosed = allClosed || this.closeUnmatchedBlocks();
  390. container = this.addChild('HorizontalRule', first_nonspace);
  391. this.offset = ln.length - 1;
  392. break;
  393. } else if ((data = parseListMarker(ln, this.offset, indent))) {
  394. // list item
  395. allClosed = allClosed || this.closeUnmatchedBlocks();
  396. this.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. // First check for a lazy paragraph continuation:
  413. if (!allClosed && !blank &&
  414. this.tip.type === 'Paragraph' &&
  415. this.tip._strings.length > 0) {
  416. // lazy paragraph continuation
  417. this.addLine(ln);
  418. } else { // not a lazy continuation
  419. // finalize any blocks not matched
  420. allClosed = allClosed || this.closeUnmatchedBlocks();
  421. if (blank && container.lastChild) {
  422. container.lastChild._lastLineBlank = true;
  423. }
  424. t = container.type;
  425. // Block quote lines are never blank as they start with >
  426. // and we don't count blanks in fenced code for purposes of tight/loose
  427. // lists or breaking out of lists. We also don't set _lastLineBlank
  428. // on an empty list item, or if we just closed a fenced block.
  429. var lastLineBlank = blank &&
  430. !(t === 'BlockQuote' ||
  431. (t === 'CodeBlock' && container._isFenced) ||
  432. (t === 'Item' &&
  433. !container._firstChild &&
  434. container.sourcepos[0][0] === this.lineNumber));
  435. // propagate lastLineBlank up through parents:
  436. var cont = container;
  437. while (cont) {
  438. cont._lastLineBlank = lastLineBlank;
  439. cont = cont._parent;
  440. }
  441. switch (t) {
  442. case 'HtmlBlock':
  443. case 'CodeBlock':
  444. this.addLine(ln);
  445. break;
  446. case 'Header':
  447. case 'HorizontalRule':
  448. // nothing to do; we already added the contents.
  449. break;
  450. default:
  451. this.offset = first_nonspace;
  452. if (acceptsLines(t)) {
  453. this.addLine(ln);
  454. } else if (blank) {
  455. break;
  456. } else {
  457. // create paragraph container for line
  458. container = this.addChild('Paragraph', this.offset);
  459. this.addLine(ln);
  460. }
  461. }
  462. }
  463. this.lastLineLength = ln.length - 1; // -1 for newline
  464. };
  465. // Finalize a block. Close it and do any necessary postprocessing,
  466. // e.g. creating string_content from strings, setting the 'tight'
  467. // or 'loose' status of a list, and parsing the beginnings
  468. // of paragraphs for reference definitions. Reset the tip to the
  469. // parent of the closed block.
  470. var finalize = function(block, lineNumber) {
  471. var pos;
  472. var above = block._parent;
  473. block._open = false;
  474. block.sourcepos[1] = [lineNumber, this.lastLineLength + 1];
  475. switch (block.type) {
  476. case 'Paragraph':
  477. block._string_content = block._strings.join('\n');
  478. // try parsing the beginning as link reference definitions:
  479. while (block._string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  480. (pos = this.inlineParser.parseReference(block._string_content,
  481. this.refmap))) {
  482. block._string_content = block._string_content.slice(pos);
  483. if (isBlank(block._string_content)) {
  484. block.unlink();
  485. break;
  486. }
  487. }
  488. break;
  489. case 'Header':
  490. block._string_content = block._strings.join('\n');
  491. break;
  492. case 'HtmlBlock':
  493. block._literal = block._strings.join('\n');
  494. break;
  495. case 'CodeBlock':
  496. if (block._isFenced) { // fenced
  497. // first line becomes info string
  498. block.info = unescapeString(block._strings[0].trim());
  499. if (block._strings.length === 1) {
  500. block._literal = '';
  501. } else {
  502. block._literal = block._strings.slice(1).join('\n') + '\n';
  503. }
  504. } else { // indented
  505. stripFinalBlankLines(block._strings);
  506. block._literal = block._strings.join('\n') + '\n';
  507. }
  508. break;
  509. case 'List':
  510. var item = block._firstChild;
  511. while (item) {
  512. // check for non-final list item ending with blank line:
  513. if (endsWithBlankLine(item) && item._next) {
  514. block._listData.tight = false;
  515. break;
  516. }
  517. // recurse into children of list item, to see if there are
  518. // spaces between any of them:
  519. var subitem = item._firstChild;
  520. while (subitem) {
  521. if (endsWithBlankLine(subitem) &&
  522. (item._next || subitem._next)) {
  523. block._listData.tight = false;
  524. break;
  525. }
  526. subitem = subitem._next;
  527. }
  528. item = item._next;
  529. }
  530. break;
  531. default:
  532. break;
  533. }
  534. this.tip = above;
  535. };
  536. // Walk through a block & children recursively, parsing string content
  537. // into inline content where appropriate. Returns new object.
  538. var processInlines = function(block) {
  539. var node, event, t;
  540. var walker = block.walker();
  541. while ((event = walker.next())) {
  542. node = event.node;
  543. t = node.type;
  544. if (!event.entering && (t === 'Paragraph' || t === 'Header')) {
  545. this.inlineParser.parse(node, this.refmap);
  546. }
  547. }
  548. };
  549. var Document = function() {
  550. var doc = new Node('Document', [[1, 1], [0, 0]]);
  551. doc._string_content = null;
  552. doc._strings = [];
  553. return doc;
  554. };
  555. // The main parsing function. Returns a parsed document AST.
  556. var parse = function(input) {
  557. this.doc = new Document();
  558. this.tip = this.doc;
  559. this.refmap = {};
  560. if (this.options.time) { console.time("preparing input"); }
  561. var lines = input.split(reLineEnding);
  562. var len = lines.length;
  563. if (input.charCodeAt(input.length - 1) === C_NEWLINE) {
  564. // ignore last blank line created by final newline
  565. len -= 1;
  566. }
  567. if (this.options.time) { console.timeEnd("preparing input"); }
  568. if (this.options.time) { console.time("block parsing"); }
  569. for (var i = 0; i < len; i++) {
  570. this.incorporateLine(lines[i]);
  571. }
  572. while (this.tip) {
  573. this.finalize(this.tip, len);
  574. }
  575. if (this.options.time) { console.timeEnd("block parsing"); }
  576. if (this.options.time) { console.time("inline parsing"); }
  577. this.processInlines(this.doc);
  578. if (this.options.time) { console.timeEnd("inline parsing"); }
  579. return this.doc;
  580. };
  581. // The Parser object.
  582. function Parser(options){
  583. return {
  584. doc: new Document(),
  585. tip: this.doc,
  586. oldtip: this.doc,
  587. lineNumber: 0,
  588. offset: 0,
  589. lastMatchedContainer: this.doc,
  590. refmap: {},
  591. lastLineLength: 0,
  592. inlineParser: new InlineParser(),
  593. breakOutOfLists: breakOutOfLists,
  594. addLine: addLine,
  595. addChild: addChild,
  596. incorporateLine: incorporateLine,
  597. finalize: finalize,
  598. processInlines: processInlines,
  599. closeUnmatchedBlocks: closeUnmatchedBlocks,
  600. parse: parse,
  601. options: options || {}
  602. };
  603. }
  604. module.exports = Parser;