aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: 279fa5476c995f744fabc8196bcafa67062f06b1 (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, offset) {
  115. this.tip._strings.push(ln.slice(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 offset;
  202. var container = this.doc;
  203. this.oldtip = this.tip;
  204. offset = 0;
  205. this.lineNumber += 1;
  206. // replace NUL characters for security
  207. if (ln.indexOf('\u0000') !== -1) {
  208. ln = ln.replace(/\0/g, '\uFFFD');
  209. }
  210. // Convert tabs to spaces:
  211. ln = detabLine(ln);
  212. // For each containing block, try to parse the associated line start.
  213. // Bail out on failure: container will point to the last matching block.
  214. // Set all_matched to false if not all containers match.
  215. var lastChild;
  216. while ((lastChild = container._lastChild) && lastChild._open) {
  217. container = lastChild;
  218. match = matchAt(reNonSpace, ln, offset);
  219. if (match === -1) {
  220. first_nonspace = ln.length;
  221. blank = true;
  222. } else {
  223. first_nonspace = match;
  224. blank = false;
  225. }
  226. indent = first_nonspace - offset;
  227. switch (container.type) {
  228. case 'BlockQuote':
  229. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  230. offset = first_nonspace + 1;
  231. if (ln.charCodeAt(offset) === C_SPACE) {
  232. offset++;
  233. }
  234. } else {
  235. all_matched = false;
  236. }
  237. break;
  238. case 'Item':
  239. if (blank) {
  240. offset = first_nonspace;
  241. } else if (indent >= container._listData.markerOffset +
  242. container._listData.padding) {
  243. offset += container._listData.markerOffset +
  244. container._listData.padding;
  245. } else {
  246. all_matched = false;
  247. }
  248. break;
  249. case 'Header':
  250. case 'HorizontalRule':
  251. // a header can never container > 1 line, so fail to match:
  252. all_matched = false;
  253. break;
  254. case 'CodeBlock':
  255. if (container._isFenced) { // fenced
  256. match = (indent <= 3 &&
  257. ln.charAt(first_nonspace) === container._fenceChar &&
  258. ln.slice(first_nonspace).match(reClosingCodeFence));
  259. if (match && match[0].length >= container._fenceLength) {
  260. // closing fence - we're at end of line, so we can return
  261. all_matched = false;
  262. this.finalize(container, this.lineNumber);
  263. return;
  264. } else {
  265. // skip optional spaces of fence offset
  266. i = container._fenceOffset;
  267. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  268. offset++;
  269. i--;
  270. }
  271. }
  272. } else { // indented
  273. if (indent >= CODE_INDENT) {
  274. offset += CODE_INDENT;
  275. } else if (blank) {
  276. 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, 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 - 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. offset += CODE_INDENT;
  326. allClosed = allClosed ||
  327. this.closeUnmatchedBlocks();
  328. container = this.addChild('CodeBlock', offset);
  329. }
  330. break;
  331. }
  332. // this is a little performance optimization:
  333. if (matchAt(reMaybeSpecial, ln, first_nonspace) === -1) {
  334. break;
  335. }
  336. offset = first_nonspace;
  337. var cc = ln.charCodeAt(offset);
  338. if (cc === C_GREATERTHAN) {
  339. // blockquote
  340. offset += 1;
  341. // optional following space
  342. if (ln.charCodeAt(offset) === C_SPACE) {
  343. offset++;
  344. }
  345. allClosed = allClosed || this.closeUnmatchedBlocks();
  346. container = this.addChild('BlockQuote', first_nonspace);
  347. } else if ((match = ln.slice(offset).match(reATXHeaderMarker))) {
  348. // ATX header
  349. 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(offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/, '')];
  356. break;
  357. } else if ((match = ln.slice(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. offset += fenceLength;
  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. // 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._lastLineBlank = false;
  418. this.addLine(ln, offset);
  419. } else { // not a lazy continuation
  420. // finalize any blocks not matched
  421. allClosed = allClosed || this.closeUnmatchedBlocks();
  422. t = container.type;
  423. if (blank && container.lastChild) {
  424. container.lastChild._lastLineBlank = true;
  425. }
  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, or if we just closed a fenced block.
  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. case 'CodeBlock':
  445. this.addLine(ln, offset);
  446. break;
  447. case 'Header':
  448. case 'HorizontalRule':
  449. // nothing to do; we already added the contents.
  450. break;
  451. default:
  452. offset = first_nonspace;
  453. if (acceptsLines(t)) {
  454. this.addLine(ln, offset);
  455. } else if (blank) {
  456. break;
  457. } else {
  458. // create paragraph container for line
  459. container = this.addChild('Paragraph', this.lineNumber, offset);
  460. this.addLine(ln, offset);
  461. }
  462. }
  463. }
  464. this.lastLineLength = ln.length - 1; // -1 for newline
  465. };
  466. // Finalize a block. Close it and do any necessary postprocessing,
  467. // e.g. creating string_content from strings, setting the 'tight'
  468. // or 'loose' status of a list, and parsing the beginnings
  469. // of paragraphs for reference definitions. Reset the tip to the
  470. // parent of the closed block.
  471. var finalize = function(block, lineNumber) {
  472. var pos;
  473. var above = block._parent;
  474. // don't do anything if the block is already closed
  475. if (!block._open) {
  476. return 0;
  477. }
  478. block._open = false;
  479. block.sourcepos[1] = [lineNumber, this.lastLineLength + 1];
  480. switch (block.type) {
  481. case 'Paragraph':
  482. block._string_content = block._strings.join('\n');
  483. // try parsing the beginning as link reference definitions:
  484. while (block._string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  485. (pos = this.inlineParser.parseReference(block._string_content,
  486. this.refmap))) {
  487. block._string_content = block._string_content.slice(pos);
  488. if (isBlank(block._string_content)) {
  489. block.unlink();
  490. break;
  491. }
  492. }
  493. break;
  494. case 'Header':
  495. block._string_content = block._strings.join('\n');
  496. break;
  497. case 'HtmlBlock':
  498. block._literal = block._strings.join('\n');
  499. break;
  500. case 'CodeBlock':
  501. if (block._isFenced) { // fenced
  502. // first line becomes info string
  503. block.info = unescapeString(block._strings[0].trim());
  504. if (block._strings.length === 1) {
  505. block._literal = '';
  506. } else {
  507. block._literal = block._strings.slice(1).join('\n') + '\n';
  508. }
  509. } else { // indented
  510. stripFinalBlankLines(block._strings);
  511. block._literal = block._strings.join('\n') + '\n';
  512. }
  513. break;
  514. case 'List':
  515. var item = block._firstChild;
  516. while (item) {
  517. // check for non-final list item ending with blank line:
  518. if (endsWithBlankLine(item) && item._next) {
  519. block._listData.tight = false;
  520. break;
  521. }
  522. // recurse into children of list item, to see if there are
  523. // spaces between any of them:
  524. var subitem = item._firstChild;
  525. while (subitem) {
  526. if (endsWithBlankLine(subitem) &&
  527. (item._next || subitem._next)) {
  528. block._listData.tight = false;
  529. break;
  530. }
  531. subitem = subitem._next;
  532. }
  533. item = item._next;
  534. }
  535. break;
  536. default:
  537. break;
  538. }
  539. this.tip = above;
  540. };
  541. // Walk through a block & children recursively, parsing string content
  542. // into inline content where appropriate. Returns new object.
  543. var processInlines = function(block) {
  544. var node, event, t;
  545. var walker = block.walker();
  546. while ((event = walker.next())) {
  547. node = event.node;
  548. t = node.type;
  549. if (!event.entering && (t === 'Paragraph' || t === 'Header')) {
  550. this.inlineParser.parse(node, this.refmap);
  551. }
  552. }
  553. };
  554. var Document = function() {
  555. var doc = new Node('Document', [[1, 1], [0, 0]]);
  556. doc._string_content = null;
  557. doc._strings = [];
  558. return doc;
  559. };
  560. // The main parsing function. Returns a parsed document AST.
  561. var parse = function(input) {
  562. this.doc = new Document();
  563. this.tip = this.doc;
  564. this.refmap = {};
  565. if (this.options.time) { console.time("preparing input"); }
  566. var lines = input.split(reLineEnding);
  567. var len = lines.length;
  568. if (input.charCodeAt(input.length - 1) === C_NEWLINE) {
  569. // ignore last blank line created by final newline
  570. len -= 1;
  571. }
  572. if (this.options.time) { console.timeEnd("preparing input"); }
  573. if (this.options.time) { console.time("block parsing"); }
  574. for (var i = 0; i < len; i++) {
  575. this.incorporateLine(lines[i]);
  576. }
  577. while (this.tip) {
  578. this.finalize(this.tip, len);
  579. }
  580. if (this.options.time) { console.timeEnd("block parsing"); }
  581. if (this.options.time) { console.time("inline parsing"); }
  582. this.processInlines(this.doc);
  583. if (this.options.time) { console.timeEnd("inline parsing"); }
  584. return this.doc;
  585. };
  586. // The Parser object.
  587. function Parser(options){
  588. return {
  589. doc: new Document(),
  590. tip: this.doc,
  591. oldtip: this.doc,
  592. lineNumber: 0,
  593. lastMatchedContainer: this.doc,
  594. refmap: {},
  595. lastLineLength: 0,
  596. inlineParser: new InlineParser(),
  597. breakOutOfLists: breakOutOfLists,
  598. addLine: addLine,
  599. addChild: addChild,
  600. incorporateLine: incorporateLine,
  601. finalize: finalize,
  602. processInlines: processInlines,
  603. closeUnmatchedBlocks: closeUnmatchedBlocks,
  604. parse: parse,
  605. options: options || {}
  606. };
  607. }
  608. module.exports = Parser;