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