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