aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: 92d13fdc1169a4b4650dbfb10e5585f3156869a7 (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 match;
  198. var data;
  199. var blank;
  200. var indent;
  201. var i;
  202. var CODE_INDENT = 4;
  203. var allClosed;
  204. var container = this.doc;
  205. this.oldtip = this.tip;
  206. this.offset = 0;
  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, this.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 - this.offset;
  228. switch (container.type) {
  229. case 'BlockQuote':
  230. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  231. this.offset = first_nonspace + 1;
  232. if (ln.charCodeAt(this.offset) === C_SPACE) {
  233. this.offset++;
  234. }
  235. } else {
  236. all_matched = false;
  237. }
  238. break;
  239. case 'Item':
  240. if (blank) {
  241. this.offset = first_nonspace;
  242. } else if (indent >= container._listData.markerOffset +
  243. container._listData.padding) {
  244. this.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. break;
  255. case 'CodeBlock':
  256. if (container._isFenced) { // fenced
  257. match = (indent <= 3 &&
  258. ln.charAt(first_nonspace) === container._fenceChar &&
  259. ln.slice(first_nonspace).match(reClosingCodeFence));
  260. if (match && match[0].length >= container._fenceLength) {
  261. // closing fence - we're at end of line, so we can return
  262. all_matched = false;
  263. this.finalize(container, this.lineNumber);
  264. return;
  265. } else {
  266. // skip optional spaces of fence offset
  267. i = container._fenceOffset;
  268. while (i > 0 && ln.charCodeAt(this.offset) === C_SPACE) {
  269. this.offset++;
  270. i--;
  271. }
  272. }
  273. } else { // indented
  274. if (indent >= CODE_INDENT) {
  275. this.offset += CODE_INDENT;
  276. } else if (blank) {
  277. this.offset = first_nonspace;
  278. } else {
  279. all_matched = false;
  280. }
  281. }
  282. break;
  283. case 'HtmlBlock':
  284. if (blank) {
  285. all_matched = false;
  286. }
  287. break;
  288. case 'Paragraph':
  289. if (blank) {
  290. all_matched = false;
  291. }
  292. break;
  293. default:
  294. }
  295. if (!all_matched) {
  296. container = container._parent; // back up to last matching block
  297. break;
  298. }
  299. }
  300. allClosed = (container === this.oldtip);
  301. this.lastMatchedContainer = container;
  302. // Check to see if we've hit 2nd blank line; if so break out of list:
  303. if (blank && container._lastLineBlank) {
  304. this.breakOutOfLists(container);
  305. }
  306. // Unless last matched container is a code block, try new container starts,
  307. // adding children to the last matched container:
  308. while (true) {
  309. var t = container.type;
  310. match = matchAt(reNonSpace, ln, this.offset);
  311. if (match === -1) {
  312. first_nonspace = ln.length;
  313. blank = true;
  314. break;
  315. } else {
  316. first_nonspace = match;
  317. blank = false;
  318. }
  319. indent = first_nonspace - this.offset;
  320. if (t === 'CodeBlock' || t === 'HtmlBlock') {
  321. break;
  322. }
  323. if (indent >= CODE_INDENT) {
  324. // indented code
  325. if (this.tip.type !== 'Paragraph' && !blank) {
  326. this.offset += CODE_INDENT;
  327. allClosed = allClosed ||
  328. this.closeUnmatchedBlocks();
  329. container = this.addChild('CodeBlock', this.offset);
  330. }
  331. break;
  332. }
  333. // this is a little performance optimization:
  334. if (matchAt(reMaybeSpecial, ln, first_nonspace) === -1) {
  335. break;
  336. }
  337. this.offset = first_nonspace;
  338. var cc = ln.charCodeAt(this.offset);
  339. if (cc === C_GREATERTHAN) {
  340. // blockquote
  341. this.offset += 1;
  342. // optional following space
  343. if (ln.charCodeAt(this.offset) === C_SPACE) {
  344. this.offset++;
  345. }
  346. allClosed = allClosed || this.closeUnmatchedBlocks();
  347. container = this.addChild('BlockQuote', first_nonspace);
  348. } else if ((match = ln.slice(this.offset).match(reATXHeaderMarker))) {
  349. // ATX header
  350. this.offset += match[0].length;
  351. allClosed = allClosed || this.closeUnmatchedBlocks();
  352. container = this.addChild('Header', first_nonspace);
  353. container.level = match[0].trim().length; // number of #s
  354. // remove trailing ###s:
  355. container._strings =
  356. [ln.slice(this.offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/, '')];
  357. break;
  358. } else if ((match = ln.slice(this.offset).match(reCodeFence))) {
  359. // fenced code block
  360. var fenceLength = match[0].length;
  361. allClosed = allClosed || this.closeUnmatchedBlocks();
  362. container = this.addChild('CodeBlock', first_nonspace);
  363. container._isFenced = true;
  364. container._fenceLength = fenceLength;
  365. container._fenceChar = match[0][0];
  366. container._fenceOffset = indent;
  367. this.offset += fenceLength;
  368. } else if (matchAt(reHtmlBlockOpen, ln, this.offset) !== -1) {
  369. // html block
  370. allClosed = allClosed || this.closeUnmatchedBlocks();
  371. container = this.addChild('HtmlBlock', this.offset);
  372. this.offset -= indent; // back up so spaces are part of block
  373. break;
  374. } else if (t === 'Paragraph' &&
  375. container._strings.length === 1 &&
  376. ((match = ln.slice(this.offset).match(reSetextHeaderLine)))) {
  377. // setext header line
  378. allClosed = allClosed || this.closeUnmatchedBlocks();
  379. var header = new Node('Header', container.sourcepos);
  380. header.level = match[0][0] === '=' ? 1 : 2;
  381. header._strings = container._strings;
  382. container.insertAfter(header);
  383. container.unlink();
  384. container = header;
  385. this.tip = header;
  386. this.offset = ln.length;
  387. break;
  388. } else if (matchAt(reHrule, ln, this.offset) !== -1) {
  389. // hrule
  390. allClosed = allClosed || this.closeUnmatchedBlocks();
  391. container = this.addChild('HorizontalRule', first_nonspace);
  392. this.offset = ln.length - 1;
  393. break;
  394. } else if ((data = parseListMarker(ln, this.offset, indent))) {
  395. // list item
  396. allClosed = allClosed || this.closeUnmatchedBlocks();
  397. this.offset += data.padding;
  398. // add the list if needed
  399. if (t !== 'List' ||
  400. !(listsMatch(container._listData, data))) {
  401. container = this.addChild('List', first_nonspace);
  402. container._listData = data;
  403. }
  404. // add the list item
  405. container = this.addChild('Item', first_nonspace);
  406. container._listData = data;
  407. } else {
  408. break;
  409. }
  410. }
  411. // What remains at the offset is a text line. Add the text to the
  412. // appropriate container.
  413. // First check for a lazy paragraph continuation:
  414. if (!allClosed && !blank &&
  415. this.tip.type === 'Paragraph' &&
  416. this.tip._strings.length > 0) {
  417. // lazy paragraph continuation
  418. this._lastLineBlank = false;
  419. this.addLine(ln, this.offset);
  420. } else { // not a lazy continuation
  421. // finalize any blocks not matched
  422. allClosed = allClosed || this.closeUnmatchedBlocks();
  423. t = container.type;
  424. if (blank && container.lastChild) {
  425. container.lastChild._lastLineBlank = true;
  426. }
  427. // Block quote lines are never blank as they start with >
  428. // and we don't count blanks in fenced code for purposes of tight/loose
  429. // lists or breaking out of lists. We also don't set _lastLineBlank
  430. // on an empty list item, or if we just closed a fenced block.
  431. container._lastLineBlank = blank &&
  432. !(t === 'BlockQuote' ||
  433. t === 'Header' ||
  434. (t === 'CodeBlock' && container._isFenced) ||
  435. (t === 'Item' &&
  436. !container._firstChild &&
  437. container.sourcepos[0][0] === this.lineNumber));
  438. var cont = container;
  439. while (cont._parent) {
  440. cont._parent._lastLineBlank = false;
  441. cont = cont._parent;
  442. }
  443. switch (t) {
  444. case 'HtmlBlock':
  445. case 'CodeBlock':
  446. this.addLine(ln, this.offset);
  447. break;
  448. case 'Header':
  449. case 'HorizontalRule':
  450. // nothing to do; we already added the contents.
  451. break;
  452. default:
  453. if (acceptsLines(t)) {
  454. this.addLine(ln, first_nonspace);
  455. } else if (blank) {
  456. break;
  457. } else {
  458. // create paragraph container for line
  459. container = this.addChild('Paragraph', this.lineNumber, first_nonspace);
  460. this.addLine(ln, first_nonspace);
  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 || this.top;
  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.lineNumber += 1;
  576. this.incorporateLine(lines[i]);
  577. }
  578. while (this.tip) {
  579. this.finalize(this.tip, len);
  580. }
  581. if (this.options.time) { console.timeEnd("block parsing"); }
  582. if (this.options.time) { console.time("inline parsing"); }
  583. this.processInlines(this.doc);
  584. if (this.options.time) { console.timeEnd("inline parsing"); }
  585. return this.doc;
  586. };
  587. // The DocParser object.
  588. function DocParser(options){
  589. return {
  590. doc: new Document(),
  591. tip: this.doc,
  592. oldtip: this.doc,
  593. lineNumber: 0,
  594. offset: 0,
  595. lastMatchedContainer: this.doc,
  596. refmap: {},
  597. lastLineLength: 0,
  598. inlineParser: new InlineParser(),
  599. breakOutOfLists: breakOutOfLists,
  600. addLine: addLine,
  601. addChild: addChild,
  602. incorporateLine: incorporateLine,
  603. finalize: finalize,
  604. processInlines: processInlines,
  605. closeUnmatchedBlocks: closeUnmatchedBlocks,
  606. parse: parse,
  607. options: options || {}
  608. };
  609. }
  610. module.exports = DocParser;