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