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