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