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