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