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