aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: 791b74f21f04e7368ac5c51c6d07117d8106aefc (plain)
  1. var C_GREATERTHAN = 62;
  2. var C_SPACE = 32;
  3. var C_OPEN_BRACKET = 91;
  4. var InlineParser = require('./inlines');
  5. var unescapeString = new InlineParser().unescapeString;
  6. // Returns true if string contains only space characters.
  7. var isBlank = function(s) {
  8. return /^\s*$/.test(s);
  9. };
  10. // Convert tabs to spaces on each line using a 4-space tab stop.
  11. var detabLine = function(text) {
  12. if (text.indexOf('\t') == -1) {
  13. return text;
  14. } else {
  15. var lastStop = 0;
  16. return text.replace(/\t/g, function(match, offset) {
  17. var result = ' '.slice((offset - lastStop) % 4);
  18. lastStop = offset + 1;
  19. return result;
  20. });
  21. }
  22. };
  23. // Attempt to match a regex in string s at offset offset.
  24. // Return index of match or -1.
  25. var matchAt = function(re, s, offset) {
  26. var res = s.slice(offset).match(re);
  27. if (res) {
  28. return offset + res.index;
  29. } else {
  30. return -1;
  31. }
  32. };
  33. 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)';
  34. var HTMLBLOCKOPEN = "<(?:" + BLOCKTAGNAME + "[\\s/>]" + "|" +
  35. "/" + BLOCKTAGNAME + "[\\s>]" + "|" + "[?!])";
  36. var reHtmlBlockOpen = new RegExp('^' + HTMLBLOCKOPEN, 'i');
  37. var reHrule = /^(?:(?:\* *){3,}|(?:_ *){3,}|(?:- *){3,}) *$/;
  38. // DOC PARSER
  39. // These are methods of a DocParser object, defined below.
  40. var makeBlock = function(tag, start_line, start_column) {
  41. return { t: tag,
  42. open: true,
  43. last_line_blank: false,
  44. start_line: start_line,
  45. start_column: start_column,
  46. end_line: start_line,
  47. children: [],
  48. parent: null,
  49. // string_content is formed by concatenating strings, in finalize:
  50. string_content: "",
  51. strings: [],
  52. inline_content: []
  53. };
  54. };
  55. // Returns true if parent block can contain child block.
  56. var canContain = function(parent_type, child_type) {
  57. return ( parent_type == 'Document' ||
  58. parent_type == 'BlockQuote' ||
  59. parent_type == 'ListItem' ||
  60. (parent_type == 'List' && child_type == 'ListItem') );
  61. };
  62. // Returns true if block type can accept lines of text.
  63. var acceptsLines = function(block_type) {
  64. return ( block_type == 'Paragraph' ||
  65. block_type == 'IndentedCode' ||
  66. block_type == 'FencedCode' );
  67. };
  68. // Returns true if block ends with a blank line, descending if needed
  69. // into lists and sublists.
  70. var endsWithBlankLine = function(block) {
  71. if (block.last_line_blank) {
  72. return true;
  73. }
  74. if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) {
  75. return endsWithBlankLine(block.children[block.children.length - 1]);
  76. } else {
  77. return false;
  78. }
  79. };
  80. // Break out of all containing lists, resetting the tip of the
  81. // document to the parent of the highest list, and finalizing
  82. // all the lists. (This is used to implement the "two blank lines
  83. // break of of all lists" feature.)
  84. var breakOutOfLists = function(block, line_number) {
  85. var b = block;
  86. var last_list = null;
  87. do {
  88. if (b.t === 'List') {
  89. last_list = b;
  90. }
  91. b = b.parent;
  92. } while (b);
  93. if (last_list) {
  94. while (block != last_list) {
  95. this.finalize(block, line_number);
  96. block = block.parent;
  97. }
  98. this.finalize(last_list, line_number);
  99. this.tip = last_list.parent;
  100. }
  101. };
  102. // Add a line to the block at the tip. We assume the tip
  103. // can accept lines -- that check should be done before calling this.
  104. var addLine = function(ln, offset) {
  105. var s = ln.slice(offset);
  106. if (!(this.tip.open)) {
  107. throw({ msg: "Attempted to add line (" + ln + ") to closed container." });
  108. }
  109. this.tip.strings.push(s);
  110. };
  111. // Add block of type tag as a child of the tip. If the tip can't
  112. // accept children, close and finalize it and try its parent,
  113. // and so on til we find a block that can accept children.
  114. var addChild = function(tag, line_number, offset) {
  115. while (!canContain(this.tip.t, tag)) {
  116. this.finalize(this.tip, line_number);
  117. }
  118. var column_number = offset + 1; // offset 0 = column 1
  119. var newBlock = makeBlock(tag, line_number, column_number);
  120. this.tip.children.push(newBlock);
  121. newBlock.parent = this.tip;
  122. this.tip = newBlock;
  123. return newBlock;
  124. };
  125. // Parse a list marker and return data on the marker (type,
  126. // start, delimiter, bullet character, padding) or null.
  127. var parseListMarker = function(ln, offset) {
  128. var rest = ln.slice(offset);
  129. var match;
  130. var spaces_after_marker;
  131. var data = {};
  132. if (rest.match(reHrule)) {
  133. return null;
  134. }
  135. if ((match = rest.match(/^[*+-]( +|$)/))) {
  136. spaces_after_marker = match[1].length;
  137. data.type = 'Bullet';
  138. data.bullet_char = match[0][0];
  139. } else if ((match = rest.match(/^(\d+)([.)])( +|$)/))) {
  140. spaces_after_marker = match[3].length;
  141. data.type = 'Ordered';
  142. data.start = parseInt(match[1]);
  143. data.delimiter = match[2];
  144. } else {
  145. return null;
  146. }
  147. var blank_item = match[0].length === rest.length;
  148. if (spaces_after_marker >= 5 ||
  149. spaces_after_marker < 1 ||
  150. blank_item) {
  151. data.padding = match[0].length - spaces_after_marker + 1;
  152. } else {
  153. data.padding = match[0].length;
  154. }
  155. return data;
  156. };
  157. // Returns true if the two list items are of the same type,
  158. // with the same delimiter and bullet character. This is used
  159. // in agglomerating list items into lists.
  160. var listsMatch = function(list_data, item_data) {
  161. return (list_data.type === item_data.type &&
  162. list_data.delimiter === item_data.delimiter &&
  163. list_data.bullet_char === item_data.bullet_char);
  164. };
  165. // Analyze a line of text and update the document appropriately.
  166. // We parse markdown text by calling this on each line of input,
  167. // then finalizing the document.
  168. var incorporateLine = function(ln, line_number) {
  169. var all_matched = true;
  170. var last_child;
  171. var first_nonspace;
  172. var offset = 0;
  173. var match;
  174. var data;
  175. var blank;
  176. var indent;
  177. var last_matched_container;
  178. var i;
  179. var CODE_INDENT = 4;
  180. var container = this.doc;
  181. var oldtip = this.tip;
  182. // Convert tabs to spaces:
  183. ln = detabLine(ln);
  184. // For each containing block, try to parse the associated line start.
  185. // Bail out on failure: container will point to the last matching block.
  186. // Set all_matched to false if not all containers match.
  187. while (container.children.length > 0) {
  188. last_child = container.children[container.children.length - 1];
  189. if (!last_child.open) {
  190. break;
  191. }
  192. container = last_child;
  193. match = matchAt(/[^ ]/, ln, offset);
  194. if (match === -1) {
  195. first_nonspace = ln.length;
  196. blank = true;
  197. } else {
  198. first_nonspace = match;
  199. blank = false;
  200. }
  201. indent = first_nonspace - offset;
  202. switch (container.t) {
  203. case 'BlockQuote':
  204. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  205. offset = first_nonspace + 1;
  206. if (ln.charCodeAt(offset) === C_SPACE) {
  207. offset++;
  208. }
  209. } else {
  210. all_matched = false;
  211. }
  212. break;
  213. case 'ListItem':
  214. if (indent >= container.list_data.marker_offset +
  215. container.list_data.padding) {
  216. offset += container.list_data.marker_offset +
  217. container.list_data.padding;
  218. } else if (blank) {
  219. offset = first_nonspace;
  220. } else {
  221. all_matched = false;
  222. }
  223. break;
  224. case 'IndentedCode':
  225. if (indent >= CODE_INDENT) {
  226. offset += CODE_INDENT;
  227. } else if (blank) {
  228. offset = first_nonspace;
  229. } else {
  230. all_matched = false;
  231. }
  232. break;
  233. case 'ATXHeader':
  234. case 'SetextHeader':
  235. case 'HorizontalRule':
  236. // a header can never container > 1 line, so fail to match:
  237. all_matched = false;
  238. break;
  239. case 'FencedCode':
  240. // skip optional spaces of fence offset
  241. i = container.fence_offset;
  242. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  243. offset++;
  244. i--;
  245. }
  246. break;
  247. case 'HtmlBlock':
  248. if (blank) {
  249. all_matched = false;
  250. }
  251. break;
  252. case 'Paragraph':
  253. if (blank) {
  254. container.last_line_blank = true;
  255. all_matched = false;
  256. }
  257. break;
  258. default:
  259. }
  260. if (!all_matched) {
  261. container = container.parent; // back up to last matching block
  262. break;
  263. }
  264. }
  265. last_matched_container = container;
  266. // This function is used to finalize and close any unmatched
  267. // blocks. We aren't ready to do this now, because we might
  268. // have a lazy paragraph continuation, in which case we don't
  269. // want to close unmatched blocks. So we store this closure for
  270. // use later, when we have more information.
  271. var closeUnmatchedBlocks = function(mythis) {
  272. // finalize any blocks not matched
  273. while (!already_done && oldtip != last_matched_container) {
  274. mythis.finalize(oldtip, line_number);
  275. oldtip = oldtip.parent;
  276. }
  277. var already_done = true;
  278. };
  279. // Check to see if we've hit 2nd blank line; if so break out of list:
  280. if (blank && container.last_line_blank) {
  281. this.breakOutOfLists(container, line_number);
  282. }
  283. // Unless last matched container is a code block, try new container starts,
  284. // adding children to the last matched container:
  285. while (container.t != 'FencedCode' &&
  286. container.t != 'IndentedCode' &&
  287. container.t != 'HtmlBlock' &&
  288. // this is a little performance optimization:
  289. matchAt(/^[ #`~*+_=<>0-9-]/,ln,offset) !== -1) {
  290. match = matchAt(/[^ ]/, ln, offset);
  291. if (match === -1) {
  292. first_nonspace = ln.length;
  293. blank = true;
  294. } else {
  295. first_nonspace = match;
  296. blank = false;
  297. }
  298. indent = first_nonspace - offset;
  299. if (indent >= CODE_INDENT) {
  300. // indented code
  301. if (this.tip.t != 'Paragraph' && !blank) {
  302. offset += CODE_INDENT;
  303. closeUnmatchedBlocks(this);
  304. container = this.addChild('IndentedCode', line_number, offset);
  305. } else { // indent > 4 in a lazy paragraph continuation
  306. break;
  307. }
  308. } else if (ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  309. // blockquote
  310. offset = first_nonspace + 1;
  311. // optional following space
  312. if (ln.charCodeAt(offset) === C_SPACE) {
  313. offset++;
  314. }
  315. closeUnmatchedBlocks(this);
  316. container = this.addChild('BlockQuote', line_number, offset);
  317. } else if ((match = ln.slice(first_nonspace).match(/^#{1,6}(?: +|$)/))) {
  318. // ATX header
  319. offset = first_nonspace + match[0].length;
  320. closeUnmatchedBlocks(this);
  321. container = this.addChild('ATXHeader', line_number, first_nonspace);
  322. container.level = match[0].trim().length; // number of #s
  323. // remove trailing ###s:
  324. container.strings =
  325. [ln.slice(offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/,'')];
  326. break;
  327. } else if ((match = ln.slice(first_nonspace).match(/^`{3,}(?!.*`)|^~{3,}(?!.*~)/))) {
  328. // fenced code block
  329. var fence_length = match[0].length;
  330. closeUnmatchedBlocks(this);
  331. container = this.addChild('FencedCode', line_number, first_nonspace);
  332. container.fence_length = fence_length;
  333. container.fence_char = match[0][0];
  334. container.fence_offset = first_nonspace - offset;
  335. offset = first_nonspace + fence_length;
  336. break;
  337. } else if (matchAt(reHtmlBlockOpen, ln, first_nonspace) !== -1) {
  338. // html block
  339. closeUnmatchedBlocks(this);
  340. container = this.addChild('HtmlBlock', line_number, first_nonspace);
  341. // note, we don't adjust offset because the tag is part of the text
  342. break;
  343. } else if (container.t == 'Paragraph' &&
  344. container.strings.length === 1 &&
  345. ((match = ln.slice(first_nonspace).match(/^(?:=+|-+) *$/)))) {
  346. // setext header line
  347. closeUnmatchedBlocks(this);
  348. container.t = 'SetextHeader'; // convert Paragraph to SetextHeader
  349. container.level = match[0][0] === '=' ? 1 : 2;
  350. offset = ln.length;
  351. } else if (matchAt(reHrule, ln, first_nonspace) !== -1) {
  352. // hrule
  353. closeUnmatchedBlocks(this);
  354. container = this.addChild('HorizontalRule', line_number, first_nonspace);
  355. offset = ln.length - 1;
  356. break;
  357. } else if ((data = parseListMarker(ln, first_nonspace))) {
  358. // list item
  359. closeUnmatchedBlocks(this);
  360. data.marker_offset = indent;
  361. offset = first_nonspace + data.padding;
  362. // add the list if needed
  363. if (container.t !== 'List' ||
  364. !(listsMatch(container.list_data, data))) {
  365. container = this.addChild('List', line_number, first_nonspace);
  366. container.list_data = data;
  367. }
  368. // add the list item
  369. container = this.addChild('ListItem', line_number, first_nonspace);
  370. container.list_data = data;
  371. } else {
  372. break;
  373. }
  374. if (acceptsLines(container.t)) {
  375. // if it's a line container, it can't contain other containers
  376. break;
  377. }
  378. }
  379. // What remains at the offset is a text line. Add the text to the
  380. // appropriate container.
  381. match = matchAt(/[^ ]/, ln, offset);
  382. if (match === -1) {
  383. first_nonspace = ln.length;
  384. blank = true;
  385. } else {
  386. first_nonspace = match;
  387. blank = false;
  388. }
  389. indent = first_nonspace - offset;
  390. // First check for a lazy paragraph continuation:
  391. if (this.tip !== last_matched_container &&
  392. !blank &&
  393. this.tip.t == 'Paragraph' &&
  394. this.tip.strings.length > 0) {
  395. // lazy paragraph continuation
  396. this.last_line_blank = false;
  397. this.addLine(ln, offset);
  398. } else { // not a lazy continuation
  399. // finalize any blocks not matched
  400. closeUnmatchedBlocks(this);
  401. // Block quote lines are never blank as they start with >
  402. // and we don't count blanks in fenced code for purposes of tight/loose
  403. // lists or breaking out of lists. We also don't set last_line_blank
  404. // on an empty list item.
  405. container.last_line_blank = blank &&
  406. !(container.t == 'BlockQuote' ||
  407. container.t == 'FencedCode' ||
  408. (container.t == 'ListItem' &&
  409. container.children.length === 0 &&
  410. container.start_line == line_number));
  411. var cont = container;
  412. while (cont.parent) {
  413. cont.parent.last_line_blank = false;
  414. cont = cont.parent;
  415. }
  416. switch (container.t) {
  417. case 'IndentedCode':
  418. case 'HtmlBlock':
  419. this.addLine(ln, offset);
  420. break;
  421. case 'FencedCode':
  422. // check for closing code fence:
  423. match = (indent <= 3 &&
  424. ln.charAt(first_nonspace) == container.fence_char &&
  425. ln.slice(first_nonspace).match(/^(?:`{3,}|~{3,})(?= *$)/));
  426. if (match && match[0].length >= container.fence_length) {
  427. // don't add closing fence to container; instead, close it:
  428. this.finalize(container, line_number);
  429. } else {
  430. this.addLine(ln, offset);
  431. }
  432. break;
  433. case 'ATXHeader':
  434. case 'SetextHeader':
  435. case 'HorizontalRule':
  436. // nothing to do; we already added the contents.
  437. break;
  438. default:
  439. if (acceptsLines(container.t)) {
  440. this.addLine(ln, first_nonspace);
  441. } else if (blank) {
  442. // do nothing
  443. } else if (container.t != 'HorizontalRule' &&
  444. container.t != 'SetextHeader') {
  445. // create paragraph container for line
  446. container = this.addChild('Paragraph', line_number, first_nonspace);
  447. this.addLine(ln, first_nonspace);
  448. } else {
  449. console.log("Line " + line_number.toString() +
  450. " with container type " + container.t +
  451. " did not match any condition.");
  452. }
  453. }
  454. }
  455. };
  456. // Finalize a block. Close it and do any necessary postprocessing,
  457. // e.g. creating string_content from strings, setting the 'tight'
  458. // or 'loose' status of a list, and parsing the beginnings
  459. // of paragraphs for reference definitions. Reset the tip to the
  460. // parent of the closed block.
  461. var finalize = function(block, line_number) {
  462. var pos;
  463. // don't do anything if the block is already closed
  464. if (!block.open) {
  465. return 0;
  466. }
  467. block.open = false;
  468. if (line_number > block.start_line) {
  469. block.end_line = line_number - 1;
  470. } else {
  471. block.end_line = line_number;
  472. }
  473. switch (block.t) {
  474. case 'Paragraph':
  475. block.string_content = block.strings.join('\n').replace(/^ */m,'');
  476. // delete block.strings;
  477. // try parsing the beginning as link reference definitions:
  478. while (block.string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  479. (pos = this.inlineParser.parseReference(block.string_content,
  480. this.refmap))) {
  481. block.string_content = block.string_content.slice(pos);
  482. if (isBlank(block.string_content)) {
  483. block.t = 'ReferenceDef';
  484. break;
  485. }
  486. }
  487. break;
  488. case 'ATXHeader':
  489. case 'SetextHeader':
  490. case 'HtmlBlock':
  491. block.string_content = block.strings.join('\n');
  492. break;
  493. case 'IndentedCode':
  494. block.string_content = block.strings.join('\n').replace(/(\n *)*$/,'\n');
  495. break;
  496. case 'FencedCode':
  497. // first line becomes info string
  498. block.info = unescapeString(block.strings[0].trim());
  499. if (block.strings.length == 1) {
  500. block.string_content = '';
  501. } else {
  502. block.string_content = block.strings.slice(1).join('\n') + '\n';
  503. }
  504. break;
  505. case 'List':
  506. block.tight = true; // tight by default
  507. var numitems = block.children.length;
  508. var i = 0;
  509. while (i < numitems) {
  510. var item = block.children[i];
  511. // check for non-final list item ending with blank line:
  512. var last_item = i == numitems - 1;
  513. if (endsWithBlankLine(item) && !last_item) {
  514. block.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 numsubitems = item.children.length;
  520. var j = 0;
  521. while (j < numsubitems) {
  522. var subitem = item.children[j];
  523. var last_subitem = j == numsubitems - 1;
  524. if (endsWithBlankLine(subitem) && !(last_item && last_subitem)) {
  525. block.tight = false;
  526. break;
  527. }
  528. j++;
  529. }
  530. i++;
  531. }
  532. break;
  533. default:
  534. break;
  535. }
  536. this.tip = block.parent || this.top;
  537. };
  538. // Walk through a block & children recursively, parsing string content
  539. // into inline content where appropriate. Returns new object.
  540. var processInlines = function(block) {
  541. var newblock = {};
  542. newblock.t = block.t;
  543. newblock.start_line = block.start_line;
  544. newblock.start_column = block.start_column;
  545. newblock.end_line = block.end_line;
  546. switch(block.t) {
  547. case 'Paragraph':
  548. newblock.inline_content =
  549. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  550. break;
  551. case 'SetextHeader':
  552. case 'ATXHeader':
  553. newblock.inline_content =
  554. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  555. newblock.level = block.level;
  556. break;
  557. case 'List':
  558. newblock.list_data = block.list_data;
  559. newblock.tight = block.tight;
  560. break;
  561. case 'FencedCode':
  562. newblock.string_content = block.string_content;
  563. newblock.info = block.info;
  564. break;
  565. case 'IndentedCode':
  566. case 'HtmlBlock':
  567. newblock.string_content = block.string_content;
  568. break;
  569. default:
  570. break;
  571. }
  572. if (block.children) {
  573. var newchildren = [];
  574. for (var i = 0; i < block.children.length; i++) {
  575. newchildren.push(this.processInlines(block.children[i]));
  576. }
  577. newblock.children = newchildren;
  578. }
  579. return newblock;
  580. };
  581. // The main parsing function. Returns a parsed document AST.
  582. var parse = function(input) {
  583. this.doc = makeBlock('Document', 1, 1);
  584. this.tip = this.doc;
  585. this.refmap = {};
  586. var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/);
  587. var len = lines.length;
  588. for (var i = 0; i < len; i++) {
  589. this.incorporateLine(lines[i], i+1);
  590. }
  591. while (this.tip) {
  592. this.finalize(this.tip, len - 1);
  593. }
  594. return this.processInlines(this.doc);
  595. };
  596. // The DocParser object.
  597. function DocParser(){
  598. return {
  599. doc: makeBlock('Document', 1, 1),
  600. tip: this.doc,
  601. refmap: {},
  602. inlineParser: new InlineParser(),
  603. breakOutOfLists: breakOutOfLists,
  604. addLine: addLine,
  605. addChild: addChild,
  606. incorporateLine: incorporateLine,
  607. finalize: finalize,
  608. processInlines: processInlines,
  609. parse: parse
  610. };
  611. }
  612. module.exports = DocParser;