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