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