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