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