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