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