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