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