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