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