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