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