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