aboutsummaryrefslogtreecommitdiff
path: root/js/lib/blocks.js
blob: cd42090bbb619a82925d84c7958bf3158198f99e (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 'Header':
  234. case 'HorizontalRule':
  235. // a header can never container > 1 line, so fail to match:
  236. all_matched = false;
  237. if (blank) {
  238. container.last_line_blank = true;
  239. }
  240. break;
  241. case 'FencedCode':
  242. // skip optional spaces of fence offset
  243. i = container.fence_offset;
  244. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  245. offset++;
  246. i--;
  247. }
  248. break;
  249. case 'HtmlBlock':
  250. if (blank) {
  251. container.last_line_blank = true;
  252. all_matched = false;
  253. }
  254. break;
  255. case 'Paragraph':
  256. if (blank) {
  257. container.last_line_blank = true;
  258. all_matched = false;
  259. }
  260. break;
  261. default:
  262. }
  263. if (!all_matched) {
  264. container = container.parent; // back up to last matching block
  265. break;
  266. }
  267. }
  268. last_matched_container = container;
  269. // This function is used to finalize and close any unmatched
  270. // blocks. We aren't ready to do this now, because we might
  271. // have a lazy paragraph continuation, in which case we don't
  272. // want to close unmatched blocks. So we store this closure for
  273. // use later, when we have more information.
  274. var closeUnmatchedBlocks = function(mythis) {
  275. // finalize any blocks not matched
  276. while (!already_done && oldtip != last_matched_container) {
  277. mythis.finalize(oldtip, line_number);
  278. oldtip = oldtip.parent;
  279. }
  280. var already_done = true;
  281. };
  282. // Check to see if we've hit 2nd blank line; if so break out of list:
  283. if (blank && container.last_line_blank) {
  284. this.breakOutOfLists(container, line_number);
  285. }
  286. // Unless last matched container is a code block, try new container starts,
  287. // adding children to the last matched container:
  288. while (container.t != 'FencedCode' &&
  289. container.t != 'IndentedCode' &&
  290. container.t != 'HtmlBlock' &&
  291. // this is a little performance optimization:
  292. matchAt(/^[ #`~*+_=<>0-9-]/,ln,offset) !== -1) {
  293. match = matchAt(/[^ ]/, ln, offset);
  294. if (match === -1) {
  295. first_nonspace = ln.length;
  296. blank = true;
  297. } else {
  298. first_nonspace = match;
  299. blank = false;
  300. }
  301. indent = first_nonspace - offset;
  302. if (indent >= CODE_INDENT) {
  303. // indented code
  304. if (this.tip.t != 'Paragraph' && !blank) {
  305. offset += CODE_INDENT;
  306. closeUnmatchedBlocks(this);
  307. container = this.addChild('IndentedCode', line_number, offset);
  308. } else { // indent > 4 in a lazy paragraph continuation
  309. break;
  310. }
  311. } else if (ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  312. // blockquote
  313. offset = first_nonspace + 1;
  314. // optional following space
  315. if (ln.charCodeAt(offset) === C_SPACE) {
  316. offset++;
  317. }
  318. closeUnmatchedBlocks(this);
  319. container = this.addChild('BlockQuote', line_number, offset);
  320. } else if ((match = ln.slice(first_nonspace).match(/^#{1,6}(?: +|$)/))) {
  321. // ATX header
  322. offset = first_nonspace + match[0].length;
  323. closeUnmatchedBlocks(this);
  324. container = this.addChild('Header', line_number, first_nonspace);
  325. container.level = match[0].trim().length; // number of #s
  326. // remove trailing ###s:
  327. container.strings =
  328. [ln.slice(offset).replace(/^ *#+ *$/, '').replace(/ +#+ *$/,'')];
  329. break;
  330. } else if ((match = ln.slice(first_nonspace).match(/^`{3,}(?!.*`)|^~{3,}(?!.*~)/))) {
  331. // fenced code block
  332. var fence_length = match[0].length;
  333. closeUnmatchedBlocks(this);
  334. container = this.addChild('FencedCode', line_number, first_nonspace);
  335. container.fence_length = fence_length;
  336. container.fence_char = match[0][0];
  337. container.fence_offset = first_nonspace - offset;
  338. offset = first_nonspace + fence_length;
  339. break;
  340. } else if (matchAt(reHtmlBlockOpen, ln, first_nonspace) !== -1) {
  341. // html block
  342. closeUnmatchedBlocks(this);
  343. container = this.addChild('HtmlBlock', line_number, first_nonspace);
  344. // note, we don't adjust offset because the tag is part of the text
  345. break;
  346. } else if (container.t == 'Paragraph' &&
  347. container.strings.length === 1 &&
  348. ((match = ln.slice(first_nonspace).match(/^(?:=+|-+) *$/)))) {
  349. // setext header line
  350. closeUnmatchedBlocks(this);
  351. container.t = 'Header'; // convert Paragraph to SetextHeader
  352. container.level = match[0][0] === '=' ? 1 : 2;
  353. offset = ln.length;
  354. } else if (matchAt(reHrule, ln, first_nonspace) !== -1) {
  355. // hrule
  356. closeUnmatchedBlocks(this);
  357. container = this.addChild('HorizontalRule', line_number, first_nonspace);
  358. offset = ln.length - 1;
  359. break;
  360. } else if ((data = parseListMarker(ln, first_nonspace))) {
  361. // list item
  362. closeUnmatchedBlocks(this);
  363. data.marker_offset = indent;
  364. offset = first_nonspace + data.padding;
  365. // add the list if needed
  366. if (container.t !== 'List' ||
  367. !(listsMatch(container.list_data, data))) {
  368. container = this.addChild('List', line_number, first_nonspace);
  369. container.list_data = data;
  370. }
  371. // add the list item
  372. container = this.addChild('ListItem', line_number, first_nonspace);
  373. container.list_data = data;
  374. } else {
  375. break;
  376. }
  377. if (acceptsLines(container.t)) {
  378. // if it's a line container, it can't contain other containers
  379. break;
  380. }
  381. }
  382. // What remains at the offset is a text line. Add the text to the
  383. // appropriate container.
  384. match = matchAt(/[^ ]/, ln, offset);
  385. if (match === -1) {
  386. first_nonspace = ln.length;
  387. blank = true;
  388. } else {
  389. first_nonspace = match;
  390. blank = false;
  391. }
  392. indent = first_nonspace - offset;
  393. // First check for a lazy paragraph continuation:
  394. if (this.tip !== last_matched_container &&
  395. !blank &&
  396. this.tip.t == 'Paragraph' &&
  397. this.tip.strings.length > 0) {
  398. // lazy paragraph continuation
  399. this.last_line_blank = false;
  400. this.addLine(ln, offset);
  401. } else { // not a lazy continuation
  402. // finalize any blocks not matched
  403. closeUnmatchedBlocks(this);
  404. // Block quote lines are never blank as they start with >
  405. // and we don't count blanks in fenced code for purposes of tight/loose
  406. // lists or breaking out of lists. We also don't set last_line_blank
  407. // on an empty list item.
  408. container.last_line_blank = blank &&
  409. !(container.t == 'BlockQuote' ||
  410. container.t == 'Header' ||
  411. container.t == 'FencedCode' ||
  412. (container.t == 'ListItem' &&
  413. container.children.length === 0 &&
  414. container.start_line == line_number));
  415. var cont = container;
  416. while (cont.parent) {
  417. cont.parent.last_line_blank = false;
  418. cont = cont.parent;
  419. }
  420. switch (container.t) {
  421. case 'IndentedCode':
  422. case 'HtmlBlock':
  423. this.addLine(ln, offset);
  424. break;
  425. case 'FencedCode':
  426. // check for closing code fence:
  427. match = (indent <= 3 &&
  428. ln.charAt(first_nonspace) == container.fence_char &&
  429. ln.slice(first_nonspace).match(/^(?:`{3,}|~{3,})(?= *$)/));
  430. if (match && match[0].length >= container.fence_length) {
  431. // don't add closing fence to container; instead, close it:
  432. this.finalize(container, line_number);
  433. } else {
  434. this.addLine(ln, offset);
  435. }
  436. break;
  437. case 'Header':
  438. case 'HorizontalRule':
  439. // nothing to do; we already added the contents.
  440. break;
  441. default:
  442. if (acceptsLines(container.t)) {
  443. this.addLine(ln, first_nonspace);
  444. } else if (blank) {
  445. // do nothing
  446. } else if (container.t != 'HorizontalRule' &&
  447. container.t != 'Header') {
  448. // create paragraph container for line
  449. container = this.addChild('Paragraph', line_number, first_nonspace);
  450. this.addLine(ln, first_nonspace);
  451. } else {
  452. console.log("Line " + line_number.toString() +
  453. " with container type " + container.t +
  454. " did not match any condition.");
  455. }
  456. }
  457. }
  458. };
  459. // Finalize a block. Close it and do any necessary postprocessing,
  460. // e.g. creating string_content from strings, setting the 'tight'
  461. // or 'loose' status of a list, and parsing the beginnings
  462. // of paragraphs for reference definitions. Reset the tip to the
  463. // parent of the closed block.
  464. var finalize = function(block, line_number) {
  465. var pos;
  466. // don't do anything if the block is already closed
  467. if (!block.open) {
  468. return 0;
  469. }
  470. block.open = false;
  471. if (line_number > block.start_line) {
  472. block.end_line = line_number - 1;
  473. } else {
  474. block.end_line = line_number;
  475. }
  476. switch (block.t) {
  477. case 'Paragraph':
  478. block.string_content = block.strings.join('\n').replace(/^ */m,'');
  479. // delete block.strings;
  480. // try parsing the beginning as link reference definitions:
  481. while (block.string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  482. (pos = this.inlineParser.parseReference(block.string_content,
  483. this.refmap))) {
  484. block.string_content = block.string_content.slice(pos);
  485. if (isBlank(block.string_content)) {
  486. block.t = 'ReferenceDef';
  487. break;
  488. }
  489. }
  490. break;
  491. case 'Header':
  492. case 'HtmlBlock':
  493. block.string_content = block.strings.join('\n');
  494. break;
  495. case 'IndentedCode':
  496. block.string_content = block.strings.join('\n').replace(/(\n *)*$/,'\n');
  497. break;
  498. case 'FencedCode':
  499. // first line becomes info string
  500. block.info = unescapeString(block.strings[0].trim());
  501. if (block.strings.length == 1) {
  502. block.string_content = '';
  503. } else {
  504. block.string_content = block.strings.slice(1).join('\n') + '\n';
  505. }
  506. break;
  507. case 'List':
  508. block.tight = true; // tight by default
  509. var numitems = block.children.length;
  510. var i = 0;
  511. while (i < numitems) {
  512. var item = block.children[i];
  513. // check for non-final list item ending with blank line:
  514. var last_item = i == numitems - 1;
  515. if (endsWithBlankLine(item) && !last_item) {
  516. block.tight = false;
  517. break;
  518. }
  519. // recurse into children of list item, to see if there are
  520. // spaces between any of them:
  521. var numsubitems = item.children.length;
  522. var j = 0;
  523. while (j < numsubitems) {
  524. var subitem = item.children[j];
  525. var last_subitem = j == numsubitems - 1;
  526. if (endsWithBlankLine(subitem) && !(last_item && last_subitem)) {
  527. block.tight = false;
  528. break;
  529. }
  530. j++;
  531. }
  532. i++;
  533. }
  534. break;
  535. default:
  536. break;
  537. }
  538. this.tip = block.parent || this.top;
  539. };
  540. // Walk through a block & children recursively, parsing string content
  541. // into inline content where appropriate. Returns new object.
  542. var processInlines = function(block) {
  543. var newblock = {};
  544. newblock.t = block.t;
  545. newblock.start_line = block.start_line;
  546. newblock.start_column = block.start_column;
  547. newblock.end_line = block.end_line;
  548. switch(block.t) {
  549. case 'Paragraph':
  550. newblock.inline_content =
  551. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  552. break;
  553. case 'Header':
  554. newblock.inline_content =
  555. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  556. newblock.level = block.level;
  557. break;
  558. case 'List':
  559. newblock.list_data = block.list_data;
  560. newblock.tight = block.tight;
  561. break;
  562. case 'FencedCode':
  563. newblock.string_content = block.string_content;
  564. newblock.info = block.info;
  565. break;
  566. case 'IndentedCode':
  567. case 'HtmlBlock':
  568. newblock.string_content = block.string_content;
  569. break;
  570. default:
  571. break;
  572. }
  573. if (block.children) {
  574. var newchildren = [];
  575. for (var i = 0; i < block.children.length; i++) {
  576. newchildren.push(this.processInlines(block.children[i]));
  577. }
  578. newblock.children = newchildren;
  579. }
  580. return newblock;
  581. };
  582. // The main parsing function. Returns a parsed document AST.
  583. var parse = function(input) {
  584. this.doc = makeBlock('Document', 1, 1);
  585. this.tip = this.doc;
  586. this.refmap = {};
  587. var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/);
  588. var len = lines.length;
  589. for (var i = 0; i < len; i++) {
  590. this.incorporateLine(lines[i], i+1);
  591. }
  592. while (this.tip) {
  593. this.finalize(this.tip, len - 1);
  594. }
  595. return this.processInlines(this.doc);
  596. };
  597. // The DocParser object.
  598. function DocParser(){
  599. return {
  600. doc: makeBlock('Document', 1, 1),
  601. tip: this.doc,
  602. refmap: {},
  603. inlineParser: new InlineParser(),
  604. breakOutOfLists: breakOutOfLists,
  605. addLine: addLine,
  606. addChild: addChild,
  607. incorporateLine: incorporateLine,
  608. finalize: finalize,
  609. processInlines: processInlines,
  610. parse: parse
  611. };
  612. }
  613. module.exports = DocParser;