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