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