aboutsummaryrefslogtreecommitdiff
path: root/js/stmd.js
blob: 287a0c912242d8c7a53fe65fe9fba3450f967294 (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 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())) {
  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 unescape(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 unescape(res.substr(1, res.length - 2));
  437. } else {
  438. res = this.match(reLinkDestination);
  439. if (res !== null) {
  440. return unescape(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[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() {
  672. var startpos = this.pos;
  673. var c = this.peek();
  674. if (!c) {
  675. return null;
  676. }
  677. var res;
  678. switch(c) {
  679. case '\n':
  680. case ' ':
  681. res = this.parseNewline();
  682. break;
  683. case '\\':
  684. res = this.parseBackslash();
  685. break;
  686. case '`':
  687. res = this.parseBackticks();
  688. break;
  689. case '*':
  690. case '_':
  691. res = this.parseEmphasis();
  692. break;
  693. case '[':
  694. res = this.parseLink();
  695. break;
  696. case '!':
  697. res = this.parseImage();
  698. break;
  699. case '<':
  700. res = this.parseAutolink() || this.parseHtmlTag();
  701. break;
  702. case '&':
  703. res = this.parseEntity();
  704. break;
  705. default:
  706. res = this.parseString();
  707. break;
  708. }
  709. if (res === null) {
  710. this.pos += 1;
  711. res = [{t: 'Str', c: c}];
  712. }
  713. return res;
  714. };
  715. // Parse s as a list of inlines, using refmap to resolve references.
  716. var parseInlines = function(s, refmap) {
  717. this.subject = s;
  718. this.pos = 0;
  719. this.refmap = refmap || {};
  720. this.last_emphasis_closer = { '*': s.length, '_': s.length };
  721. var inlines = [];
  722. var next_inline;
  723. while ((next_inline = this.parseInline())) {
  724. Array.prototype.push.apply(inlines, next_inline);
  725. }
  726. return inlines;
  727. };
  728. // The InlineParser object.
  729. function InlineParser(){
  730. return {
  731. subject: '',
  732. label_nest_level: 0, // used by parseLinkLabel method
  733. last_emphasis_closer: null, // used by parseEmphasis method
  734. pos: 0,
  735. refmap: {},
  736. match: match,
  737. peek: peek,
  738. spnl: spnl,
  739. parseBackticks: parseBackticks,
  740. parseBackslash: parseBackslash,
  741. parseAutolink: parseAutolink,
  742. parseHtmlTag: parseHtmlTag,
  743. scanDelims: scanDelims,
  744. parseEmphasis: parseEmphasis,
  745. parseLinkTitle: parseLinkTitle,
  746. parseLinkDestination: parseLinkDestination,
  747. parseLinkLabel: parseLinkLabel,
  748. parseLink: parseLink,
  749. parseEntity: parseEntity,
  750. parseString: parseString,
  751. parseNewline: parseNewline,
  752. parseImage: parseImage,
  753. parseReference: parseReference,
  754. parseInline: parseInline,
  755. parse: parseInlines
  756. };
  757. }
  758. // DOC PARSER
  759. // These are methods of a DocParser object, defined below.
  760. var makeBlock = function(tag, start_line, start_column) {
  761. return { t: tag,
  762. open: true,
  763. last_line_blank: false,
  764. start_line: start_line,
  765. start_column: start_column,
  766. end_line: start_line,
  767. children: [],
  768. parent: null,
  769. // string_content is formed by concatenating strings, in finalize:
  770. string_content: "",
  771. strings: [],
  772. inline_content: []
  773. };
  774. };
  775. // Returns true if parent block can contain child block.
  776. var canContain = function(parent_type, child_type) {
  777. return ( parent_type == 'Document' ||
  778. parent_type == 'BlockQuote' ||
  779. parent_type == 'ListItem' ||
  780. (parent_type == 'List' && child_type == 'ListItem') );
  781. };
  782. // Returns true if block type can accept lines of text.
  783. var acceptsLines = function(block_type) {
  784. return ( block_type == 'Paragraph' ||
  785. block_type == 'IndentedCode' ||
  786. block_type == 'FencedCode' );
  787. };
  788. // Returns true if block ends with a blank line, descending if needed
  789. // into lists and sublists.
  790. var endsWithBlankLine = function(block) {
  791. if (block.last_line_blank) {
  792. return true;
  793. }
  794. if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) {
  795. return endsWithBlankLine(block.children[block.children.length - 1]);
  796. } else {
  797. return false;
  798. }
  799. };
  800. // Break out of all containing lists, resetting the tip of the
  801. // document to the parent of the highest list, and finalizing
  802. // all the lists. (This is used to implement the "two blank lines
  803. // break of of all lists" feature.)
  804. var breakOutOfLists = function(block, line_number) {
  805. var b = block;
  806. var last_list = null;
  807. do {
  808. if (b.t === 'List') {
  809. last_list = b;
  810. }
  811. b = b.parent;
  812. } while (b);
  813. if (last_list) {
  814. while (block != last_list) {
  815. this.finalize(block, line_number);
  816. block = block.parent;
  817. }
  818. this.finalize(last_list, line_number);
  819. this.tip = last_list.parent;
  820. }
  821. };
  822. // Add a line to the block at the tip. We assume the tip
  823. // can accept lines -- that check should be done before calling this.
  824. var addLine = function(ln, offset) {
  825. var s = ln.slice(offset);
  826. if (!(this.tip.open)) {
  827. throw({ msg: "Attempted to add line (" + ln + ") to closed container." });
  828. }
  829. this.tip.strings.push(s);
  830. };
  831. // Add block of type tag as a child of the tip. If the tip can't
  832. // accept children, close and finalize it and try its parent,
  833. // and so on til we find a block that can accept children.
  834. var addChild = function(tag, line_number, offset) {
  835. while (!canContain(this.tip.t, tag)) {
  836. this.finalize(this.tip, line_number);
  837. }
  838. var column_number = offset + 1; // offset 0 = column 1
  839. var newBlock = makeBlock(tag, line_number, column_number);
  840. this.tip.children.push(newBlock);
  841. newBlock.parent = this.tip;
  842. this.tip = newBlock;
  843. return newBlock;
  844. };
  845. // Parse a list marker and return data on the marker (type,
  846. // start, delimiter, bullet character, padding) or null.
  847. var parseListMarker = function(ln, offset) {
  848. var rest = ln.slice(offset);
  849. var match;
  850. var spaces_after_marker;
  851. var data = {};
  852. if (rest.match(reHrule)) {
  853. return null;
  854. }
  855. if ((match = rest.match(/^[*+-]( +|$)/))) {
  856. spaces_after_marker = match[1].length;
  857. data.type = 'Bullet';
  858. data.bullet_char = match[0][0];
  859. } else if ((match = rest.match(/^(\d+)([.)])( +|$)/))) {
  860. spaces_after_marker = match[3].length;
  861. data.type = 'Ordered';
  862. data.start = parseInt(match[1]);
  863. data.delimiter = match[2];
  864. } else {
  865. return null;
  866. }
  867. var blank_item = match[0].length === rest.length;
  868. if (spaces_after_marker >= 5 ||
  869. spaces_after_marker < 1 ||
  870. blank_item) {
  871. data.padding = match[0].length - spaces_after_marker + 1;
  872. } else {
  873. data.padding = match[0].length;
  874. }
  875. return data;
  876. };
  877. // Returns true if the two list items are of the same type,
  878. // with the same delimiter and bullet character. This is used
  879. // in agglomerating list items into lists.
  880. var listsMatch = function(list_data, item_data) {
  881. return (list_data.type === item_data.type &&
  882. list_data.delimiter === item_data.delimiter &&
  883. list_data.bullet_char === item_data.bullet_char);
  884. };
  885. // Analyze a line of text and update the document appropriately.
  886. // We parse markdown text by calling this on each line of input,
  887. // then finalizing the document.
  888. var incorporateLine = function(ln, line_number) {
  889. var all_matched = true;
  890. var last_child;
  891. var first_nonspace;
  892. var offset = 0;
  893. var match;
  894. var data;
  895. var blank;
  896. var indent;
  897. var last_matched_container;
  898. var i;
  899. var CODE_INDENT = 4;
  900. var container = this.doc;
  901. var oldtip = this.tip;
  902. // Convert tabs to spaces:
  903. ln = detabLine(ln);
  904. // For each containing block, try to parse the associated line start.
  905. // Bail out on failure: container will point to the last matching block.
  906. // Set all_matched to false if not all containers match.
  907. while (container.children.length > 0) {
  908. last_child = container.children[container.children.length - 1];
  909. if (!last_child.open) {
  910. break;
  911. }
  912. container = last_child;
  913. match = matchAt(/[^ ]/, ln, offset);
  914. if (match === null) {
  915. first_nonspace = ln.length;
  916. blank = true;
  917. } else {
  918. first_nonspace = match;
  919. blank = false;
  920. }
  921. indent = first_nonspace - offset;
  922. switch (container.t) {
  923. case 'BlockQuote':
  924. var matched = indent <= 3 && ln[first_nonspace] === '>';
  925. if (matched) {
  926. offset = first_nonspace + 1;
  927. if (ln[offset] === ' ') {
  928. offset++;
  929. }
  930. } else {
  931. all_matched = false;
  932. }
  933. break;
  934. case 'ListItem':
  935. if (indent >= container.list_data.marker_offset +
  936. container.list_data.padding) {
  937. offset += container.list_data.marker_offset +
  938. container.list_data.padding;
  939. } else if (blank) {
  940. offset = first_nonspace;
  941. } else {
  942. all_matched = false;
  943. }
  944. break;
  945. case 'IndentedCode':
  946. if (indent >= CODE_INDENT) {
  947. offset += CODE_INDENT;
  948. } else if (blank) {
  949. offset = first_nonspace;
  950. } else {
  951. all_matched = false;
  952. }
  953. break;
  954. case 'ATXHeader':
  955. case 'SetextHeader':
  956. case 'HorizontalRule':
  957. // a header can never container > 1 line, so fail to match:
  958. all_matched = false;
  959. break;
  960. case 'FencedCode':
  961. // skip optional spaces of fence offset
  962. i = container.fence_offset;
  963. while (i > 0 && ln[offset] === ' ') {
  964. offset++;
  965. i--;
  966. }
  967. break;
  968. case 'HtmlBlock':
  969. if (blank) {
  970. all_matched = false;
  971. }
  972. break;
  973. case 'Paragraph':
  974. if (blank) {
  975. container.last_line_blank = true;
  976. all_matched = false;
  977. }
  978. break;
  979. default:
  980. }
  981. if (!all_matched) {
  982. container = container.parent; // back up to last matching block
  983. break;
  984. }
  985. }
  986. last_matched_container = container;
  987. // This function is used to finalize and close any unmatched
  988. // blocks. We aren't ready to do this now, because we might
  989. // have a lazy paragraph continuation, in which case we don't
  990. // want to close unmatched blocks. So we store this closure for
  991. // use later, when we have more information.
  992. var closeUnmatchedBlocks = function(mythis) {
  993. // finalize any blocks not matched
  994. while (!already_done && oldtip != last_matched_container) {
  995. mythis.finalize(oldtip, line_number);
  996. oldtip = oldtip.parent;
  997. }
  998. var already_done = true;
  999. };
  1000. // Check to see if we've hit 2nd blank line; if so break out of list:
  1001. if (blank && container.last_line_blank) {
  1002. this.breakOutOfLists(container, line_number);
  1003. }
  1004. // Unless last matched container is a code block, try new container starts,
  1005. // adding children to the last matched container:
  1006. while (container.t != 'FencedCode' &&
  1007. container.t != 'IndentedCode' &&
  1008. container.t != 'HtmlBlock' &&
  1009. // this is a little performance optimization:
  1010. matchAt(/^[ #`~*+_=<>0-9-]/,ln,offset) !== null) {
  1011. match = matchAt(/[^ ]/, ln, offset);
  1012. if (match === null) {
  1013. first_nonspace = ln.length;
  1014. blank = true;
  1015. } else {
  1016. first_nonspace = match;
  1017. blank = false;
  1018. }
  1019. indent = first_nonspace - offset;
  1020. if (indent >= CODE_INDENT) {
  1021. // indented code
  1022. if (this.tip.t != 'Paragraph' && !blank) {
  1023. offset += CODE_INDENT;
  1024. closeUnmatchedBlocks(this);
  1025. container = this.addChild('IndentedCode', line_number, offset);
  1026. } else { // indent > 4 in a lazy paragraph continuation
  1027. break;
  1028. }
  1029. } else if (ln[first_nonspace] === '>') {
  1030. // blockquote
  1031. offset = first_nonspace + 1;
  1032. // optional following space
  1033. if (ln[offset] === ' ') {
  1034. offset++;
  1035. }
  1036. closeUnmatchedBlocks(this);
  1037. container = this.addChild('BlockQuote', line_number, offset);
  1038. } else if ((match = ln.slice(first_nonspace).match(/^#{1,6}(?: +|$)/))) {
  1039. // ATX header
  1040. offset = first_nonspace + match[0].length;
  1041. closeUnmatchedBlocks(this);
  1042. container = this.addChild('ATXHeader', line_number, first_nonspace);
  1043. container.level = match[0].trim().length; // number of #s
  1044. // remove trailing ###s:
  1045. container.strings =
  1046. [ln.slice(offset).replace(/(?:(\\#) *#*| *#+) *$/,'$1')];
  1047. break;
  1048. } else if ((match = ln.slice(first_nonspace).match(/^`{3,}(?!.*`)|^~{3,}(?!.*~)/))) {
  1049. // fenced code block
  1050. var fence_length = match[0].length;
  1051. closeUnmatchedBlocks(this);
  1052. container = this.addChild('FencedCode', line_number, first_nonspace);
  1053. container.fence_length = fence_length;
  1054. container.fence_char = match[0][0];
  1055. container.fence_offset = first_nonspace - offset;
  1056. offset = first_nonspace + fence_length;
  1057. break;
  1058. } else if (matchAt(reHtmlBlockOpen, ln, first_nonspace) !== null) {
  1059. // html block
  1060. closeUnmatchedBlocks(this);
  1061. container = this.addChild('HtmlBlock', line_number, first_nonspace);
  1062. // note, we don't adjust offset because the tag is part of the text
  1063. break;
  1064. } else if (container.t == 'Paragraph' &&
  1065. container.strings.length === 1 &&
  1066. ((match = ln.slice(first_nonspace).match(/^(?:=+|-+) *$/)))) {
  1067. // setext header line
  1068. closeUnmatchedBlocks(this);
  1069. container.t = 'SetextHeader'; // convert Paragraph to SetextHeader
  1070. container.level = match[0][0] === '=' ? 1 : 2;
  1071. offset = ln.length;
  1072. } else if (matchAt(reHrule, ln, first_nonspace) !== null) {
  1073. // hrule
  1074. closeUnmatchedBlocks(this);
  1075. container = this.addChild('HorizontalRule', line_number, first_nonspace);
  1076. offset = ln.length - 1;
  1077. break;
  1078. } else if ((data = parseListMarker(ln, first_nonspace))) {
  1079. // list item
  1080. closeUnmatchedBlocks(this);
  1081. data.marker_offset = indent;
  1082. offset = first_nonspace + data.padding;
  1083. // add the list if needed
  1084. if (container.t !== 'List' ||
  1085. !(listsMatch(container.list_data, data))) {
  1086. container = this.addChild('List', line_number, first_nonspace);
  1087. container.list_data = data;
  1088. }
  1089. // add the list item
  1090. container = this.addChild('ListItem', line_number, first_nonspace);
  1091. container.list_data = data;
  1092. } else {
  1093. break;
  1094. }
  1095. if (acceptsLines(container.t)) {
  1096. // if it's a line container, it can't contain other containers
  1097. break;
  1098. }
  1099. }
  1100. // What remains at the offset is a text line. Add the text to the
  1101. // appropriate container.
  1102. match = matchAt(/[^ ]/, ln, offset);
  1103. if (match === null) {
  1104. first_nonspace = ln.length;
  1105. blank = true;
  1106. } else {
  1107. first_nonspace = match;
  1108. blank = false;
  1109. }
  1110. indent = first_nonspace - offset;
  1111. // First check for a lazy paragraph continuation:
  1112. if (this.tip !== last_matched_container &&
  1113. !blank &&
  1114. this.tip.t == 'Paragraph' &&
  1115. this.tip.strings.length > 0) {
  1116. // lazy paragraph continuation
  1117. this.last_line_blank = false;
  1118. this.addLine(ln, offset);
  1119. } else { // not a lazy continuation
  1120. // finalize any blocks not matched
  1121. closeUnmatchedBlocks(this);
  1122. // Block quote lines are never blank as they start with >
  1123. // and we don't count blanks in fenced code for purposes of tight/loose
  1124. // lists or breaking out of lists. We also don't set last_line_blank
  1125. // on an empty list item.
  1126. container.last_line_blank = blank &&
  1127. !(container.t == 'BlockQuote' ||
  1128. container.t == 'FencedCode' ||
  1129. (container.t == 'ListItem' &&
  1130. container.children.length === 0 &&
  1131. container.start_line == line_number));
  1132. var cont = container;
  1133. while (cont.parent) {
  1134. cont.parent.last_line_blank = false;
  1135. cont = cont.parent;
  1136. }
  1137. switch (container.t) {
  1138. case 'IndentedCode':
  1139. case 'HtmlBlock':
  1140. this.addLine(ln, offset);
  1141. break;
  1142. case 'FencedCode':
  1143. // check for closing code fence:
  1144. match = (indent <= 3 &&
  1145. ln[first_nonspace] == container.fence_char &&
  1146. ln.slice(first_nonspace).match(/^(?:`{3,}|~{3,})(?= *$)/));
  1147. if (match && match[0].length >= container.fence_length) {
  1148. // don't add closing fence to container; instead, close it:
  1149. this.finalize(container, line_number);
  1150. } else {
  1151. this.addLine(ln, offset);
  1152. }
  1153. break;
  1154. case 'ATXHeader':
  1155. case 'SetextHeader':
  1156. case 'HorizontalRule':
  1157. // nothing to do; we already added the contents.
  1158. break;
  1159. default:
  1160. if (acceptsLines(container.t)) {
  1161. this.addLine(ln, first_nonspace);
  1162. } else if (blank) {
  1163. // do nothing
  1164. } else if (container.t != 'HorizontalRule' &&
  1165. container.t != 'SetextHeader') {
  1166. // create paragraph container for line
  1167. container = this.addChild('Paragraph', line_number, first_nonspace);
  1168. this.addLine(ln, first_nonspace);
  1169. } else {
  1170. console.log("Line " + line_number.toString() +
  1171. " with container type " + container.t +
  1172. " did not match any condition.");
  1173. }
  1174. }
  1175. }
  1176. };
  1177. // Finalize a block. Close it and do any necessary postprocessing,
  1178. // e.g. creating string_content from strings, setting the 'tight'
  1179. // or 'loose' status of a list, and parsing the beginnings
  1180. // of paragraphs for reference definitions. Reset the tip to the
  1181. // parent of the closed block.
  1182. var finalize = function(block, line_number) {
  1183. var pos;
  1184. // don't do anything if the block is already closed
  1185. if (!block.open) {
  1186. return 0;
  1187. }
  1188. block.open = false;
  1189. if (line_number > block.start_line) {
  1190. block.end_line = line_number - 1;
  1191. } else {
  1192. block.end_line = line_number;
  1193. }
  1194. switch (block.t) {
  1195. case 'Paragraph':
  1196. block.string_content = block.strings.join('\n').replace(/^ */m,'');
  1197. // try parsing the beginning as link reference definitions:
  1198. while (block.string_content[0] === '[' &&
  1199. (pos = this.inlineParser.parseReference(block.string_content,
  1200. this.refmap))) {
  1201. block.string_content = block.string_content.slice(pos);
  1202. if (isBlank(block.string_content)) {
  1203. block.t = 'ReferenceDef';
  1204. break;
  1205. }
  1206. }
  1207. break;
  1208. case 'ATXHeader':
  1209. case 'SetextHeader':
  1210. case 'HtmlBlock':
  1211. block.string_content = block.strings.join('\n');
  1212. break;
  1213. case 'IndentedCode':
  1214. block.string_content = block.strings.join('\n').replace(/(\n *)*$/,'\n');
  1215. break;
  1216. case 'FencedCode':
  1217. // first line becomes info string
  1218. block.info = unescape(block.strings[0].trim());
  1219. if (block.strings.length == 1) {
  1220. block.string_content = '';
  1221. } else {
  1222. block.string_content = block.strings.slice(1).join('\n') + '\n';
  1223. }
  1224. break;
  1225. case 'List':
  1226. block.tight = true; // tight by default
  1227. var numitems = block.children.length;
  1228. var i = 0;
  1229. while (i < numitems) {
  1230. var item = block.children[i];
  1231. // check for non-final list item ending with blank line:
  1232. var last_item = i == numitems - 1;
  1233. if (endsWithBlankLine(item) && !last_item) {
  1234. block.tight = false;
  1235. break;
  1236. }
  1237. // recurse into children of list item, to see if there are
  1238. // spaces between any of them:
  1239. var numsubitems = item.children.length;
  1240. var j = 0;
  1241. while (j < numsubitems) {
  1242. var subitem = item.children[j];
  1243. var last_subitem = j == numsubitems - 1;
  1244. if (endsWithBlankLine(subitem) && !(last_item && last_subitem)) {
  1245. block.tight = false;
  1246. break;
  1247. }
  1248. j++;
  1249. }
  1250. i++;
  1251. }
  1252. break;
  1253. default:
  1254. break;
  1255. }
  1256. this.tip = block.parent || this.top;
  1257. };
  1258. // Walk through a block & children recursively, parsing string content
  1259. // into inline content where appropriate.
  1260. var processInlines = function(block) {
  1261. switch(block.t) {
  1262. case 'Paragraph':
  1263. case 'SetextHeader':
  1264. case 'ATXHeader':
  1265. block.inline_content =
  1266. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  1267. block.string_content = "";
  1268. break;
  1269. default:
  1270. break;
  1271. }
  1272. if (block.children) {
  1273. for (var i = 0; i < block.children.length; i++) {
  1274. this.processInlines(block.children[i]);
  1275. }
  1276. }
  1277. };
  1278. // The main parsing function. Returns a parsed document AST.
  1279. var parse = function(input) {
  1280. this.doc = makeBlock('Document', 1, 1);
  1281. this.tip = this.doc;
  1282. this.refmap = {};
  1283. var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/);
  1284. var len = lines.length;
  1285. for (var i = 0; i < len; i++) {
  1286. this.incorporateLine(lines[i], i+1);
  1287. }
  1288. while (this.tip) {
  1289. this.finalize(this.tip, len - 1);
  1290. }
  1291. this.processInlines(this.doc);
  1292. return this.doc;
  1293. };
  1294. // The DocParser object.
  1295. function DocParser(){
  1296. return {
  1297. doc: makeBlock('Document', 1, 1),
  1298. tip: this.doc,
  1299. refmap: {},
  1300. inlineParser: new InlineParser(),
  1301. breakOutOfLists: breakOutOfLists,
  1302. addLine: addLine,
  1303. addChild: addChild,
  1304. incorporateLine: incorporateLine,
  1305. finalize: finalize,
  1306. processInlines: processInlines,
  1307. parse: parse
  1308. };
  1309. }
  1310. // HTML RENDERER
  1311. // Helper function to produce content in a pair of HTML tags.
  1312. var inTags = function(tag, attribs, contents, selfclosing) {
  1313. var result = '<' + tag;
  1314. if (attribs) {
  1315. var i = 0;
  1316. var attrib;
  1317. while ((attrib = attribs[i]) !== undefined) {
  1318. result = result.concat(' ', attrib[0], '="', attrib[1], '"');
  1319. i++;
  1320. }
  1321. }
  1322. if (contents) {
  1323. result = result.concat('>', contents, '</', tag, '>');
  1324. } else if (selfclosing) {
  1325. result = result + ' />';
  1326. } else {
  1327. result = result.concat('></', tag, '>');
  1328. }
  1329. return result;
  1330. };
  1331. // Render an inline element as HTML.
  1332. var renderInline = function(inline) {
  1333. var attrs;
  1334. switch (inline.t) {
  1335. case 'Str':
  1336. return this.escape(inline.c);
  1337. case 'Softbreak':
  1338. return this.softbreak;
  1339. case 'Hardbreak':
  1340. return inTags('br',[],"",true) + '\n';
  1341. case 'Emph':
  1342. return inTags('em', [], this.renderInlines(inline.c));
  1343. case 'Strong':
  1344. return inTags('strong', [], this.renderInlines(inline.c));
  1345. case 'Html':
  1346. return inline.c;
  1347. case 'Entity':
  1348. return inline.c;
  1349. case 'Link':
  1350. attrs = [['href', this.escape(inline.destination, true)]];
  1351. if (inline.title) {
  1352. attrs.push(['title', this.escape(inline.title, true)]);
  1353. }
  1354. return inTags('a', attrs, this.renderInlines(inline.label));
  1355. case 'Image':
  1356. attrs = [['src', this.escape(inline.destination, true)],
  1357. ['alt', this.escape(this.renderInlines(inline.label))]];
  1358. if (inline.title) {
  1359. attrs.push(['title', this.escape(inline.title, true)]);
  1360. }
  1361. return inTags('img', attrs, "", true);
  1362. case 'Code':
  1363. return inTags('code', [], this.escape(inline.c));
  1364. default:
  1365. console.log("Unknown inline type " + inline.t);
  1366. return "";
  1367. }
  1368. };
  1369. // Render a list of inlines.
  1370. var renderInlines = function(inlines) {
  1371. var result = '';
  1372. for (var i=0; i < inlines.length; i++) {
  1373. result = result + this.renderInline(inlines[i]);
  1374. }
  1375. return result;
  1376. };
  1377. // Render a single block element.
  1378. var renderBlock = function(block, in_tight_list) {
  1379. var tag;
  1380. var attr;
  1381. var info_words;
  1382. switch (block.t) {
  1383. case 'Document':
  1384. var whole_doc = this.renderBlocks(block.children);
  1385. return (whole_doc === '' ? '' : whole_doc + '\n');
  1386. case 'Paragraph':
  1387. if (in_tight_list) {
  1388. return this.renderInlines(block.inline_content);
  1389. } else {
  1390. return inTags('p', [], this.renderInlines(block.inline_content));
  1391. }
  1392. break;
  1393. case 'BlockQuote':
  1394. var filling = this.renderBlocks(block.children);
  1395. return inTags('blockquote', [], filling === '' ? this.innersep :
  1396. this.innersep + this.renderBlocks(block.children) + this.innersep);
  1397. case 'ListItem':
  1398. return inTags('li', [], this.renderBlocks(block.children, in_tight_list).trim());
  1399. case 'List':
  1400. tag = block.list_data.type == 'Bullet' ? 'ul' : 'ol';
  1401. attr = (!block.list_data.start || block.list_data.start == 1) ?
  1402. [] : [['start', block.list_data.start.toString()]];
  1403. return inTags(tag, attr, this.innersep +
  1404. this.renderBlocks(block.children, block.tight) +
  1405. this.innersep);
  1406. case 'ATXHeader':
  1407. case 'SetextHeader':
  1408. tag = 'h' + block.level;
  1409. return inTags(tag, [], this.renderInlines(block.inline_content));
  1410. case 'IndentedCode':
  1411. return inTags('pre', [],
  1412. inTags('code', [], this.escape(block.string_content)));
  1413. case 'FencedCode':
  1414. info_words = block.info.split(/ +/);
  1415. attr = info_words.length === 0 || info_words[0].length === 0 ?
  1416. [] : [['class','language-' +
  1417. this.escape(info_words[0],true)]];
  1418. return inTags('pre', [],
  1419. inTags('code', attr, this.escape(block.string_content)));
  1420. case 'HtmlBlock':
  1421. return block.string_content;
  1422. case 'ReferenceDef':
  1423. return "";
  1424. case 'HorizontalRule':
  1425. return inTags('hr',[],"",true);
  1426. default:
  1427. console.log("Unknown block type " + block.t);
  1428. return "";
  1429. }
  1430. };
  1431. // Render a list of block elements, separated by this.blocksep.
  1432. var renderBlocks = function(blocks, in_tight_list) {
  1433. var result = [];
  1434. for (var i=0; i < blocks.length; i++) {
  1435. if (blocks[i].t !== 'ReferenceDef') {
  1436. result.push(this.renderBlock(blocks[i], in_tight_list));
  1437. }
  1438. }
  1439. return result.join(this.blocksep);
  1440. };
  1441. // The HtmlRenderer object.
  1442. function HtmlRenderer(){
  1443. return {
  1444. // default options:
  1445. blocksep: '\n', // space between blocks
  1446. innersep: '\n', // space between block container tag and contents
  1447. softbreak: '\n', // by default, soft breaks are rendered as newlines in HTML
  1448. // set to "<br />" to make them hard breaks
  1449. // set to " " if you want to ignore line wrapping in source
  1450. escape: function(s, preserve_entities) {
  1451. if (preserve_entities) {
  1452. return s.replace(/[&](?![#](x[a-f0-9]{1,8}|[0-9]{1,8});|[a-z][a-z0-9]{1,31};)/gi,'&amp;')
  1453. .replace(/[<]/g,'&lt;')
  1454. .replace(/[>]/g,'&gt;')
  1455. .replace(/["]/g,'&quot;');
  1456. } else {
  1457. return s.replace(/[&]/g,'&amp;')
  1458. .replace(/[<]/g,'&lt;')
  1459. .replace(/[>]/g,'&gt;')
  1460. .replace(/["]/g,'&quot;');
  1461. }
  1462. },
  1463. renderInline: renderInline,
  1464. renderInlines: renderInlines,
  1465. renderBlock: renderBlock,
  1466. renderBlocks: renderBlocks,
  1467. render: renderBlock
  1468. };
  1469. }
  1470. exports.DocParser = DocParser;
  1471. exports.HtmlRenderer = HtmlRenderer;
  1472. })(typeof exports === 'undefined' ? this.stmd = {} : exports);