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