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