aboutsummaryrefslogtreecommitdiff
path: root/js/stmd.js
blob: c5268d828d8425eaa8523489ec9fef89d3efef5c (plain)
  1. // stmd.js - CommomMark in javascript
  2. // Copyright (C) 2014 John MacFarlane
  3. // License: BSD3.
  4. // Basic usage:
  5. //
  6. // var stmd = require('stmd');
  7. // var parser = new stmd.DocParser();
  8. // var renderer = new stmd.HtmlRenderer();
  9. // console.log(renderer.render(parser.parse('Hello *world*')));
  10. (function(exports) {
  11. // Some regexps used in inline parser:
  12. var ESCAPABLE = '[!"#$%&\'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]';
  13. var ESCAPED_CHAR = '\\\\' + ESCAPABLE;
  14. var IN_DOUBLE_QUOTES = '"(' + ESCAPED_CHAR + '|[^"\\x00])*"';
  15. var IN_SINGLE_QUOTES = '\'(' + ESCAPED_CHAR + '|[^\'\\x00])*\'';
  16. var IN_PARENS = '\\((' + ESCAPED_CHAR + '|[^)\\x00])*\\)';
  17. var REG_CHAR = '[^\\\\()\\x00-\\x20]';
  18. var IN_PARENS_NOSP = '\\((' + REG_CHAR + '|' + ESCAPED_CHAR + ')*\\)';
  19. var TAGNAME = '[A-Za-z][A-Za-z0-9]*';
  20. 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)';
  21. var ATTRIBUTENAME = '[a-zA-Z_:][a-zA-Z0-9:._-]*';
  22. var UNQUOTEDVALUE = "[^\"'=<>`\\x00-\\x20]+";
  23. var SINGLEQUOTEDVALUE = "'[^']*'";
  24. var DOUBLEQUOTEDVALUE = '"[^"]*"';
  25. var ATTRIBUTEVALUE = "(?:" + UNQUOTEDVALUE + "|" + SINGLEQUOTEDVALUE + "|" + DOUBLEQUOTEDVALUE + ")";
  26. var ATTRIBUTEVALUESPEC = "(?:" + "\\s*=" + "\\s*" + ATTRIBUTEVALUE + ")";
  27. var ATTRIBUTE = "(?:" + "\\s+" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC + "?)";
  28. var OPENTAG = "<" + TAGNAME + ATTRIBUTE + "*" + "\\s*/?>";
  29. var CLOSETAG = "</" + TAGNAME + "\\s*[>]";
  30. var OPENBLOCKTAG = "<" + BLOCKTAGNAME + ATTRIBUTE + "*" + "\\s*/?>";
  31. var CLOSEBLOCKTAG = "</" + BLOCKTAGNAME + "\\s*[>]";
  32. var HTMLCOMMENT = "<!--([^-]+|[-][^-]+)*-->";
  33. var PROCESSINGINSTRUCTION = "[<][?].*?[?][>]";
  34. var DECLARATION = "<![A-Z]+" + "\\s+[^>]*>";
  35. var CDATA = "<!\\[CDATA\\[([^\\]]+|\\][^\\]]|\\]\\][^>])*\\]\\]>";
  36. var HTMLTAG = "(?:" + OPENTAG + "|" + CLOSETAG + "|" + HTMLCOMMENT + "|" +
  37. PROCESSINGINSTRUCTION + "|" + DECLARATION + "|" + CDATA + ")";
  38. var HTMLBLOCKOPEN = "<(?:" + BLOCKTAGNAME + "[\\s/>]" + "|" +
  39. "/" + BLOCKTAGNAME + "[\\s>]" + "|" + "[?!])";
  40. var reHtmlTag = new RegExp('^' + HTMLTAG, 'i');
  41. var reHtmlBlockOpen = new RegExp('^' + HTMLBLOCKOPEN, 'i');
  42. var reLinkTitle = new RegExp(
  43. '^(?:"(' + ESCAPED_CHAR + '|[^"\\x00])*"' +
  44. '|' +
  45. '\'(' + ESCAPED_CHAR + '|[^\'\\x00])*\'' +
  46. '|' +
  47. '\\((' + ESCAPED_CHAR + '|[^)\\x00])*\\))');
  48. var reLinkDestinationBraces = new RegExp(
  49. '^(?:[<](?:[^<>\\n\\\\\\x00]' + '|' + ESCAPED_CHAR + '|' + '\\\\)*[>])');
  50. var reLinkDestination = new RegExp(
  51. '^(?:' + REG_CHAR + '+|' + ESCAPED_CHAR + '|' + IN_PARENS_NOSP + ')*');
  52. var reEscapable = new RegExp(ESCAPABLE);
  53. var reAllEscapedChar = new RegExp('\\\\(' + ESCAPABLE + ')', 'g');
  54. var reEscapedChar = new RegExp('^\\\\(' + ESCAPABLE + ')');
  55. var reAllTab = /\t/g;
  56. var reHrule = /^(?:(?:\* *){3,}|(?:_ *){3,}|(?:- *){3,}) *$/;
  57. // Matches a character with a special meaning in markdown,
  58. // or a string of non-special characters. Note: we match
  59. // clumps of _ or * or `, because they need to be handled in groups.
  60. var reMain = /^(?:[_*`\n]+|[\[\]\\!<&*_]|(?: *[^\n `\[\]\\!<&*_]+)+|[ \n]+)/m;
  61. // UTILITY FUNCTIONS
  62. // Replace backslash escapes with literal characters.
  63. var unescape = function(s) {
  64. return s.replace(reAllEscapedChar, '$1');
  65. };
  66. // Returns true if string contains only space characters.
  67. var isBlank = function(s) {
  68. return /^\s*$/.test(s);
  69. };
  70. // Normalize reference label: collapse internal whitespace
  71. // to single space, remove leading/trailing whitespace, case fold.
  72. var normalizeReference = function(s) {
  73. return s.trim()
  74. .replace(/\s+/,' ')
  75. .toUpperCase();
  76. };
  77. // Attempt to match a regex in string s at offset offset.
  78. // Return index of match or null.
  79. var matchAt = function(re, s, offset) {
  80. var res = s.slice(offset).match(re);
  81. if (res) {
  82. return offset + res.index;
  83. } else {
  84. return null;
  85. }
  86. };
  87. // Convert tabs to spaces on each line using a 4-space tab stop.
  88. var detabLine = function(text) {
  89. if (text.indexOf('\t') == -1) {
  90. return text;
  91. } else {
  92. var lastStop = 0;
  93. return text.replace(reAllTab, function(match, offset) {
  94. var result = ' '.slice((offset - lastStop) % 4);
  95. lastStop = offset + 1;
  96. return result;
  97. });
  98. }
  99. };
  100. // INLINE PARSER
  101. // These are methods of an InlineParser object, defined below.
  102. // An InlineParser keeps track of a subject (a string to be
  103. // parsed) and a position in that subject.
  104. // If re matches at current position in the subject, advance
  105. // position in subject and return the match; otherwise return null.
  106. var match = function(re) {
  107. var match = re.exec(this.subject.slice(this.pos));
  108. if (match) {
  109. this.pos += match.index + match[0].length;
  110. return match[0];
  111. } else {
  112. return null;
  113. }
  114. };
  115. // Returns the character at the current subject position, or null if
  116. // there are no more characters.
  117. var peek = function() {
  118. return this.subject[this.pos] || null;
  119. };
  120. // Parse zero or more space characters, including at most one newline
  121. var spnl = function() {
  122. this.match(/^ *(?:\n *)?/);
  123. return 1;
  124. };
  125. // All of the parsers below try to match something at the current position
  126. // in the subject. If they succeed in matching anything, they
  127. // return the inline matched, advancing the subject.
  128. // Attempt to parse backticks, returning either a backtick code span or a
  129. // literal sequence of backticks.
  130. var parseBackticks = function() {
  131. var startpos = this.pos;
  132. var ticks = this.match(/^`+/);
  133. if (!ticks) {
  134. return 0;
  135. }
  136. var afterOpenTicks = this.pos;
  137. var foundCode = false;
  138. var match;
  139. while (!foundCode && (match = this.match(/`+/m))) {
  140. if (match == ticks) {
  141. return [{ t: 'Code', c: this.subject.slice(afterOpenTicks,
  142. this.pos - ticks.length)
  143. .replace(/[ \n]+/g,' ')
  144. .trim() }];
  145. }
  146. }
  147. // If we got here, we didn't match a closing backtick sequence.
  148. this.pos = afterOpenTicks;
  149. return [{ t: 'Str', c: ticks }];
  150. };
  151. // Parse a backslash-escaped special character, adding either the escaped
  152. // character, a hard line break (if the backslash is followed by a newline),
  153. // or a literal backslash to the 'inlines' list.
  154. var parseBackslash = function() {
  155. var subj = this.subject,
  156. pos = this.pos;
  157. if (subj[pos] === '\\') {
  158. if (subj[pos + 1] === '\n') {
  159. this.pos = this.pos + 2;
  160. return [{ t: 'Hardbreak' }];
  161. } else if (reEscapable.test(subj[pos + 1])) {
  162. this.pos = this.pos + 2;
  163. return [{ t: 'Str', c: subj[pos + 1] }];
  164. } else {
  165. this.pos++;
  166. return [{t: 'Str', c: '\\'}];
  167. }
  168. } else {
  169. return null;
  170. }
  171. };
  172. // Attempt to parse an autolink (URL or email in pointy brackets).
  173. var parseAutolink = function() {
  174. var m;
  175. var dest;
  176. if ((m = this.match(/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/))) { // email autolink
  177. dest = m.slice(1,-1);
  178. return [{t: 'Link',
  179. label: [{ t: 'Str', c: dest }],
  180. destination: 'mailto:' + dest }];
  181. } else if ((m = this.match(/^<(?:coap|doi|javascript|aaa|aaas|about|acap|cap|cid|crid|data|dav|dict|dns|file|ftp|geo|go|gopher|h323|http|https|iax|icap|im|imap|info|ipp|iris|iris.beep|iris.xpc|iris.xpcs|iris.lwz|ldap|mailto|mid|msrp|msrps|mtqp|mupdate|news|nfs|ni|nih|nntp|opaquelocktoken|pop|pres|rtsp|service|session|shttp|sieve|sip|sips|sms|snmp|soap.beep|soap.beeps|tag|tel|telnet|tftp|thismessage|tn3270|tip|tv|urn|vemmi|ws|wss|xcon|xcon-userid|xmlrpc.beep|xmlrpc.beeps|xmpp|z39.50r|z39.50s|adiumxtra|afp|afs|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|chrome|chrome-extension|com-eventbrite-attendee|content|cvs|dlna-playsingle|dlna-playcontainer|dtn|dvb|ed2k|facetime|feed|finger|fish|gg|git|gizmoproject|gtalk|hcp|icon|ipn|irc|irc6|ircs|itms|jar|jms|keyparc|lastfm|ldaps|magnet|maps|market|message|mms|ms-help|msnim|mumble|mvn|notes|oid|palm|paparazzi|platform|proxy|psyc|query|res|resource|rmi|rsync|rtmp|secondlife|sftp|sgn|skype|smb|soldat|spotify|ssh|steam|svn|teamspeak|things|udp|unreal|ut2004|ventrilo|view-source|webcal|wtai|wyciwyg|xfire|xri|ymsgr):[^<>\x00-\x20]*>/i))) {
  182. dest = m.slice(1,-1);
  183. return [{ t: 'Link',
  184. label: [{ t: 'Str', c: dest }],
  185. destination: dest }];
  186. } else {
  187. return null;
  188. }
  189. };
  190. // Attempt to parse a raw HTML tag.
  191. var parseHtmlTag = function() {
  192. var m = this.match(reHtmlTag);
  193. if (m) {
  194. return [{ t: 'Html', c: m }];
  195. } else {
  196. return null;
  197. }
  198. };
  199. // Scan a sequence of characters == c, and return information about
  200. // the number of delimiters and whether they are positioned such that
  201. // they can open and/or close emphasis or strong emphasis. A utility
  202. // function for strong/emph parsing.
  203. var scanDelims = function(c) {
  204. var numdelims = 0;
  205. var first_close_delims = 0;
  206. var char_before, char_after;
  207. var startpos = this.pos;
  208. char_before = this.pos === 0 ? '\n' :
  209. this.subject[this.pos - 1];
  210. while (this.peek() === c) {
  211. numdelims++;
  212. this.pos++;
  213. }
  214. char_after = this.peek() || '\n';
  215. var can_open = numdelims > 0 && numdelims <= 3 && !(/\s/.test(char_after));
  216. var can_close = numdelims > 0 && numdelims <= 3 && !(/\s/.test(char_before));
  217. if (c === '_') {
  218. can_open = can_open && !((/[a-z0-9]/i).test(char_before));
  219. can_close = can_close && !((/[a-z0-9]/i).test(char_after));
  220. }
  221. this.pos = startpos;
  222. return { numdelims: numdelims,
  223. can_open: can_open,
  224. can_close: can_close };
  225. };
  226. // Attempt to parse emphasis or strong emphasis.
  227. var parseEmphasis = function() {
  228. var startpos = this.pos;
  229. var c ;
  230. var first_close = 0;
  231. c = this.peek();
  232. if (!(c === '*' || c === '_')) {
  233. return null;
  234. }
  235. var numdelims;
  236. var delimpos;
  237. var inlines = [];
  238. // Get opening delimiters.
  239. res = this.scanDelims(c);
  240. numdelims = res.numdelims;
  241. if (numdelims === 0) {
  242. this.pos = startpos;
  243. return null;
  244. }
  245. if (numdelims >= 4 || !res.can_open) {
  246. this.pos += numdelims;
  247. return [{t: 'Str', c: this.subject.slice(startpos, startpos + numdelims)}];
  248. }
  249. this.pos += numdelims;
  250. var next_inline;
  251. var first = [];
  252. var second = [];
  253. var current = first;
  254. var state = 0;
  255. var can_close = false;
  256. var can_open = false;
  257. if (numdelims === 3) {
  258. state = 1;
  259. } else if (numdelims === 2) {
  260. state = 2;
  261. } else if (numdelims === 1) {
  262. state = 3;
  263. }
  264. while (true) {
  265. res = this.scanDelims(c);
  266. if (res) {
  267. numdelims = res.numdelims;
  268. can_close = res.can_close;
  269. can_open = res.can_open;
  270. switch (state) {
  271. case 1: // ***a
  272. if (numdelims === 3 && can_close) {
  273. this.pos += 3;
  274. return [{t: 'Strong', c: [{t: 'Emph', c: first}]}];
  275. } else if (numdelims === 2 && can_close) {
  276. this.pos += 2;
  277. current = second;
  278. state = can_open ? 4 : 6;
  279. continue;
  280. } else if (numdelims === 1 && can_close) {
  281. this.pos += 1;
  282. current = second;
  283. state = can_open ? 5 : 7;
  284. continue;
  285. }
  286. break;
  287. case 2: // **a
  288. if (numdelims === 2 && can_close) {
  289. this.pos += 2;
  290. return [{t: 'Strong', c: first}];
  291. } else if (numdelims === 1 && can_open) {
  292. this.pos += 1;
  293. current = second;
  294. state = 8;
  295. continue;
  296. }
  297. break;
  298. case 3: // *a
  299. if (numdelims === 1 && can_close) {
  300. this.pos += 1;
  301. return [{t: 'Emph', c: first}];
  302. } else if (numdelims === 2 && can_open) {
  303. this.pos += 2;
  304. current = second;
  305. state = 9;
  306. continue;
  307. }
  308. break;
  309. case 4: // ***a**b
  310. if (numdelims === 3 && can_close) {
  311. this.pos += 3;
  312. return [{t: 'Strong',
  313. c: [{t: 'Emph',
  314. c: first.concat(
  315. [{t: 'Str', c: c+c}],
  316. second)}]}];
  317. } else if (numdelims === 2 && can_close) {
  318. this.pos += 2;
  319. return [{t: 'Strong',
  320. c: [{t: 'Str', c: c+c+c}].concat(
  321. first,
  322. [{t: 'Strong', c: second}])}];
  323. } else if (numdelims === 1 && can_close) {
  324. this.pos += 1;
  325. return [{t: 'Emph',
  326. c: [{t: 'Strong', c: first}].concat(second)}];
  327. }
  328. break;
  329. case 5: // ***a*b
  330. if (numdelims === 3 && can_close) {
  331. this.pos += 3;
  332. return [{t: 'Strong',
  333. c: [{t: 'Emph',
  334. c: first.concat(
  335. [{t: 'Str', c: c}],
  336. second)}]}];
  337. } else if (numdelims === 2 && can_close) {
  338. this.pos += 2;
  339. return [{t: 'Strong',
  340. c: [{t: 'Emph', c: first}].concat(second)}];
  341. } else if (numdelims === 1 && can_close) {
  342. this.pos += 1;
  343. return [{t: 'Strong',
  344. c: [{t: 'Str', c: c+c+c}].concat(
  345. first,
  346. [{t: 'Emph', c: second}])}];
  347. }
  348. break;
  349. case 6: // ***a** b
  350. if (numdelims === 3 && can_close) {
  351. this.pos += 3;
  352. return [{t: 'Strong',
  353. c: [{t: 'Emph',
  354. c: first.concat(
  355. [{t: 'Str', c: c+c}],
  356. second)}]}];
  357. } else if (numdelims === 1 && can_close) {
  358. this.pos += 1;
  359. return [{t: 'Emph',
  360. c: [{t: 'Strong', c: first}].concat(second)}];
  361. }
  362. break;
  363. case 7: // ***a* b
  364. if (numdelims === 3 && can_close) {
  365. this.pos += 3;
  366. return [{t: 'Strong',
  367. c: [{t: 'Emph',
  368. c: first.concat(
  369. [{t: 'Str', c: c}],
  370. second)}]}];
  371. } else if (numdelims === 2 && can_close) {
  372. this.pos += 2;
  373. return [{t: 'Strong',
  374. c: [{t: 'Emph', c: first}].concat(second)}];
  375. }
  376. break;
  377. case 8: // **a *b
  378. if (numdelims === 3 && can_close) {
  379. this.pos += 3;
  380. return [{t: 'Strong',
  381. c: first.concat([{t: 'Emph',
  382. c: second}])}];
  383. } else if (numdelims === 2 && can_close) {
  384. this.pos += 2;
  385. return [{t: 'Strong',
  386. c: first.concat(
  387. [{t: 'Str', c: c}],
  388. second)}];
  389. } else if (numdelims === 1 && can_close) {
  390. this.pos += 1;
  391. first = first.concat([{t: 'Emph', c: second}]);
  392. current = first;
  393. state = 2;
  394. continue;
  395. }
  396. break;
  397. case 9: // *a **b
  398. if (numdelims === 3 && can_close) {
  399. this.pos += 3;
  400. return [{t: 'Emph',
  401. c: first.concat([{t: 'Strong',
  402. c: second}])}];
  403. } else if (numdelims === 2 && can_close) {
  404. this.pos += 2;
  405. first = first.concat([{t: 'Strong', c: second}]);
  406. current = first;
  407. state = 3;
  408. continue;
  409. } else if (numdelims === 1 && can_close) {
  410. this.pos += 1;
  411. return [{t: 'Emph',
  412. c: first.concat(
  413. [{t: 'Str', c: c+c}],
  414. second)}];
  415. }
  416. break;
  417. default:
  418. break;
  419. }
  420. }
  421. if ((next_inline = this.parseInline())) {
  422. Array.prototype.push.apply(current, next_inline);
  423. } else {
  424. break;
  425. }
  426. }
  427. switch (state) {
  428. case 1: // ***a
  429. return [{t: 'Str', c: c+c+c}].concat(first);
  430. case 2: // **a
  431. return [{t: 'Str', c: c+c}].concat(first);
  432. case 3: // *a
  433. return [{t: 'Str', c: c}].concat(first);
  434. case 4: // ***a**b
  435. case 6: // ***a** b
  436. return [{t: 'Str', c: c+c+c}]
  437. .concat(first,
  438. [{t: 'Str', c: c+c}],
  439. second);
  440. case 5: // ***a*b
  441. case 7: // ***a* b
  442. return [{t: 'Str', c: c+c+c}]
  443. .concat(first,
  444. [{t: 'Str', c: c}],
  445. second);
  446. case 8: // **a *b
  447. return [{t: 'Str', c: c+c}]
  448. .concat(first,
  449. [{t: 'Str', c: c}],
  450. second);
  451. case 9: // *a **b
  452. return [{t: 'Str', c: c}]
  453. .concat(first,
  454. [{t: 'Str', c: c+c}],
  455. second);
  456. default:
  457. console.log("Unknown state, parseEmphasis");
  458. // shouldn't happen
  459. }
  460. };
  461. // Attempt to parse link title (sans quotes), returning the string
  462. // or null if no match.
  463. var parseLinkTitle = function() {
  464. var title = this.match(reLinkTitle);
  465. if (title) {
  466. // chop off quotes from title and unescape:
  467. return unescape(title.substr(1, title.length - 2));
  468. } else {
  469. return null;
  470. }
  471. };
  472. // Attempt to parse link destination, returning the string or
  473. // null if no match.
  474. var parseLinkDestination = function() {
  475. var res = this.match(reLinkDestinationBraces);
  476. if (res) { // chop off surrounding <..>:
  477. return unescape(res.substr(1, res.length - 2));
  478. } else {
  479. res = this.match(reLinkDestination);
  480. if (res !== null) {
  481. return unescape(res);
  482. } else {
  483. return null;
  484. }
  485. }
  486. };
  487. // Attempt to parse a link label, returning number of characters parsed.
  488. var parseLinkLabel = function() {
  489. if (this.peek() != '[') {
  490. return 0;
  491. }
  492. var startpos = this.pos;
  493. var nest_level = 0;
  494. if (this.label_nest_level > 0) {
  495. // If we've already checked to the end of this subject
  496. // for a label, even with a different starting [, we
  497. // know we won't find one here and we can just return.
  498. // This avoids lots of backtracking.
  499. // Note: nest level 1 would be: [foo [bar]
  500. // nest level 2 would be: [foo [bar [baz]
  501. this.label_nest_level--;
  502. return 0;
  503. }
  504. this.pos++; // advance past [
  505. var c;
  506. while ((c = this.peek()) && (c != ']' || nest_level > 0)) {
  507. switch (c) {
  508. case '`':
  509. this.parseBackticks();
  510. break;
  511. case '<':
  512. if (!(this.parseAutolink())) {
  513. this.parseHtmlTag();
  514. }
  515. break;
  516. case '[': // nested []
  517. nest_level++;
  518. this.pos++;
  519. break;
  520. case ']': // nested []
  521. nest_level--;
  522. this.pos++;
  523. break;
  524. case '\\':
  525. this.parseBackslash();
  526. break;
  527. default:
  528. this.parseString();
  529. }
  530. }
  531. if (c === ']') {
  532. this.label_nest_level = 0;
  533. this.pos++; // advance past ]
  534. return this.pos - startpos;
  535. } else {
  536. if (!c) {
  537. this.label_nest_level = nest_level;
  538. }
  539. this.pos = startpos;
  540. return 0;
  541. }
  542. };
  543. // Parse raw link label, including surrounding [], and return
  544. // inline contents. (Note: this is not a method of InlineParser.)
  545. var parseRawLabel = function(s) {
  546. // note: parse without a refmap; we don't want links to resolve
  547. // in nested brackets!
  548. return new InlineParser().parse(s.substr(1, s.length - 2), {});
  549. };
  550. // Attempt to parse a link. If successful, return the link.
  551. var parseLink = function() {
  552. var startpos = this.pos;
  553. var reflabel;
  554. var n;
  555. var dest;
  556. var title;
  557. n = this.parseLinkLabel();
  558. if (n === 0) {
  559. return null;
  560. }
  561. var afterlabel = this.pos;
  562. var rawlabel = this.subject.substr(startpos, n);
  563. // if we got this far, we've parsed a label.
  564. // Try to parse an explicit link: [label](url "title")
  565. if (this.peek() == '(') {
  566. this.pos++;
  567. if (this.spnl() &&
  568. ((dest = this.parseLinkDestination()) !== null) &&
  569. this.spnl() &&
  570. // make sure there's a space before the title:
  571. (/^\s/.test(this.subject[this.pos - 1]) &&
  572. (title = this.parseLinkTitle() || '') || true) &&
  573. this.spnl() &&
  574. this.match(/^\)/)) {
  575. return [{ t: 'Link',
  576. destination: dest,
  577. title: title,
  578. label: parseRawLabel(rawlabel) }];
  579. } else {
  580. this.pos = startpos;
  581. return null;
  582. }
  583. }
  584. // If we're here, it wasn't an explicit link. Try to parse a reference link.
  585. // first, see if there's another label
  586. var savepos = this.pos;
  587. this.spnl();
  588. var beforelabel = this.pos;
  589. n = this.parseLinkLabel();
  590. if (n == 2) {
  591. // empty second label
  592. reflabel = rawlabel;
  593. } else if (n > 0) {
  594. reflabel = this.subject.slice(beforelabel, beforelabel + n);
  595. } else {
  596. this.pos = savepos;
  597. reflabel = rawlabel;
  598. }
  599. // lookup rawlabel in refmap
  600. var link = this.refmap[normalizeReference(reflabel)];
  601. if (link) {
  602. return [{t: 'Link',
  603. destination: link.destination,
  604. title: link.title,
  605. label: parseRawLabel(rawlabel) }];
  606. } else {
  607. this.pos = startpos;
  608. return null;
  609. }
  610. // Nothing worked, rewind:
  611. this.pos = startpos;
  612. return null;
  613. };
  614. // Attempt to parse an entity, return Entity object if successful.
  615. var parseEntity = function() {
  616. var m;
  617. if ((m = this.match(/^&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});/i))) {
  618. return [{ t: 'Entity', c: m }];
  619. } else {
  620. return null;
  621. }
  622. };
  623. // Parse a run of ordinary characters, or a single character with
  624. // a special meaning in markdown, as a plain string, adding to inlines.
  625. var parseString = function() {
  626. var m;
  627. if ((m = this.match(reMain))) {
  628. return [{ t: 'Str', c: m }];
  629. } else {
  630. return null;
  631. }
  632. };
  633. // Parse a newline. If it was preceded by two spaces, return a hard
  634. // line break; otherwise a soft line break.
  635. var parseNewline = function() {
  636. var m = this.match(/^ *\n/);
  637. if (m) {
  638. if (m.length > 2) {
  639. return [{ t: 'Hardbreak' }];
  640. } else if (m.length > 0) {
  641. return [{ t: 'Softbreak' }];
  642. }
  643. }
  644. return null;
  645. };
  646. // Attempt to parse an image. If the opening '!' is not followed
  647. // by a link, return a literal '!'.
  648. var parseImage = function() {
  649. if (this.match(/^!/)) {
  650. var link = this.parseLink();
  651. if (link) {
  652. link[0].t = 'Image';
  653. return link;
  654. } else {
  655. return [{ t: 'Str', c: '!' }];
  656. }
  657. } else {
  658. return null;
  659. }
  660. };
  661. // Attempt to parse a link reference, modifying refmap.
  662. var parseReference = function(s, refmap) {
  663. this.subject = s;
  664. this.pos = 0;
  665. var rawlabel;
  666. var dest;
  667. var title;
  668. var matchChars;
  669. var startpos = this.pos;
  670. var match;
  671. // label:
  672. matchChars = this.parseLinkLabel();
  673. if (matchChars === 0) {
  674. return 0;
  675. } else {
  676. rawlabel = this.subject.substr(0, matchChars);
  677. }
  678. // colon:
  679. if (this.peek() === ':') {
  680. this.pos++;
  681. } else {
  682. this.pos = startpos;
  683. return 0;
  684. }
  685. // link url
  686. this.spnl();
  687. dest = this.parseLinkDestination();
  688. if (dest === null || dest.length === 0) {
  689. this.pos = startpos;
  690. return 0;
  691. }
  692. var beforetitle = this.pos;
  693. this.spnl();
  694. title = this.parseLinkTitle();
  695. if (title === null) {
  696. title = '';
  697. // rewind before spaces
  698. this.pos = beforetitle;
  699. }
  700. // make sure we're at line end:
  701. if (this.match(/^ *(?:\n|$)/) === null) {
  702. this.pos = startpos;
  703. return 0;
  704. }
  705. var normlabel = normalizeReference(rawlabel);
  706. if (!refmap[normlabel]) {
  707. refmap[normlabel] = { destination: dest, title: title };
  708. }
  709. return this.pos - startpos;
  710. };
  711. // Parse the next inline element in subject, advancing subject position
  712. // and returning the inline parsed.
  713. var parseInline = function() {
  714. var startpos = this.pos;
  715. /*
  716. var memoized = this.memo[startpos];
  717. if (memoized) {
  718. this.pos = memoized.endpos;
  719. return memoized.inline;
  720. }
  721. */
  722. var c = this.peek();
  723. if (!c) {
  724. return null;
  725. }
  726. var res;
  727. switch(c) {
  728. case '\n':
  729. case ' ':
  730. res = this.parseNewline();
  731. break;
  732. case '\\':
  733. res = this.parseBackslash();
  734. break;
  735. case '`':
  736. res = this.parseBackticks();
  737. break;
  738. case '*':
  739. case '_':
  740. res = this.parseEmphasis();
  741. break;
  742. case '[':
  743. res = this.parseLink();
  744. break;
  745. case '!':
  746. res = this.parseImage();
  747. break;
  748. case '<':
  749. res = this.parseAutolink() || this.parseHtmlTag();
  750. break;
  751. case '&':
  752. res = this.parseEntity();
  753. break;
  754. default:
  755. res = this.parseString();
  756. break;
  757. }
  758. if (res === null) {
  759. this.pos += 1;
  760. res = [{t: 'Str', c: c}];
  761. }
  762. /*
  763. if (res) {
  764. this.memo[startpos] = { inline: res,
  765. endpos: this.pos };
  766. }
  767. */
  768. return res;
  769. };
  770. // Parse s as a list of inlines, using refmap to resolve references.
  771. var parseInlines = function(s, refmap) {
  772. this.subject = s;
  773. this.pos = 0;
  774. this.refmap = refmap || {};
  775. // this.memo = {};
  776. this.last_emphasis_closer = null;
  777. var inlines = [];
  778. var next_inline;
  779. while ((next_inline = this.parseInline())) {
  780. Array.prototype.push.apply(inlines, next_inline);
  781. }
  782. return inlines;
  783. };
  784. // The InlineParser object.
  785. function InlineParser(){
  786. return {
  787. subject: '',
  788. label_nest_level: 0, // used by parseLinkLabel method
  789. last_emphasis_closer: null, // used by parseEmphasis method
  790. pos: 0,
  791. refmap: {},
  792. // memo: {},
  793. match: match,
  794. peek: peek,
  795. spnl: spnl,
  796. parseBackticks: parseBackticks,
  797. parseBackslash: parseBackslash,
  798. parseAutolink: parseAutolink,
  799. parseHtmlTag: parseHtmlTag,
  800. scanDelims: scanDelims,
  801. parseEmphasis: parseEmphasis,
  802. parseLinkTitle: parseLinkTitle,
  803. parseLinkDestination: parseLinkDestination,
  804. parseLinkLabel: parseLinkLabel,
  805. parseLink: parseLink,
  806. parseEntity: parseEntity,
  807. parseString: parseString,
  808. parseNewline: parseNewline,
  809. parseImage: parseImage,
  810. parseReference: parseReference,
  811. parseInline: parseInline,
  812. parse: parseInlines
  813. };
  814. }
  815. // DOC PARSER
  816. // These are methods of a DocParser object, defined below.
  817. var makeBlock = function(tag, start_line, start_column) {
  818. return { t: tag,
  819. open: true,
  820. last_line_blank: false,
  821. start_line: start_line,
  822. start_column: start_column,
  823. end_line: start_line,
  824. children: [],
  825. parent: null,
  826. // string_content is formed by concatenating strings, in finalize:
  827. string_content: "",
  828. strings: [],
  829. inline_content: []
  830. };
  831. };
  832. // Returns true if parent block can contain child block.
  833. var canContain = function(parent_type, child_type) {
  834. return ( parent_type == 'Document' ||
  835. parent_type == 'BlockQuote' ||
  836. parent_type == 'ListItem' ||
  837. (parent_type == 'List' && child_type == 'ListItem') );
  838. };
  839. // Returns true if block type can accept lines of text.
  840. var acceptsLines = function(block_type) {
  841. return ( block_type == 'Paragraph' ||
  842. block_type == 'IndentedCode' ||
  843. block_type == 'FencedCode' );
  844. };
  845. // Returns true if block ends with a blank line, descending if needed
  846. // into lists and sublists.
  847. var endsWithBlankLine = function(block) {
  848. if (block.last_line_blank) {
  849. return true;
  850. }
  851. if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) {
  852. return endsWithBlankLine(block.children[block.children.length - 1]);
  853. } else {
  854. return false;
  855. }
  856. };
  857. // Break out of all containing lists, resetting the tip of the
  858. // document to the parent of the highest list, and finalizing
  859. // all the lists. (This is used to implement the "two blank lines
  860. // break of of all lists" feature.)
  861. var breakOutOfLists = function(block, line_number) {
  862. var b = block;
  863. var last_list = null;
  864. do {
  865. if (b.t === 'List') {
  866. last_list = b;
  867. }
  868. b = b.parent;
  869. } while (b);
  870. if (last_list) {
  871. while (block != last_list) {
  872. this.finalize(block, line_number);
  873. block = block.parent;
  874. }
  875. this.finalize(last_list, line_number);
  876. this.tip = last_list.parent;
  877. }
  878. };
  879. // Add a line to the block at the tip. We assume the tip
  880. // can accept lines -- that check should be done before calling this.
  881. var addLine = function(ln, offset) {
  882. var s = ln.slice(offset);
  883. if (!(this.tip.open)) {
  884. throw({ msg: "Attempted to add line (" + ln + ") to closed container." });
  885. }
  886. this.tip.strings.push(s);
  887. };
  888. // Add block of type tag as a child of the tip. If the tip can't
  889. // accept children, close and finalize it and try its parent,
  890. // and so on til we find a block that can accept children.
  891. var addChild = function(tag, line_number, offset) {
  892. while (!canContain(this.tip.t, tag)) {
  893. this.finalize(this.tip, line_number);
  894. }
  895. var column_number = offset + 1; // offset 0 = column 1
  896. var newBlock = makeBlock(tag, line_number, column_number);
  897. this.tip.children.push(newBlock);
  898. newBlock.parent = this.tip;
  899. this.tip = newBlock;
  900. return newBlock;
  901. };
  902. // Parse a list marker and return data on the marker (type,
  903. // start, delimiter, bullet character, padding) or null.
  904. var parseListMarker = function(ln, offset) {
  905. var rest = ln.slice(offset);
  906. var match;
  907. var spaces_after_marker;
  908. var data = {};
  909. if (rest.match(reHrule)) {
  910. return null;
  911. }
  912. if ((match = rest.match(/^[*+-]( +|$)/))) {
  913. spaces_after_marker = match[1].length;
  914. data.type = 'Bullet';
  915. data.bullet_char = match[0][0];
  916. } else if ((match = rest.match(/^(\d+)([.)])( +|$)/))) {
  917. spaces_after_marker = match[3].length;
  918. data.type = 'Ordered';
  919. data.start = parseInt(match[1]);
  920. data.delimiter = match[2];
  921. } else {
  922. return null;
  923. }
  924. var blank_item = match[0].length === rest.length;
  925. if (spaces_after_marker >= 5 ||
  926. spaces_after_marker < 1 ||
  927. blank_item) {
  928. data.padding = match[0].length - spaces_after_marker + 1;
  929. } else {
  930. data.padding = match[0].length;
  931. }
  932. return data;
  933. };
  934. // Returns true if the two list items are of the same type,
  935. // with the same delimiter and bullet character. This is used
  936. // in agglomerating list items into lists.
  937. var listsMatch = function(list_data, item_data) {
  938. return (list_data.type === item_data.type &&
  939. list_data.delimiter === item_data.delimiter &&
  940. list_data.bullet_char === item_data.bullet_char);
  941. };
  942. // Analyze a line of text and update the document appropriately.
  943. // We parse markdown text by calling this on each line of input,
  944. // then finalizing the document.
  945. var incorporateLine = function(ln, line_number) {
  946. var all_matched = true;
  947. var last_child;
  948. var first_nonspace;
  949. var offset = 0;
  950. var match;
  951. var data;
  952. var blank;
  953. var indent;
  954. var last_matched_container;
  955. var i;
  956. var CODE_INDENT = 4;
  957. var container = this.doc;
  958. var oldtip = this.tip;
  959. // Convert tabs to spaces:
  960. ln = detabLine(ln);
  961. // For each containing block, try to parse the associated line start.
  962. // Bail out on failure: container will point to the last matching block.
  963. // Set all_matched to false if not all containers match.
  964. while (container.children.length > 0) {
  965. last_child = container.children[container.children.length - 1];
  966. if (!last_child.open) {
  967. break;
  968. }
  969. container = last_child;
  970. match = matchAt(/[^ ]/, ln, offset);
  971. if (match === null) {
  972. first_nonspace = ln.length;
  973. blank = true;
  974. } else {
  975. first_nonspace = match;
  976. blank = false;
  977. }
  978. indent = first_nonspace - offset;
  979. switch (container.t) {
  980. case 'BlockQuote':
  981. var matched = indent <= 3 && ln[first_nonspace] === '>';
  982. if (matched) {
  983. offset = first_nonspace + 1;
  984. if (ln[offset] === ' ') {
  985. offset++;
  986. }
  987. } else {
  988. all_matched = false;
  989. }
  990. break;
  991. case 'ListItem':
  992. if (indent >= container.list_data.marker_offset +
  993. container.list_data.padding) {
  994. offset += container.list_data.marker_offset +
  995. container.list_data.padding;
  996. } else if (blank) {
  997. offset = first_nonspace;
  998. } else {
  999. all_matched = false;
  1000. }
  1001. break;
  1002. case 'IndentedCode':
  1003. if (indent >= CODE_INDENT) {
  1004. offset += CODE_INDENT;
  1005. } else if (blank) {
  1006. offset = first_nonspace;
  1007. } else {
  1008. all_matched = false;
  1009. }
  1010. break;
  1011. case 'ATXHeader':
  1012. case 'SetextHeader':
  1013. case 'HorizontalRule':
  1014. // a header can never container > 1 line, so fail to match:
  1015. all_matched = false;
  1016. break;
  1017. case 'FencedCode':
  1018. // skip optional spaces of fence offset
  1019. i = container.fence_offset;
  1020. while (i > 0 && ln[offset] === ' ') {
  1021. offset++;
  1022. i--;
  1023. }
  1024. break;
  1025. case 'HtmlBlock':
  1026. if (blank) {
  1027. all_matched = false;
  1028. }
  1029. break;
  1030. case 'Paragraph':
  1031. if (blank) {
  1032. container.last_line_blank = true;
  1033. all_matched = false;
  1034. }
  1035. break;
  1036. default:
  1037. }
  1038. if (!all_matched) {
  1039. container = container.parent; // back up to last matching block
  1040. break;
  1041. }
  1042. }
  1043. last_matched_container = container;
  1044. // This function is used to finalize and close any unmatched
  1045. // blocks. We aren't ready to do this now, because we might
  1046. // have a lazy paragraph continuation, in which case we don't
  1047. // want to close unmatched blocks. So we store this closure for
  1048. // use later, when we have more information.
  1049. var closeUnmatchedBlocks = function(mythis) {
  1050. // finalize any blocks not matched
  1051. while (!already_done && oldtip != last_matched_container) {
  1052. mythis.finalize(oldtip, line_number);
  1053. oldtip = oldtip.parent;
  1054. }
  1055. var already_done = true;
  1056. };
  1057. // Check to see if we've hit 2nd blank line; if so break out of list:
  1058. if (blank && container.last_line_blank) {
  1059. this.breakOutOfLists(container, line_number);
  1060. }
  1061. // Unless last matched container is a code block, try new container starts,
  1062. // adding children to the last matched container:
  1063. while (container.t != 'FencedCode' &&
  1064. container.t != 'IndentedCode' &&
  1065. container.t != 'HtmlBlock' &&
  1066. // this is a little performance optimization:
  1067. matchAt(/^[ #`~*+_=<>0-9-]/,ln,offset) !== null) {
  1068. match = matchAt(/[^ ]/, ln, offset);
  1069. if (match === null) {
  1070. first_nonspace = ln.length;
  1071. blank = true;
  1072. } else {
  1073. first_nonspace = match;
  1074. blank = false;
  1075. }
  1076. indent = first_nonspace - offset;
  1077. if (indent >= CODE_INDENT) {
  1078. // indented code
  1079. if (this.tip.t != 'Paragraph' && !blank) {
  1080. offset += CODE_INDENT;
  1081. closeUnmatchedBlocks(this);
  1082. container = this.addChild('IndentedCode', line_number, offset);
  1083. } else { // indent > 4 in a lazy paragraph continuation
  1084. break;
  1085. }
  1086. } else if (ln[first_nonspace] === '>') {
  1087. // blockquote
  1088. offset = first_nonspace + 1;
  1089. // optional following space
  1090. if (ln[offset] === ' ') {
  1091. offset++;
  1092. }
  1093. closeUnmatchedBlocks(this);
  1094. container = this.addChild('BlockQuote', line_number, offset);
  1095. } else if ((match = ln.slice(first_nonspace).match(/^#{1,6}(?: +|$)/))) {
  1096. // ATX header
  1097. offset = first_nonspace + match[0].length;
  1098. closeUnmatchedBlocks(this);
  1099. container = this.addChild('ATXHeader', line_number, first_nonspace);
  1100. container.level = match[0].trim().length; // number of #s
  1101. // remove trailing ###s:
  1102. container.strings =
  1103. [ln.slice(offset).replace(/(?:(\\#) *#*| *#+) *$/,'$1')];
  1104. break;
  1105. } else if ((match = ln.slice(first_nonspace).match(/^`{3,}(?!.*`)|^~{3,}(?!.*~)/))) {
  1106. // fenced code block
  1107. var fence_length = match[0].length;
  1108. closeUnmatchedBlocks(this);
  1109. container = this.addChild('FencedCode', line_number, first_nonspace);
  1110. container.fence_length = fence_length;
  1111. container.fence_char = match[0][0];
  1112. container.fence_offset = first_nonspace - offset;
  1113. offset = first_nonspace + fence_length;
  1114. break;
  1115. } else if (matchAt(reHtmlBlockOpen, ln, first_nonspace) !== null) {
  1116. // html block
  1117. closeUnmatchedBlocks(this);
  1118. container = this.addChild('HtmlBlock', line_number, first_nonspace);
  1119. // note, we don't adjust offset because the tag is part of the text
  1120. break;
  1121. } else if (container.t == 'Paragraph' &&
  1122. container.strings.length === 1 &&
  1123. ((match = ln.slice(first_nonspace).match(/^(?:=+|-+) *$/)))) {
  1124. // setext header line
  1125. closeUnmatchedBlocks(this);
  1126. container.t = 'SetextHeader'; // convert Paragraph to SetextHeader
  1127. container.level = match[0][0] === '=' ? 1 : 2;
  1128. offset = ln.length;
  1129. } else if (matchAt(reHrule, ln, first_nonspace) !== null) {
  1130. // hrule
  1131. closeUnmatchedBlocks(this);
  1132. container = this.addChild('HorizontalRule', line_number, first_nonspace);
  1133. offset = ln.length - 1;
  1134. break;
  1135. } else if ((data = parseListMarker(ln, first_nonspace))) {
  1136. // list item
  1137. closeUnmatchedBlocks(this);
  1138. data.marker_offset = indent;
  1139. offset = first_nonspace + data.padding;
  1140. // add the list if needed
  1141. if (container.t !== 'List' ||
  1142. !(listsMatch(container.list_data, data))) {
  1143. container = this.addChild('List', line_number, first_nonspace);
  1144. container.list_data = data;
  1145. }
  1146. // add the list item
  1147. container = this.addChild('ListItem', line_number, first_nonspace);
  1148. container.list_data = data;
  1149. } else {
  1150. break;
  1151. }
  1152. if (acceptsLines(container.t)) {
  1153. // if it's a line container, it can't contain other containers
  1154. break;
  1155. }
  1156. }
  1157. // What remains at the offset is a text line. Add the text to the
  1158. // appropriate container.
  1159. match = matchAt(/[^ ]/, ln, offset);
  1160. if (match === null) {
  1161. first_nonspace = ln.length;
  1162. blank = true;
  1163. } else {
  1164. first_nonspace = match;
  1165. blank = false;
  1166. }
  1167. indent = first_nonspace - offset;
  1168. // First check for a lazy paragraph continuation:
  1169. if (this.tip !== last_matched_container &&
  1170. !blank &&
  1171. this.tip.t == 'Paragraph' &&
  1172. this.tip.strings.length > 0) {
  1173. // lazy paragraph continuation
  1174. this.last_line_blank = false;
  1175. this.addLine(ln, offset);
  1176. } else { // not a lazy continuation
  1177. // finalize any blocks not matched
  1178. closeUnmatchedBlocks(this);
  1179. // Block quote lines are never blank as they start with >
  1180. // and we don't count blanks in fenced code for purposes of tight/loose
  1181. // lists or breaking out of lists. We also don't set last_line_blank
  1182. // on an empty list item.
  1183. container.last_line_blank = blank &&
  1184. !(container.t == 'BlockQuote' ||
  1185. container.t == 'FencedCode' ||
  1186. (container.t == 'ListItem' &&
  1187. container.children.length === 0 &&
  1188. container.start_line == line_number));
  1189. var cont = container;
  1190. while (cont.parent) {
  1191. cont.parent.last_line_blank = false;
  1192. cont = cont.parent;
  1193. }
  1194. switch (container.t) {
  1195. case 'IndentedCode':
  1196. case 'HtmlBlock':
  1197. this.addLine(ln, offset);
  1198. break;
  1199. case 'FencedCode':
  1200. // check for closing code fence:
  1201. match = (indent <= 3 &&
  1202. ln[first_nonspace] == container.fence_char &&
  1203. ln.slice(first_nonspace).match(/^(?:`{3,}|~{3,})(?= *$)/));
  1204. if (match && match[0].length >= container.fence_length) {
  1205. // don't add closing fence to container; instead, close it:
  1206. this.finalize(container, line_number);
  1207. } else {
  1208. this.addLine(ln, offset);
  1209. }
  1210. break;
  1211. case 'ATXHeader':
  1212. case 'SetextHeader':
  1213. case 'HorizontalRule':
  1214. // nothing to do; we already added the contents.
  1215. break;
  1216. default:
  1217. if (acceptsLines(container.t)) {
  1218. this.addLine(ln, first_nonspace);
  1219. } else if (blank) {
  1220. // do nothing
  1221. } else if (container.t != 'HorizontalRule' &&
  1222. container.t != 'SetextHeader') {
  1223. // create paragraph container for line
  1224. container = this.addChild('Paragraph', line_number, first_nonspace);
  1225. this.addLine(ln, first_nonspace);
  1226. } else {
  1227. console.log("Line " + line_number.toString() +
  1228. " with container type " + container.t +
  1229. " did not match any condition.");
  1230. }
  1231. }
  1232. }
  1233. };
  1234. // Finalize a block. Close it and do any necessary postprocessing,
  1235. // e.g. creating string_content from strings, setting the 'tight'
  1236. // or 'loose' status of a list, and parsing the beginnings
  1237. // of paragraphs for reference definitions. Reset the tip to the
  1238. // parent of the closed block.
  1239. var finalize = function(block, line_number) {
  1240. var pos;
  1241. // don't do anything if the block is already closed
  1242. if (!block.open) {
  1243. return 0;
  1244. }
  1245. block.open = false;
  1246. if (line_number > block.start_line) {
  1247. block.end_line = line_number - 1;
  1248. } else {
  1249. block.end_line = line_number;
  1250. }
  1251. switch (block.t) {
  1252. case 'Paragraph':
  1253. block.string_content = block.strings.join('\n').replace(/^ */m,'');
  1254. // try parsing the beginning as link reference definitions:
  1255. while (block.string_content[0] === '[' &&
  1256. (pos = this.inlineParser.parseReference(block.string_content,
  1257. this.refmap))) {
  1258. block.string_content = block.string_content.slice(pos);
  1259. if (isBlank(block.string_content)) {
  1260. block.t = 'ReferenceDef';
  1261. break;
  1262. }
  1263. }
  1264. break;
  1265. case 'ATXHeader':
  1266. case 'SetextHeader':
  1267. case 'HtmlBlock':
  1268. block.string_content = block.strings.join('\n');
  1269. break;
  1270. case 'IndentedCode':
  1271. block.string_content = block.strings.join('\n').replace(/(\n *)*$/,'\n');
  1272. break;
  1273. case 'FencedCode':
  1274. // first line becomes info string
  1275. block.info = unescape(block.strings[0].trim());
  1276. if (block.strings.length == 1) {
  1277. block.string_content = '';
  1278. } else {
  1279. block.string_content = block.strings.slice(1).join('\n') + '\n';
  1280. }
  1281. break;
  1282. case 'List':
  1283. block.tight = true; // tight by default
  1284. var numitems = block.children.length;
  1285. var i = 0;
  1286. while (i < numitems) {
  1287. var item = block.children[i];
  1288. // check for non-final list item ending with blank line:
  1289. var last_item = i == numitems - 1;
  1290. if (endsWithBlankLine(item) && !last_item) {
  1291. block.tight = false;
  1292. break;
  1293. }
  1294. // recurse into children of list item, to see if there are
  1295. // spaces between any of them:
  1296. var numsubitems = item.children.length;
  1297. var j = 0;
  1298. while (j < numsubitems) {
  1299. var subitem = item.children[j];
  1300. var last_subitem = j == numsubitems - 1;
  1301. if (endsWithBlankLine(subitem) && !(last_item && last_subitem)) {
  1302. block.tight = false;
  1303. break;
  1304. }
  1305. j++;
  1306. }
  1307. i++;
  1308. }
  1309. break;
  1310. default:
  1311. break;
  1312. }
  1313. this.tip = block.parent || this.top;
  1314. };
  1315. // Walk through a block & children recursively, parsing string content
  1316. // into inline content where appropriate.
  1317. var processInlines = function(block) {
  1318. switch(block.t) {
  1319. case 'Paragraph':
  1320. case 'SetextHeader':
  1321. case 'ATXHeader':
  1322. block.inline_content =
  1323. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  1324. block.string_content = "";
  1325. break;
  1326. default:
  1327. break;
  1328. }
  1329. if (block.children) {
  1330. for (var i = 0; i < block.children.length; i++) {
  1331. this.processInlines(block.children[i]);
  1332. }
  1333. }
  1334. };
  1335. // The main parsing function. Returns a parsed document AST.
  1336. var parse = function(input) {
  1337. this.doc = makeBlock('Document', 1, 1);
  1338. this.tip = this.doc;
  1339. this.refmap = {};
  1340. var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/);
  1341. var len = lines.length;
  1342. for (var i = 0; i < len; i++) {
  1343. this.incorporateLine(lines[i], i+1);
  1344. }
  1345. while (this.tip) {
  1346. this.finalize(this.tip, len - 1);
  1347. }
  1348. this.processInlines(this.doc);
  1349. return this.doc;
  1350. };
  1351. // The DocParser object.
  1352. function DocParser(){
  1353. return {
  1354. doc: makeBlock('Document', 1, 1),
  1355. tip: this.doc,
  1356. refmap: {},
  1357. inlineParser: new InlineParser(),
  1358. breakOutOfLists: breakOutOfLists,
  1359. addLine: addLine,
  1360. addChild: addChild,
  1361. incorporateLine: incorporateLine,
  1362. finalize: finalize,
  1363. processInlines: processInlines,
  1364. parse: parse
  1365. };
  1366. }
  1367. // HTML RENDERER
  1368. // Helper function to produce content in a pair of HTML tags.
  1369. var inTags = function(tag, attribs, contents, selfclosing) {
  1370. var result = '<' + tag;
  1371. if (attribs) {
  1372. var i = 0;
  1373. var attrib;
  1374. while ((attrib = attribs[i]) !== undefined) {
  1375. result = result.concat(' ', attrib[0], '="', attrib[1], '"');
  1376. i++;
  1377. }
  1378. }
  1379. if (contents) {
  1380. result = result.concat('>', contents, '</', tag, '>');
  1381. } else if (selfclosing) {
  1382. result = result + ' />';
  1383. } else {
  1384. result = result.concat('></', tag, '>');
  1385. }
  1386. return result;
  1387. };
  1388. // Render an inline element as HTML.
  1389. var renderInline = function(inline) {
  1390. var attrs;
  1391. switch (inline.t) {
  1392. case 'Str':
  1393. return this.escape(inline.c);
  1394. case 'Softbreak':
  1395. return this.softbreak;
  1396. case 'Hardbreak':
  1397. return inTags('br',[],"",true) + '\n';
  1398. case 'Emph':
  1399. return inTags('em', [], this.renderInlines(inline.c));
  1400. case 'Strong':
  1401. return inTags('strong', [], this.renderInlines(inline.c));
  1402. case 'Html':
  1403. return inline.c;
  1404. case 'Entity':
  1405. return inline.c;
  1406. case 'Link':
  1407. attrs = [['href', this.escape(inline.destination, true)]];
  1408. if (inline.title) {
  1409. attrs.push(['title', this.escape(inline.title, true)]);
  1410. }
  1411. return inTags('a', attrs, this.renderInlines(inline.label));
  1412. case 'Image':
  1413. attrs = [['src', this.escape(inline.destination, true)],
  1414. ['alt', this.escape(this.renderInlines(inline.label))]];
  1415. if (inline.title) {
  1416. attrs.push(['title', this.escape(inline.title, true)]);
  1417. }
  1418. return inTags('img', attrs, "", true);
  1419. case 'Code':
  1420. return inTags('code', [], this.escape(inline.c));
  1421. default:
  1422. console.log("Unknown inline type " + inline.t);
  1423. return "";
  1424. }
  1425. };
  1426. // Render a list of inlines.
  1427. var renderInlines = function(inlines) {
  1428. var result = '';
  1429. for (var i=0; i < inlines.length; i++) {
  1430. result = result + this.renderInline(inlines[i]);
  1431. }
  1432. return result;
  1433. };
  1434. // Render a single block element.
  1435. var renderBlock = function(block, in_tight_list) {
  1436. var tag;
  1437. var attr;
  1438. var info_words;
  1439. switch (block.t) {
  1440. case 'Document':
  1441. var whole_doc = this.renderBlocks(block.children);
  1442. return (whole_doc === '' ? '' : whole_doc + '\n');
  1443. case 'Paragraph':
  1444. if (in_tight_list) {
  1445. return this.renderInlines(block.inline_content);
  1446. } else {
  1447. return inTags('p', [], this.renderInlines(block.inline_content));
  1448. }
  1449. break;
  1450. case 'BlockQuote':
  1451. var filling = this.renderBlocks(block.children);
  1452. return inTags('blockquote', [], filling === '' ? this.innersep :
  1453. this.innersep + this.renderBlocks(block.children) + this.innersep);
  1454. case 'ListItem':
  1455. return inTags('li', [], this.renderBlocks(block.children, in_tight_list).trim());
  1456. case 'List':
  1457. tag = block.list_data.type == 'Bullet' ? 'ul' : 'ol';
  1458. attr = (!block.list_data.start || block.list_data.start == 1) ?
  1459. [] : [['start', block.list_data.start.toString()]];
  1460. return inTags(tag, attr, this.innersep +
  1461. this.renderBlocks(block.children, block.tight) +
  1462. this.innersep);
  1463. case 'ATXHeader':
  1464. case 'SetextHeader':
  1465. tag = 'h' + block.level;
  1466. return inTags(tag, [], this.renderInlines(block.inline_content));
  1467. case 'IndentedCode':
  1468. return inTags('pre', [],
  1469. inTags('code', [], this.escape(block.string_content)));
  1470. case 'FencedCode':
  1471. info_words = block.info.split(/ +/);
  1472. attr = info_words.length === 0 || info_words[0].length === 0 ?
  1473. [] : [['class','language-' +
  1474. this.escape(info_words[0],true)]];
  1475. return inTags('pre', [],
  1476. inTags('code', attr, this.escape(block.string_content)));
  1477. case 'HtmlBlock':
  1478. return block.string_content;
  1479. case 'ReferenceDef':
  1480. return "";
  1481. case 'HorizontalRule':
  1482. return inTags('hr',[],"",true);
  1483. default:
  1484. console.log("Unknown block type " + block.t);
  1485. return "";
  1486. }
  1487. };
  1488. // Render a list of block elements, separated by this.blocksep.
  1489. var renderBlocks = function(blocks, in_tight_list) {
  1490. var result = [];
  1491. for (var i=0; i < blocks.length; i++) {
  1492. if (blocks[i].t !== 'ReferenceDef') {
  1493. result.push(this.renderBlock(blocks[i], in_tight_list));
  1494. }
  1495. }
  1496. return result.join(this.blocksep);
  1497. };
  1498. // The HtmlRenderer object.
  1499. function HtmlRenderer(){
  1500. return {
  1501. // default options:
  1502. blocksep: '\n', // space between blocks
  1503. innersep: '\n', // space between block container tag and contents
  1504. softbreak: '\n', // by default, soft breaks are rendered as newlines in HTML
  1505. // set to "<br />" to make them hard breaks
  1506. // set to " " if you want to ignore line wrapping in source
  1507. escape: function(s, preserve_entities) {
  1508. if (preserve_entities) {
  1509. return s.replace(/[&](?![#](x[a-f0-9]{1,8}|[0-9]{1,8});|[a-z][a-z0-9]{1,31};)/gi,'&amp;')
  1510. .replace(/[<]/g,'&lt;')
  1511. .replace(/[>]/g,'&gt;')
  1512. .replace(/["]/g,'&quot;');
  1513. } else {
  1514. return s.replace(/[&]/g,'&amp;')
  1515. .replace(/[<]/g,'&lt;')
  1516. .replace(/[>]/g,'&gt;')
  1517. .replace(/["]/g,'&quot;');
  1518. }
  1519. },
  1520. renderInline: renderInline,
  1521. renderInlines: renderInlines,
  1522. renderBlock: renderBlock,
  1523. renderBlocks: renderBlocks,
  1524. render: renderBlock
  1525. };
  1526. }
  1527. exports.DocParser = DocParser;
  1528. exports.HtmlRenderer = HtmlRenderer;
  1529. })(typeof exports === 'undefined' ? this.stmd = {} : exports);