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