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