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