aboutsummaryrefslogtreecommitdiff
path: root/js/stmd.js
blob: 97120edb22a793e6a983f9fa445325eb64b026a1 (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 unescapeBS = 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.charAt(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.charAt(pos) === '\\') {
  158. if (subj.charAt(pos + 1) === '\n') {
  159. this.pos = this.pos + 2;
  160. return [{ t: 'Hardbreak' }];
  161. } else if (reEscapable.test(subj.charAt(pos + 1))) {
  162. this.pos = this.pos + 2;
  163. return [{ t: 'Str', c: subj.charAt(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:' + encodeURI(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: encodeURI(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.charAt(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. var Emph = function(ils) {
  227. return {t: 'Emph', c: ils};
  228. }
  229. var Strong = function(ils) {
  230. return {t: 'Strong', c: ils};
  231. }
  232. var Str = function(s) {
  233. return {t: 'Str', c: s};
  234. }
  235. // Attempt to parse emphasis or strong emphasis.
  236. var parseEmphasis = function() {
  237. var startpos = this.pos;
  238. var c ;
  239. var first_close = 0;
  240. c = this.peek();
  241. if (!(c === '*' || c === '_')) {
  242. return null;
  243. }
  244. var numdelims;
  245. var delimpos;
  246. var inlines = [];
  247. // Get opening delimiters.
  248. res = this.scanDelims(c);
  249. numdelims = res.numdelims;
  250. if (numdelims === 0) {
  251. this.pos = startpos;
  252. return null;
  253. }
  254. if (numdelims >= 4 || !res.can_open) {
  255. this.pos += numdelims;
  256. return [Str(this.subject.slice(startpos, startpos + numdelims))];
  257. }
  258. this.pos += numdelims;
  259. var fallbackpos = this.pos;
  260. var fallback = Str(this.subject.slice(startpos, fallbackpos));
  261. var next_inline;
  262. var first = [];
  263. var second = [];
  264. var current = first;
  265. var state = 0;
  266. var can_close = false;
  267. var can_open = false;
  268. var last_emphasis_closer = null;
  269. if (numdelims === 3) {
  270. state = 1;
  271. } else if (numdelims === 2) {
  272. state = 2;
  273. } else if (numdelims === 1) {
  274. state = 3;
  275. }
  276. while (true) {
  277. if (this.last_emphasis_closer[c] < this.pos) {
  278. break;
  279. }
  280. res = this.scanDelims(c);
  281. if (res) {
  282. numdelims = res.numdelims;
  283. can_close = res.can_close;
  284. if (can_close) {
  285. last_emphasis_closer = this.pos;
  286. }
  287. can_open = res.can_open;
  288. switch (state) {
  289. case 1: // ***a
  290. if (numdelims === 3 && can_close) {
  291. this.pos += 3;
  292. return [Strong([Emph(first)])];
  293. } else if (numdelims === 2 && can_close) {
  294. this.pos += 2;
  295. current = second;
  296. state = can_open ? 4 : 6;
  297. continue;
  298. } else if (numdelims === 1 && can_close) {
  299. this.pos += 1;
  300. current = second;
  301. state = can_open ? 5 : 7;
  302. continue;
  303. }
  304. break;
  305. case 2: // **a
  306. if (numdelims === 2 && can_close) {
  307. this.pos += 2;
  308. return [Strong(first)];
  309. } else if (numdelims === 1 && can_open) {
  310. this.pos += 1;
  311. current = second;
  312. state = 8;
  313. continue;
  314. }
  315. break;
  316. case 3: // *a
  317. if (numdelims === 1 && can_close) {
  318. this.pos += 1;
  319. return [Emph(first)];
  320. } else if (numdelims === 2 && can_open) {
  321. this.pos += 2;
  322. current = second;
  323. state = 9;
  324. continue;
  325. }
  326. break;
  327. case 4: // ***a**b
  328. if (numdelims === 3 && can_close) {
  329. this.pos += 3;
  330. return [Strong([Emph(first.concat([Str(c+c)], second))])];
  331. } else if (numdelims === 2 && can_close) {
  332. this.pos += 2;
  333. return [Strong([Str(c+c+c)].concat(
  334. first,
  335. [Strong(second)]))];
  336. } else if (numdelims === 1 && can_close) {
  337. this.pos += 1;
  338. return [Emph([Strong(first)].concat(second))];
  339. }
  340. break;
  341. case 5: // ***a*b
  342. if (numdelims === 3 && can_close) {
  343. this.pos += 3;
  344. return [Strong([Emph(first.concat([Str(c)], second))])];
  345. } else if (numdelims === 2 && can_close) {
  346. this.pos += 2;
  347. return [Strong([Emph(first)].concat(second))];
  348. } else if (numdelims === 1 && can_close) {
  349. this.pos += 1;
  350. return [Strong([Str(c+c+c)].concat(
  351. first,
  352. [Emph(second)]))];
  353. }
  354. break;
  355. case 6: // ***a** b
  356. if (numdelims === 3 && can_close) {
  357. this.pos += 3;
  358. return [Strong([Emph(first.concat([Str(c+c)], second))])];
  359. } else if (numdelims === 1 && can_close) {
  360. this.pos += 1;
  361. return [Emph([Strong(first)].concat(second))];
  362. }
  363. break;
  364. case 7: // ***a* b
  365. if (numdelims === 3 && can_close) {
  366. this.pos += 3;
  367. return [Strong([Emph(first.concat([Str(c)], second))])];
  368. } else if (numdelims === 2 && can_close) {
  369. this.pos += 2;
  370. return [Strong([Emph(first)].concat(second))];
  371. }
  372. break;
  373. case 8: // **a *b
  374. if (numdelims === 3 && can_close) {
  375. this.pos += 3;
  376. return [Strong(first.concat([Emph(second)]))];
  377. } else if (numdelims === 2 && can_close) {
  378. this.pos += 2;
  379. return [Strong(first.concat([Str(c)], second))];
  380. } else if (numdelims === 1 && can_close) {
  381. this.pos += 1;
  382. first.push(Emph(second));
  383. current = first;
  384. state = 2;
  385. continue;
  386. }
  387. break;
  388. case 9: // *a **b
  389. if (numdelims === 3 && can_close) {
  390. this.pos += 3;
  391. return [(Emph(first.concat([Strong(second)])))];
  392. } else if (numdelims === 2 && can_close) {
  393. this.pos += 2;
  394. first.push(Strong(second));
  395. current = first;
  396. state = 3;
  397. continue;
  398. } else if (numdelims === 1 && can_close) {
  399. this.pos += 1;
  400. return [Emph(first.concat([Str(c+c)], second))];
  401. }
  402. break;
  403. default:
  404. break;
  405. }
  406. }
  407. if ((next_inline = this.parseInline(true))) {
  408. Array.prototype.push.apply(current, next_inline);
  409. } else {
  410. break;
  411. }
  412. }
  413. // we didn't match emphasis: fallback
  414. this.pos = fallbackpos;
  415. if (last_emphasis_closer) {
  416. this.last_emphasis_closer[c] = last_emphasis_closer;
  417. }
  418. return [fallback];
  419. };
  420. // Attempt to parse link title (sans quotes), returning the string
  421. // or null if no match.
  422. var parseLinkTitle = function() {
  423. var title = this.match(reLinkTitle);
  424. if (title) {
  425. // chop off quotes from title and unescape:
  426. return unescapeBS(title.substr(1, title.length - 2));
  427. } else {
  428. return null;
  429. }
  430. };
  431. // Attempt to parse link destination, returning the string or
  432. // null if no match.
  433. var parseLinkDestination = function() {
  434. var res = this.match(reLinkDestinationBraces);
  435. if (res) { // chop off surrounding <..>:
  436. return encodeURI(unescapeBS(res.substr(1, res.length - 2)));
  437. } else {
  438. res = this.match(reLinkDestination);
  439. if (res !== null) {
  440. return encodeURI(unescapeBS(res));
  441. } else {
  442. return null;
  443. }
  444. }
  445. };
  446. // Attempt to parse a link label, returning number of characters parsed.
  447. var parseLinkLabel = function() {
  448. if (this.peek() != '[') {
  449. return 0;
  450. }
  451. var startpos = this.pos;
  452. var nest_level = 0;
  453. if (this.label_nest_level > 0) {
  454. // If we've already checked to the end of this subject
  455. // for a label, even with a different starting [, we
  456. // know we won't find one here and we can just return.
  457. // This avoids lots of backtracking.
  458. // Note: nest level 1 would be: [foo [bar]
  459. // nest level 2 would be: [foo [bar [baz]
  460. this.label_nest_level--;
  461. return 0;
  462. }
  463. this.pos++; // advance past [
  464. var c;
  465. while ((c = this.peek()) && (c != ']' || nest_level > 0)) {
  466. switch (c) {
  467. case '`':
  468. this.parseBackticks();
  469. break;
  470. case '<':
  471. this.parseAutolink() || this.parseHtmlTag() ||
  472. this.pos++;
  473. break;
  474. case '[': // nested []
  475. nest_level++;
  476. this.pos++;
  477. break;
  478. case ']': // nested []
  479. nest_level--;
  480. this.pos++;
  481. break;
  482. case '\\':
  483. this.parseBackslash();
  484. break;
  485. default:
  486. this.parseString();
  487. }
  488. }
  489. if (c === ']') {
  490. this.label_nest_level = 0;
  491. this.pos++; // advance past ]
  492. return this.pos - startpos;
  493. } else {
  494. if (!c) {
  495. this.label_nest_level = nest_level;
  496. }
  497. this.pos = startpos;
  498. return 0;
  499. }
  500. };
  501. // Parse raw link label, including surrounding [], and return
  502. // inline contents. (Note: this is not a method of InlineParser.)
  503. var parseRawLabel = function(s) {
  504. // note: parse without a refmap; we don't want links to resolve
  505. // in nested brackets!
  506. return new InlineParser().parse(s.substr(1, s.length - 2), {});
  507. };
  508. // Attempt to parse a link. If successful, return the link.
  509. var parseLink = function() {
  510. var startpos = this.pos;
  511. var reflabel;
  512. var n;
  513. var dest;
  514. var title;
  515. n = this.parseLinkLabel();
  516. if (n === 0) {
  517. return null;
  518. }
  519. var afterlabel = this.pos;
  520. var rawlabel = this.subject.substr(startpos, n);
  521. // if we got this far, we've parsed a label.
  522. // Try to parse an explicit link: [label](url "title")
  523. if (this.peek() == '(') {
  524. this.pos++;
  525. if (this.spnl() &&
  526. ((dest = this.parseLinkDestination()) !== null) &&
  527. this.spnl() &&
  528. // make sure there's a space before the title:
  529. (/^\s/.test(this.subject.charAt(this.pos - 1)) &&
  530. (title = this.parseLinkTitle() || '') || true) &&
  531. this.spnl() &&
  532. this.match(/^\)/)) {
  533. return [{ t: 'Link',
  534. destination: dest,
  535. title: title,
  536. label: parseRawLabel(rawlabel) }];
  537. } else {
  538. this.pos = startpos;
  539. return null;
  540. }
  541. }
  542. // If we're here, it wasn't an explicit link. Try to parse a reference link.
  543. // first, see if there's another label
  544. var savepos = this.pos;
  545. this.spnl();
  546. var beforelabel = this.pos;
  547. n = this.parseLinkLabel();
  548. if (n == 2) {
  549. // empty second label
  550. reflabel = rawlabel;
  551. } else if (n > 0) {
  552. reflabel = this.subject.slice(beforelabel, beforelabel + n);
  553. } else {
  554. this.pos = savepos;
  555. reflabel = rawlabel;
  556. }
  557. // lookup rawlabel in refmap
  558. var link = this.refmap[normalizeReference(reflabel)];
  559. if (link) {
  560. return [{t: 'Link',
  561. destination: link.destination,
  562. title: link.title,
  563. label: parseRawLabel(rawlabel) }];
  564. } else {
  565. this.pos = startpos;
  566. return null;
  567. }
  568. // Nothing worked, rewind:
  569. this.pos = startpos;
  570. return null;
  571. };
  572. // Attempt to parse an entity, return Entity object if successful.
  573. var parseEntity = function() {
  574. var m;
  575. if ((m = this.match(/^&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});/i))) {
  576. return [{ t: 'Entity', c: m }];
  577. } else {
  578. return null;
  579. }
  580. };
  581. // Parse a run of ordinary characters, or a single character with
  582. // a special meaning in markdown, as a plain string, adding to inlines.
  583. var parseString = function() {
  584. var m;
  585. if ((m = this.match(reMain))) {
  586. return [{ t: 'Str', c: m }];
  587. } else {
  588. return null;
  589. }
  590. };
  591. // Parse a newline. If it was preceded by two spaces, return a hard
  592. // line break; otherwise a soft line break.
  593. var parseNewline = function() {
  594. var m = this.match(/^ *\n/);
  595. if (m) {
  596. if (m.length > 2) {
  597. return [{ t: 'Hardbreak' }];
  598. } else if (m.length > 0) {
  599. return [{ t: 'Softbreak' }];
  600. }
  601. }
  602. return null;
  603. };
  604. // Attempt to parse an image. If the opening '!' is not followed
  605. // by a link, return a literal '!'.
  606. var parseImage = function() {
  607. if (this.match(/^!/)) {
  608. var link = this.parseLink();
  609. if (link) {
  610. link[0].t = 'Image';
  611. return link;
  612. } else {
  613. return [{ t: 'Str', c: '!' }];
  614. }
  615. } else {
  616. return null;
  617. }
  618. };
  619. // Attempt to parse a link reference, modifying refmap.
  620. var parseReference = function(s, refmap) {
  621. this.subject = s;
  622. this.pos = 0;
  623. var rawlabel;
  624. var dest;
  625. var title;
  626. var matchChars;
  627. var startpos = this.pos;
  628. var match;
  629. // label:
  630. matchChars = this.parseLinkLabel();
  631. if (matchChars === 0) {
  632. return 0;
  633. } else {
  634. rawlabel = this.subject.substr(0, matchChars);
  635. }
  636. // colon:
  637. if (this.peek() === ':') {
  638. this.pos++;
  639. } else {
  640. this.pos = startpos;
  641. return 0;
  642. }
  643. // link url
  644. this.spnl();
  645. dest = this.parseLinkDestination();
  646. if (dest === null || dest.length === 0) {
  647. this.pos = startpos;
  648. return 0;
  649. }
  650. var beforetitle = this.pos;
  651. this.spnl();
  652. title = this.parseLinkTitle();
  653. if (title === null) {
  654. title = '';
  655. // rewind before spaces
  656. this.pos = beforetitle;
  657. }
  658. // make sure we're at line end:
  659. if (this.match(/^ *(?:\n|$)/) === null) {
  660. this.pos = startpos;
  661. return 0;
  662. }
  663. var normlabel = normalizeReference(rawlabel);
  664. if (!refmap[normlabel]) {
  665. refmap[normlabel] = { destination: dest, title: title };
  666. }
  667. return this.pos - startpos;
  668. };
  669. // Parse the next inline element in subject, advancing subject position
  670. // and returning the inline parsed.
  671. var parseInline = function(memoize) {
  672. var startpos = this.pos;
  673. var memoized = memoize && this.memo[startpos];
  674. if (memoized) {
  675. this.pos = memoized.endpos;
  676. return memoized.inline;
  677. }
  678. var c = this.peek();
  679. if (!c) {
  680. return null;
  681. }
  682. var res;
  683. switch(c) {
  684. case '\n':
  685. case ' ':
  686. res = this.parseNewline();
  687. break;
  688. case '\\':
  689. res = this.parseBackslash();
  690. break;
  691. case '`':
  692. res = this.parseBackticks();
  693. break;
  694. case '*':
  695. case '_':
  696. res = this.parseEmphasis();
  697. break;
  698. case '[':
  699. res = this.parseLink();
  700. break;
  701. case '!':
  702. res = this.parseImage();
  703. break;
  704. case '<':
  705. res = this.parseAutolink() || this.parseHtmlTag();
  706. break;
  707. case '&':
  708. res = this.parseEntity();
  709. break;
  710. default:
  711. res = this.parseString();
  712. break;
  713. }
  714. if (res === null) {
  715. this.pos += 1;
  716. res = [{t: 'Str', c: c}];
  717. }
  718. if (res && memoize) {
  719. this.memo[startpos] = { inline: res,
  720. endpos: this.pos };
  721. }
  722. return res;
  723. };
  724. // Parse s as a list of inlines, using refmap to resolve references.
  725. var parseInlines = function(s, refmap) {
  726. this.subject = s;
  727. this.pos = 0;
  728. this.refmap = refmap || {};
  729. this.memo = {};
  730. this.last_emphasis_closer = { '*': s.length, '_': s.length };
  731. var inlines = [];
  732. var next_inline;
  733. while ((next_inline = this.parseInline())) {
  734. Array.prototype.push.apply(inlines, next_inline);
  735. }
  736. return inlines;
  737. };
  738. // The InlineParser object.
  739. function InlineParser(){
  740. return {
  741. subject: '',
  742. label_nest_level: 0, // used by parseLinkLabel method
  743. last_emphasis_closer: null, // used by parseEmphasis method
  744. pos: 0,
  745. refmap: {},
  746. memo: {},
  747. match: match,
  748. peek: peek,
  749. spnl: spnl,
  750. parseBackticks: parseBackticks,
  751. parseBackslash: parseBackslash,
  752. parseAutolink: parseAutolink,
  753. parseHtmlTag: parseHtmlTag,
  754. scanDelims: scanDelims,
  755. parseEmphasis: parseEmphasis,
  756. parseLinkTitle: parseLinkTitle,
  757. parseLinkDestination: parseLinkDestination,
  758. parseLinkLabel: parseLinkLabel,
  759. parseLink: parseLink,
  760. parseEntity: parseEntity,
  761. parseString: parseString,
  762. parseNewline: parseNewline,
  763. parseImage: parseImage,
  764. parseReference: parseReference,
  765. parseInline: parseInline,
  766. parse: parseInlines
  767. };
  768. }
  769. // DOC PARSER
  770. // These are methods of a DocParser object, defined below.
  771. var makeBlock = function(tag, start_line, start_column) {
  772. return { t: tag,
  773. open: true,
  774. last_line_blank: false,
  775. start_line: start_line,
  776. start_column: start_column,
  777. end_line: start_line,
  778. children: [],
  779. parent: null,
  780. // string_content is formed by concatenating strings, in finalize:
  781. string_content: "",
  782. strings: [],
  783. inline_content: []
  784. };
  785. };
  786. // Returns true if parent block can contain child block.
  787. var canContain = function(parent_type, child_type) {
  788. return ( parent_type == 'Document' ||
  789. parent_type == 'BlockQuote' ||
  790. parent_type == 'ListItem' ||
  791. (parent_type == 'List' && child_type == 'ListItem') );
  792. };
  793. // Returns true if block type can accept lines of text.
  794. var acceptsLines = function(block_type) {
  795. return ( block_type == 'Paragraph' ||
  796. block_type == 'IndentedCode' ||
  797. block_type == 'FencedCode' );
  798. };
  799. // Returns true if block ends with a blank line, descending if needed
  800. // into lists and sublists.
  801. var endsWithBlankLine = function(block) {
  802. if (block.last_line_blank) {
  803. return true;
  804. }
  805. if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) {
  806. return endsWithBlankLine(block.children[block.children.length - 1]);
  807. } else {
  808. return false;
  809. }
  810. };
  811. // Break out of all containing lists, resetting the tip of the
  812. // document to the parent of the highest list, and finalizing
  813. // all the lists. (This is used to implement the "two blank lines
  814. // break of of all lists" feature.)
  815. var breakOutOfLists = function(block, line_number) {
  816. var b = block;
  817. var last_list = null;
  818. do {
  819. if (b.t === 'List') {
  820. last_list = b;
  821. }
  822. b = b.parent;
  823. } while (b);
  824. if (last_list) {
  825. while (block != last_list) {
  826. this.finalize(block, line_number);
  827. block = block.parent;
  828. }
  829. this.finalize(last_list, line_number);
  830. this.tip = last_list.parent;
  831. }
  832. };
  833. // Add a line to the block at the tip. We assume the tip
  834. // can accept lines -- that check should be done before calling this.
  835. var addLine = function(ln, offset) {
  836. var s = ln.slice(offset);
  837. if (!(this.tip.open)) {
  838. throw({ msg: "Attempted to add line (" + ln + ") to closed container." });
  839. }
  840. this.tip.strings.push(s);
  841. };
  842. // Add block of type tag as a child of the tip. If the tip can't
  843. // accept children, close and finalize it and try its parent,
  844. // and so on til we find a block that can accept children.
  845. var addChild = function(tag, line_number, offset) {
  846. while (!canContain(this.tip.t, tag)) {
  847. this.finalize(this.tip, line_number);
  848. }
  849. var column_number = offset + 1; // offset 0 = column 1
  850. var newBlock = makeBlock(tag, line_number, column_number);
  851. this.tip.children.push(newBlock);
  852. newBlock.parent = this.tip;
  853. this.tip = newBlock;
  854. return newBlock;
  855. };
  856. // Parse a list marker and return data on the marker (type,
  857. // start, delimiter, bullet character, padding) or null.
  858. var parseListMarker = function(ln, offset) {
  859. var rest = ln.slice(offset);
  860. var match;
  861. var spaces_after_marker;
  862. var data = {};
  863. if (rest.match(reHrule)) {
  864. return null;
  865. }
  866. if ((match = rest.match(/^[*+-]( +|$)/))) {
  867. spaces_after_marker = match[1].length;
  868. data.type = 'Bullet';
  869. data.bullet_char = match[0][0];
  870. } else if ((match = rest.match(/^(\d+)([.)])( +|$)/))) {
  871. spaces_after_marker = match[3].length;
  872. data.type = 'Ordered';
  873. data.start = parseInt(match[1]);
  874. data.delimiter = match[2];
  875. } else {
  876. return null;
  877. }
  878. var blank_item = match[0].length === rest.length;
  879. if (spaces_after_marker >= 5 ||
  880. spaces_after_marker < 1 ||
  881. blank_item) {
  882. data.padding = match[0].length - spaces_after_marker + 1;
  883. } else {
  884. data.padding = match[0].length;
  885. }
  886. return data;
  887. };
  888. // Returns true if the two list items are of the same type,
  889. // with the same delimiter and bullet character. This is used
  890. // in agglomerating list items into lists.
  891. var listsMatch = function(list_data, item_data) {
  892. return (list_data.type === item_data.type &&
  893. list_data.delimiter === item_data.delimiter &&
  894. list_data.bullet_char === item_data.bullet_char);
  895. };
  896. // Analyze a line of text and update the document appropriately.
  897. // We parse markdown text by calling this on each line of input,
  898. // then finalizing the document.
  899. var incorporateLine = function(ln, line_number) {
  900. var all_matched = true;
  901. var last_child;
  902. var first_nonspace;
  903. var offset = 0;
  904. var match;
  905. var data;
  906. var blank;
  907. var indent;
  908. var last_matched_container;
  909. var i;
  910. var CODE_INDENT = 4;
  911. var container = this.doc;
  912. var oldtip = this.tip;
  913. // Convert tabs to spaces:
  914. ln = detabLine(ln);
  915. // For each containing block, try to parse the associated line start.
  916. // Bail out on failure: container will point to the last matching block.
  917. // Set all_matched to false if not all containers match.
  918. while (container.children.length > 0) {
  919. last_child = container.children[container.children.length - 1];
  920. if (!last_child.open) {
  921. break;
  922. }
  923. container = last_child;
  924. match = matchAt(/[^ ]/, ln, offset);
  925. if (match === null) {
  926. first_nonspace = ln.length;
  927. blank = true;
  928. } else {
  929. first_nonspace = match;
  930. blank = false;
  931. }
  932. indent = first_nonspace - offset;
  933. switch (container.t) {
  934. case 'BlockQuote':
  935. var matched = indent <= 3 && ln.charAt(first_nonspace) === '>';
  936. if (matched) {
  937. offset = first_nonspace + 1;
  938. if (ln.charAt(offset) === ' ') {
  939. offset++;
  940. }
  941. } else {
  942. all_matched = false;
  943. }
  944. break;
  945. case 'ListItem':
  946. if (indent >= container.list_data.marker_offset +
  947. container.list_data.padding) {
  948. offset += container.list_data.marker_offset +
  949. container.list_data.padding;
  950. } else if (blank) {
  951. offset = first_nonspace;
  952. } else {
  953. all_matched = false;
  954. }
  955. break;
  956. case 'IndentedCode':
  957. if (indent >= CODE_INDENT) {
  958. offset += CODE_INDENT;
  959. } else if (blank) {
  960. offset = first_nonspace;
  961. } else {
  962. all_matched = false;
  963. }
  964. break;
  965. case 'ATXHeader':
  966. case 'SetextHeader':
  967. case 'HorizontalRule':
  968. // a header can never container > 1 line, so fail to match:
  969. all_matched = false;
  970. break;
  971. case 'FencedCode':
  972. // skip optional spaces of fence offset
  973. i = container.fence_offset;
  974. while (i > 0 && ln.charAt(offset) === ' ') {
  975. offset++;
  976. i--;
  977. }
  978. break;
  979. case 'HtmlBlock':
  980. if (blank) {
  981. all_matched = false;
  982. }
  983. break;
  984. case 'Paragraph':
  985. if (blank) {
  986. container.last_line_blank = true;
  987. all_matched = false;
  988. }
  989. break;
  990. default:
  991. }
  992. if (!all_matched) {
  993. container = container.parent; // back up to last matching block
  994. break;
  995. }
  996. }
  997. last_matched_container = container;
  998. // This function is used to finalize and close any unmatched
  999. // blocks. We aren't ready to do this now, because we might
  1000. // have a lazy paragraph continuation, in which case we don't
  1001. // want to close unmatched blocks. So we store this closure for
  1002. // use later, when we have more information.
  1003. var closeUnmatchedBlocks = function(mythis) {
  1004. // finalize any blocks not matched
  1005. while (!already_done && oldtip != last_matched_container) {
  1006. mythis.finalize(oldtip, line_number);
  1007. oldtip = oldtip.parent;
  1008. }
  1009. var already_done = true;
  1010. };
  1011. // Check to see if we've hit 2nd blank line; if so break out of list:
  1012. if (blank && container.last_line_blank) {
  1013. this.breakOutOfLists(container, line_number);
  1014. }
  1015. // Unless last matched container is a code block, try new container starts,
  1016. // adding children to the last matched container:
  1017. while (container.t != 'FencedCode' &&
  1018. container.t != 'IndentedCode' &&
  1019. container.t != 'HtmlBlock' &&
  1020. // this is a little performance optimization:
  1021. matchAt(/^[ #`~*+_=<>0-9-]/,ln,offset) !== null) {
  1022. match = matchAt(/[^ ]/, ln, offset);
  1023. if (match === null) {
  1024. first_nonspace = ln.length;
  1025. blank = true;
  1026. } else {
  1027. first_nonspace = match;
  1028. blank = false;
  1029. }
  1030. indent = first_nonspace - offset;
  1031. if (indent >= CODE_INDENT) {
  1032. // indented code
  1033. if (this.tip.t != 'Paragraph' && !blank) {
  1034. offset += CODE_INDENT;
  1035. closeUnmatchedBlocks(this);
  1036. container = this.addChild('IndentedCode', line_number, offset);
  1037. } else { // indent > 4 in a lazy paragraph continuation
  1038. break;
  1039. }
  1040. } else if (ln.charAt(first_nonspace) === '>') {
  1041. // blockquote
  1042. offset = first_nonspace + 1;
  1043. // optional following space
  1044. if (ln.charAt(offset) === ' ') {
  1045. offset++;
  1046. }
  1047. closeUnmatchedBlocks(this);
  1048. container = this.addChild('BlockQuote', line_number, offset);
  1049. } else if ((match = ln.slice(first_nonspace).match(/^#{1,6}(?: +|$)/))) {
  1050. // ATX header
  1051. offset = first_nonspace + match[0].length;
  1052. closeUnmatchedBlocks(this);
  1053. container = this.addChild('ATXHeader', line_number, first_nonspace);
  1054. container.level = match[0].trim().length; // number of #s
  1055. // remove trailing ###s:
  1056. container.strings =
  1057. [ln.slice(offset).replace(/(?:(\\#) *#*| *#+) *$/,'$1')];
  1058. break;
  1059. } else if ((match = ln.slice(first_nonspace).match(/^`{3,}(?!.*`)|^~{3,}(?!.*~)/))) {
  1060. // fenced code block
  1061. var fence_length = match[0].length;
  1062. closeUnmatchedBlocks(this);
  1063. container = this.addChild('FencedCode', line_number, first_nonspace);
  1064. container.fence_length = fence_length;
  1065. container.fence_char = match[0][0];
  1066. container.fence_offset = first_nonspace - offset;
  1067. offset = first_nonspace + fence_length;
  1068. break;
  1069. } else if (matchAt(reHtmlBlockOpen, ln, first_nonspace) !== null) {
  1070. // html block
  1071. closeUnmatchedBlocks(this);
  1072. container = this.addChild('HtmlBlock', line_number, first_nonspace);
  1073. // note, we don't adjust offset because the tag is part of the text
  1074. break;
  1075. } else if (container.t == 'Paragraph' &&
  1076. container.strings.length === 1 &&
  1077. ((match = ln.slice(first_nonspace).match(/^(?:=+|-+) *$/)))) {
  1078. // setext header line
  1079. closeUnmatchedBlocks(this);
  1080. container.t = 'SetextHeader'; // convert Paragraph to SetextHeader
  1081. container.level = match[0][0] === '=' ? 1 : 2;
  1082. offset = ln.length;
  1083. } else if (matchAt(reHrule, ln, first_nonspace) !== null) {
  1084. // hrule
  1085. closeUnmatchedBlocks(this);
  1086. container = this.addChild('HorizontalRule', line_number, first_nonspace);
  1087. offset = ln.length - 1;
  1088. break;
  1089. } else if ((data = parseListMarker(ln, first_nonspace))) {
  1090. // list item
  1091. closeUnmatchedBlocks(this);
  1092. data.marker_offset = indent;
  1093. offset = first_nonspace + data.padding;
  1094. // add the list if needed
  1095. if (container.t !== 'List' ||
  1096. !(listsMatch(container.list_data, data))) {
  1097. container = this.addChild('List', line_number, first_nonspace);
  1098. container.list_data = data;
  1099. }
  1100. // add the list item
  1101. container = this.addChild('ListItem', line_number, first_nonspace);
  1102. container.list_data = data;
  1103. } else {
  1104. break;
  1105. }
  1106. if (acceptsLines(container.t)) {
  1107. // if it's a line container, it can't contain other containers
  1108. break;
  1109. }
  1110. }
  1111. // What remains at the offset is a text line. Add the text to the
  1112. // appropriate container.
  1113. match = matchAt(/[^ ]/, ln, offset);
  1114. if (match === null) {
  1115. first_nonspace = ln.length;
  1116. blank = true;
  1117. } else {
  1118. first_nonspace = match;
  1119. blank = false;
  1120. }
  1121. indent = first_nonspace - offset;
  1122. // First check for a lazy paragraph continuation:
  1123. if (this.tip !== last_matched_container &&
  1124. !blank &&
  1125. this.tip.t == 'Paragraph' &&
  1126. this.tip.strings.length > 0) {
  1127. // lazy paragraph continuation
  1128. this.last_line_blank = false;
  1129. this.addLine(ln, offset);
  1130. } else { // not a lazy continuation
  1131. // finalize any blocks not matched
  1132. closeUnmatchedBlocks(this);
  1133. // Block quote lines are never blank as they start with >
  1134. // and we don't count blanks in fenced code for purposes of tight/loose
  1135. // lists or breaking out of lists. We also don't set last_line_blank
  1136. // on an empty list item.
  1137. container.last_line_blank = blank &&
  1138. !(container.t == 'BlockQuote' ||
  1139. container.t == 'FencedCode' ||
  1140. (container.t == 'ListItem' &&
  1141. container.children.length === 0 &&
  1142. container.start_line == line_number));
  1143. var cont = container;
  1144. while (cont.parent) {
  1145. cont.parent.last_line_blank = false;
  1146. cont = cont.parent;
  1147. }
  1148. switch (container.t) {
  1149. case 'IndentedCode':
  1150. case 'HtmlBlock':
  1151. this.addLine(ln, offset);
  1152. break;
  1153. case 'FencedCode':
  1154. // check for closing code fence:
  1155. match = (indent <= 3 &&
  1156. ln.charAt(first_nonspace) == container.fence_char &&
  1157. ln.slice(first_nonspace).match(/^(?:`{3,}|~{3,})(?= *$)/));
  1158. if (match && match[0].length >= container.fence_length) {
  1159. // don't add closing fence to container; instead, close it:
  1160. this.finalize(container, line_number);
  1161. } else {
  1162. this.addLine(ln, offset);
  1163. }
  1164. break;
  1165. case 'ATXHeader':
  1166. case 'SetextHeader':
  1167. case 'HorizontalRule':
  1168. // nothing to do; we already added the contents.
  1169. break;
  1170. default:
  1171. if (acceptsLines(container.t)) {
  1172. this.addLine(ln, first_nonspace);
  1173. } else if (blank) {
  1174. // do nothing
  1175. } else if (container.t != 'HorizontalRule' &&
  1176. container.t != 'SetextHeader') {
  1177. // create paragraph container for line
  1178. container = this.addChild('Paragraph', line_number, first_nonspace);
  1179. this.addLine(ln, first_nonspace);
  1180. } else {
  1181. console.log("Line " + line_number.toString() +
  1182. " with container type " + container.t +
  1183. " did not match any condition.");
  1184. }
  1185. }
  1186. }
  1187. };
  1188. // Finalize a block. Close it and do any necessary postprocessing,
  1189. // e.g. creating string_content from strings, setting the 'tight'
  1190. // or 'loose' status of a list, and parsing the beginnings
  1191. // of paragraphs for reference definitions. Reset the tip to the
  1192. // parent of the closed block.
  1193. var finalize = function(block, line_number) {
  1194. var pos;
  1195. // don't do anything if the block is already closed
  1196. if (!block.open) {
  1197. return 0;
  1198. }
  1199. block.open = false;
  1200. if (line_number > block.start_line) {
  1201. block.end_line = line_number - 1;
  1202. } else {
  1203. block.end_line = line_number;
  1204. }
  1205. switch (block.t) {
  1206. case 'Paragraph':
  1207. block.string_content = block.strings.join('\n').replace(/^ */m,'');
  1208. // try parsing the beginning as link reference definitions:
  1209. while (block.string_content.charAt(0) === '[' &&
  1210. (pos = this.inlineParser.parseReference(block.string_content,
  1211. this.refmap))) {
  1212. block.string_content = block.string_content.slice(pos);
  1213. if (isBlank(block.string_content)) {
  1214. block.t = 'ReferenceDef';
  1215. break;
  1216. }
  1217. }
  1218. break;
  1219. case 'ATXHeader':
  1220. case 'SetextHeader':
  1221. case 'HtmlBlock':
  1222. block.string_content = block.strings.join('\n');
  1223. break;
  1224. case 'IndentedCode':
  1225. block.string_content = block.strings.join('\n').replace(/(\n *)*$/,'\n');
  1226. break;
  1227. case 'FencedCode':
  1228. // first line becomes info string
  1229. block.info = unescapeBS(block.strings[0].trim());
  1230. if (block.strings.length == 1) {
  1231. block.string_content = '';
  1232. } else {
  1233. block.string_content = block.strings.slice(1).join('\n') + '\n';
  1234. }
  1235. break;
  1236. case 'List':
  1237. block.tight = true; // tight by default
  1238. var numitems = block.children.length;
  1239. var i = 0;
  1240. while (i < numitems) {
  1241. var item = block.children[i];
  1242. // check for non-final list item ending with blank line:
  1243. var last_item = i == numitems - 1;
  1244. if (endsWithBlankLine(item) && !last_item) {
  1245. block.tight = false;
  1246. break;
  1247. }
  1248. // recurse into children of list item, to see if there are
  1249. // spaces between any of them:
  1250. var numsubitems = item.children.length;
  1251. var j = 0;
  1252. while (j < numsubitems) {
  1253. var subitem = item.children[j];
  1254. var last_subitem = j == numsubitems - 1;
  1255. if (endsWithBlankLine(subitem) && !(last_item && last_subitem)) {
  1256. block.tight = false;
  1257. break;
  1258. }
  1259. j++;
  1260. }
  1261. i++;
  1262. }
  1263. break;
  1264. default:
  1265. break;
  1266. }
  1267. this.tip = block.parent || this.top;
  1268. };
  1269. // Walk through a block & children recursively, parsing string content
  1270. // into inline content where appropriate.
  1271. var processInlines = function(block) {
  1272. switch(block.t) {
  1273. case 'Paragraph':
  1274. case 'SetextHeader':
  1275. case 'ATXHeader':
  1276. block.inline_content =
  1277. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  1278. block.string_content = "";
  1279. break;
  1280. default:
  1281. break;
  1282. }
  1283. if (block.children) {
  1284. for (var i = 0; i < block.children.length; i++) {
  1285. this.processInlines(block.children[i]);
  1286. }
  1287. }
  1288. };
  1289. // The main parsing function. Returns a parsed document AST.
  1290. var parse = function(input) {
  1291. this.doc = makeBlock('Document', 1, 1);
  1292. this.tip = this.doc;
  1293. this.refmap = {};
  1294. var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/);
  1295. var len = lines.length;
  1296. for (var i = 0; i < len; i++) {
  1297. this.incorporateLine(lines[i], i+1);
  1298. }
  1299. while (this.tip) {
  1300. this.finalize(this.tip, len - 1);
  1301. }
  1302. this.processInlines(this.doc);
  1303. return this.doc;
  1304. };
  1305. // The DocParser object.
  1306. function DocParser(){
  1307. return {
  1308. doc: makeBlock('Document', 1, 1),
  1309. tip: this.doc,
  1310. refmap: {},
  1311. inlineParser: new InlineParser(),
  1312. breakOutOfLists: breakOutOfLists,
  1313. addLine: addLine,
  1314. addChild: addChild,
  1315. incorporateLine: incorporateLine,
  1316. finalize: finalize,
  1317. processInlines: processInlines,
  1318. parse: parse
  1319. };
  1320. }
  1321. // HTML RENDERER
  1322. // Helper function to produce content in a pair of HTML tags.
  1323. var inTags = function(tag, attribs, contents, selfclosing) {
  1324. var result = '<' + tag;
  1325. if (attribs) {
  1326. var i = 0;
  1327. var attrib;
  1328. while ((attrib = attribs[i]) !== undefined) {
  1329. result = result.concat(' ', attrib[0], '="', attrib[1], '"');
  1330. i++;
  1331. }
  1332. }
  1333. if (contents) {
  1334. result = result.concat('>', contents, '</', tag, '>');
  1335. } else if (selfclosing) {
  1336. result = result + ' />';
  1337. } else {
  1338. result = result.concat('></', tag, '>');
  1339. }
  1340. return result;
  1341. };
  1342. // Render an inline element as HTML.
  1343. var renderInline = function(inline) {
  1344. var attrs;
  1345. switch (inline.t) {
  1346. case 'Str':
  1347. return this.escape(inline.c);
  1348. case 'Softbreak':
  1349. return this.softbreak;
  1350. case 'Hardbreak':
  1351. return inTags('br',[],"",true) + '\n';
  1352. case 'Emph':
  1353. return inTags('em', [], this.renderInlines(inline.c));
  1354. case 'Strong':
  1355. return inTags('strong', [], this.renderInlines(inline.c));
  1356. case 'Html':
  1357. return inline.c;
  1358. case 'Entity':
  1359. return inline.c;
  1360. case 'Link':
  1361. attrs = [['href', this.escape(inline.destination, true)]];
  1362. if (inline.title) {
  1363. attrs.push(['title', this.escape(inline.title, true)]);
  1364. }
  1365. return inTags('a', attrs, this.renderInlines(inline.label));
  1366. case 'Image':
  1367. attrs = [['src', this.escape(inline.destination, true)],
  1368. ['alt', this.escape(this.renderInlines(inline.label))]];
  1369. if (inline.title) {
  1370. attrs.push(['title', this.escape(inline.title, true)]);
  1371. }
  1372. return inTags('img', attrs, "", true);
  1373. case 'Code':
  1374. return inTags('code', [], this.escape(inline.c));
  1375. default:
  1376. console.log("Unknown inline type " + inline.t);
  1377. return "";
  1378. }
  1379. };
  1380. // Render a list of inlines.
  1381. var renderInlines = function(inlines) {
  1382. var result = '';
  1383. for (var i=0; i < inlines.length; i++) {
  1384. result = result + this.renderInline(inlines[i]);
  1385. }
  1386. return result;
  1387. };
  1388. // Render a single block element.
  1389. var renderBlock = function(block, in_tight_list) {
  1390. var tag;
  1391. var attr;
  1392. var info_words;
  1393. switch (block.t) {
  1394. case 'Document':
  1395. var whole_doc = this.renderBlocks(block.children);
  1396. return (whole_doc === '' ? '' : whole_doc + '\n');
  1397. case 'Paragraph':
  1398. if (in_tight_list) {
  1399. return this.renderInlines(block.inline_content);
  1400. } else {
  1401. return inTags('p', [], this.renderInlines(block.inline_content));
  1402. }
  1403. break;
  1404. case 'BlockQuote':
  1405. var filling = this.renderBlocks(block.children);
  1406. return inTags('blockquote', [], filling === '' ? this.innersep :
  1407. this.innersep + this.renderBlocks(block.children) + this.innersep);
  1408. case 'ListItem':
  1409. return inTags('li', [], this.renderBlocks(block.children, in_tight_list).trim());
  1410. case 'List':
  1411. tag = block.list_data.type == 'Bullet' ? 'ul' : 'ol';
  1412. attr = (!block.list_data.start || block.list_data.start == 1) ?
  1413. [] : [['start', block.list_data.start.toString()]];
  1414. return inTags(tag, attr, this.innersep +
  1415. this.renderBlocks(block.children, block.tight) +
  1416. this.innersep);
  1417. case 'ATXHeader':
  1418. case 'SetextHeader':
  1419. tag = 'h' + block.level;
  1420. return inTags(tag, [], this.renderInlines(block.inline_content));
  1421. case 'IndentedCode':
  1422. return inTags('pre', [],
  1423. inTags('code', [], this.escape(block.string_content)));
  1424. case 'FencedCode':
  1425. info_words = block.info.split(/ +/);
  1426. attr = info_words.length === 0 || info_words[0].length === 0 ?
  1427. [] : [['class','language-' +
  1428. this.escape(info_words[0],true)]];
  1429. return inTags('pre', [],
  1430. inTags('code', attr, this.escape(block.string_content)));
  1431. case 'HtmlBlock':
  1432. return block.string_content;
  1433. case 'ReferenceDef':
  1434. return "";
  1435. case 'HorizontalRule':
  1436. return inTags('hr',[],"",true);
  1437. default:
  1438. console.log("Unknown block type " + block.t);
  1439. return "";
  1440. }
  1441. };
  1442. // Render a list of block elements, separated by this.blocksep.
  1443. var renderBlocks = function(blocks, in_tight_list) {
  1444. var result = [];
  1445. for (var i=0; i < blocks.length; i++) {
  1446. if (blocks[i].t !== 'ReferenceDef') {
  1447. result.push(this.renderBlock(blocks[i], in_tight_list));
  1448. }
  1449. }
  1450. return result.join(this.blocksep);
  1451. };
  1452. // The HtmlRenderer object.
  1453. function HtmlRenderer(){
  1454. return {
  1455. // default options:
  1456. blocksep: '\n', // space between blocks
  1457. innersep: '\n', // space between block container tag and contents
  1458. softbreak: '\n', // by default, soft breaks are rendered as newlines in HTML
  1459. // set to "<br />" to make them hard breaks
  1460. // set to " " if you want to ignore line wrapping in source
  1461. escape: function(s, preserve_entities) {
  1462. if (preserve_entities) {
  1463. return s.replace(/[&](?![#](x[a-f0-9]{1,8}|[0-9]{1,8});|[a-z][a-z0-9]{1,31};)/gi,'&amp;')
  1464. .replace(/[<]/g,'&lt;')
  1465. .replace(/[>]/g,'&gt;')
  1466. .replace(/["]/g,'&quot;');
  1467. } else {
  1468. return s.replace(/[&]/g,'&amp;')
  1469. .replace(/[<]/g,'&lt;')
  1470. .replace(/[>]/g,'&gt;')
  1471. .replace(/["]/g,'&quot;');
  1472. }
  1473. },
  1474. renderInline: renderInline,
  1475. renderInlines: renderInlines,
  1476. renderBlock: renderBlock,
  1477. renderBlocks: renderBlocks,
  1478. render: renderBlock
  1479. };
  1480. }
  1481. exports.DocParser = DocParser;
  1482. exports.HtmlRenderer = HtmlRenderer;
  1483. })(typeof exports === 'undefined' ? this.stmd = {} : exports);