aboutsummaryrefslogtreecommitdiff
path: root/js/lib/index.js
blob: 55db200de9aee073b4f8c5e50b48cc30f8827f2e (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. var fromCodePoint = require('./from-code-point.js');
  11. var entityToChar = require('./html5-entities.js').entityToChar;
  12. // Constants for character codes:
  13. var C_NEWLINE = 10;
  14. var C_SPACE = 32;
  15. var C_ASTERISK = 42;
  16. var C_UNDERSCORE = 95;
  17. var C_BACKTICK = 96;
  18. var C_OPEN_BRACKET = 91;
  19. var C_CLOSE_BRACKET = 93;
  20. var C_LESSTHAN = 60;
  21. var C_GREATERTHAN = 62;
  22. var C_BANG = 33;
  23. var C_BACKSLASH = 92;
  24. var C_AMPERSAND = 38;
  25. var C_OPEN_PAREN = 40;
  26. var C_COLON = 58;
  27. // Some regexps used in inline parser:
  28. var ESCAPABLE = '[!"#$%&\'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]';
  29. var ESCAPED_CHAR = '\\\\' + ESCAPABLE;
  30. var IN_DOUBLE_QUOTES = '"(' + ESCAPED_CHAR + '|[^"\\x00])*"';
  31. var IN_SINGLE_QUOTES = '\'(' + ESCAPED_CHAR + '|[^\'\\x00])*\'';
  32. var IN_PARENS = '\\((' + ESCAPED_CHAR + '|[^)\\x00])*\\)';
  33. var REG_CHAR = '[^\\\\()\\x00-\\x20]';
  34. var IN_PARENS_NOSP = '\\((' + REG_CHAR + '|' + ESCAPED_CHAR + ')*\\)';
  35. var TAGNAME = '[A-Za-z][A-Za-z0-9]*';
  36. 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)';
  37. var ATTRIBUTENAME = '[a-zA-Z_:][a-zA-Z0-9:._-]*';
  38. var UNQUOTEDVALUE = "[^\"'=<>`\\x00-\\x20]+";
  39. var SINGLEQUOTEDVALUE = "'[^']*'";
  40. var DOUBLEQUOTEDVALUE = '"[^"]*"';
  41. var ATTRIBUTEVALUE = "(?:" + UNQUOTEDVALUE + "|" + SINGLEQUOTEDVALUE + "|" + DOUBLEQUOTEDVALUE + ")";
  42. var ATTRIBUTEVALUESPEC = "(?:" + "\\s*=" + "\\s*" + ATTRIBUTEVALUE + ")";
  43. var ATTRIBUTE = "(?:" + "\\s+" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC + "?)";
  44. var OPENTAG = "<" + TAGNAME + ATTRIBUTE + "*" + "\\s*/?>";
  45. var CLOSETAG = "</" + TAGNAME + "\\s*[>]";
  46. var OPENBLOCKTAG = "<" + BLOCKTAGNAME + ATTRIBUTE + "*" + "\\s*/?>";
  47. var CLOSEBLOCKTAG = "</" + BLOCKTAGNAME + "\\s*[>]";
  48. var HTMLCOMMENT = "<!--([^-]+|[-][^-]+)*-->";
  49. var PROCESSINGINSTRUCTION = "[<][?].*?[?][>]";
  50. var DECLARATION = "<![A-Z]+" + "\\s+[^>]*>";
  51. var CDATA = "<!\\[CDATA\\[([^\\]]+|\\][^\\]]|\\]\\][^>])*\\]\\]>";
  52. var HTMLTAG = "(?:" + OPENTAG + "|" + CLOSETAG + "|" + HTMLCOMMENT + "|" +
  53. PROCESSINGINSTRUCTION + "|" + DECLARATION + "|" + CDATA + ")";
  54. var HTMLBLOCKOPEN = "<(?:" + BLOCKTAGNAME + "[\\s/>]" + "|" +
  55. "/" + BLOCKTAGNAME + "[\\s>]" + "|" + "[?!])";
  56. var ENTITY = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});";
  57. var reHtmlTag = new RegExp('^' + HTMLTAG, 'i');
  58. var reHtmlBlockOpen = new RegExp('^' + HTMLBLOCKOPEN, 'i');
  59. var reLinkTitle = new RegExp(
  60. '^(?:"(' + ESCAPED_CHAR + '|[^"\\x00])*"' +
  61. '|' +
  62. '\'(' + ESCAPED_CHAR + '|[^\'\\x00])*\'' +
  63. '|' +
  64. '\\((' + ESCAPED_CHAR + '|[^)\\x00])*\\))');
  65. var reLinkDestinationBraces = new RegExp(
  66. '^(?:[<](?:[^<>\\n\\\\\\x00]' + '|' + ESCAPED_CHAR + '|' + '\\\\)*[>])');
  67. var reLinkDestination = new RegExp(
  68. '^(?:' + REG_CHAR + '+|' + ESCAPED_CHAR + '|' + IN_PARENS_NOSP + ')*');
  69. var reEscapable = new RegExp(ESCAPABLE);
  70. var reAllEscapedChar = new RegExp('\\\\(' + ESCAPABLE + ')', 'g');
  71. var reEscapedChar = new RegExp('^\\\\(' + ESCAPABLE + ')');
  72. var reAllTab = /\t/g;
  73. var reHrule = /^(?:(?:\* *){3,}|(?:_ *){3,}|(?:- *){3,}) *$/;
  74. var reEntityHere = new RegExp('^' + ENTITY, 'i');
  75. var reEntity = new RegExp(ENTITY, 'gi');
  76. // Matches a character with a special meaning in markdown,
  77. // or a string of non-special characters. Note: we match
  78. // clumps of _ or * or `, because they need to be handled in groups.
  79. var reMain = /^(?:[_*`\n]+|[\[\]\\!<&*_]|(?: *[^\n `\[\]\\!<&*_]+)+|[ \n]+)/m;
  80. // Replace entities and backslash escapes with literal characters.
  81. var unescapeEntBS = function(s) {
  82. return s.replace(reAllEscapedChar, '$1')
  83. .replace(reEntity, entityToChar);
  84. };
  85. // Returns true if string contains only space characters.
  86. var isBlank = function(s) {
  87. return /^\s*$/.test(s);
  88. };
  89. // Normalize reference label: collapse internal whitespace
  90. // to single space, remove leading/trailing whitespace, case fold.
  91. var normalizeReference = function(s) {
  92. return s.trim()
  93. .replace(/\s+/,' ')
  94. .toUpperCase();
  95. };
  96. // Attempt to match a regex in string s at offset offset.
  97. // Return index of match or null.
  98. var matchAt = function(re, s, offset) {
  99. var res = s.slice(offset).match(re);
  100. if (res) {
  101. return offset + res.index;
  102. } else {
  103. return null;
  104. }
  105. };
  106. // Convert tabs to spaces on each line using a 4-space tab stop.
  107. var detabLine = function(text) {
  108. if (text.indexOf('\t') == -1) {
  109. return text;
  110. } else {
  111. var lastStop = 0;
  112. return text.replace(reAllTab, function(match, offset) {
  113. var result = ' '.slice((offset - lastStop) % 4);
  114. lastStop = offset + 1;
  115. return result;
  116. });
  117. }
  118. };
  119. // INLINE PARSER
  120. // These are methods of an InlineParser object, defined below.
  121. // An InlineParser keeps track of a subject (a string to be
  122. // parsed) and a position in that subject.
  123. // If re matches at current position in the subject, advance
  124. // position in subject and return the match; otherwise return null.
  125. var match = function(re) {
  126. var match = re.exec(this.subject.slice(this.pos));
  127. if (match) {
  128. this.pos += match.index + match[0].length;
  129. return match[0];
  130. } else {
  131. return null;
  132. }
  133. };
  134. // Returns the code for the character at the current subject position, or -1
  135. // there are no more characters.
  136. var peek = function() {
  137. if (this.pos < this.subject.length) {
  138. return this.subject.charCodeAt(this.pos);
  139. } else {
  140. return -1;
  141. }
  142. };
  143. // Parse zero or more space characters, including at most one newline
  144. var spnl = function() {
  145. this.match(/^ *(?:\n *)?/);
  146. return 1;
  147. };
  148. // All of the parsers below try to match something at the current position
  149. // in the subject. If they succeed in matching anything, they
  150. // return the inline matched, advancing the subject.
  151. // Attempt to parse backticks, returning either a backtick code span or a
  152. // literal sequence of backticks.
  153. var parseBackticks = function(inlines) {
  154. var startpos = this.pos;
  155. var ticks = this.match(/^`+/);
  156. if (!ticks) {
  157. return 0;
  158. }
  159. var afterOpenTicks = this.pos;
  160. var foundCode = false;
  161. var match;
  162. while (!foundCode && (match = this.match(/`+/m))) {
  163. if (match == ticks) {
  164. inlines.push({ t: 'Code', c: this.subject.slice(afterOpenTicks,
  165. this.pos - ticks.length)
  166. .replace(/[ \n]+/g,' ')
  167. .trim() });
  168. return true;
  169. }
  170. }
  171. // If we got here, we didn't match a closing backtick sequence.
  172. this.pos = afterOpenTicks;
  173. inlines.push({ t: 'Str', c: ticks });
  174. return true;
  175. };
  176. // Parse a backslash-escaped special character, adding either the escaped
  177. // character, a hard line break (if the backslash is followed by a newline),
  178. // or a literal backslash to the 'inlines' list.
  179. var parseBackslash = function(inlines) {
  180. var subj = this.subject,
  181. pos = this.pos;
  182. if (subj.charCodeAt(pos) === C_BACKSLASH) {
  183. if (subj.charAt(pos + 1) === '\n') {
  184. this.pos = this.pos + 2;
  185. inlines.push({ t: 'Hardbreak' });
  186. } else if (reEscapable.test(subj.charAt(pos + 1))) {
  187. this.pos = this.pos + 2;
  188. inlines.push({ t: 'Str', c: subj.charAt(pos + 1) });
  189. } else {
  190. this.pos++;
  191. inlines.push({t: 'Str', c: '\\'});
  192. }
  193. return true;
  194. } else {
  195. return false;
  196. }
  197. };
  198. // Attempt to parse an autolink (URL or email in pointy brackets).
  199. var parseAutolink = function(inlines) {
  200. var m;
  201. var dest;
  202. 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
  203. dest = m.slice(1,-1);
  204. inlines.push(
  205. {t: 'Link',
  206. label: [{ t: 'Str', c: dest }],
  207. destination: 'mailto:' + encodeURI(unescape(dest)) });
  208. return true;
  209. } 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))) {
  210. dest = m.slice(1,-1);
  211. inlines.push({
  212. t: 'Link',
  213. label: [{ t: 'Str', c: dest }],
  214. destination: encodeURI(unescape(dest)) });
  215. return true;
  216. } else {
  217. return false;
  218. }
  219. };
  220. // Attempt to parse a raw HTML tag.
  221. var parseHtmlTag = function(inlines) {
  222. var m = this.match(reHtmlTag);
  223. if (m) {
  224. inlines.push({ t: 'Html', c: m });
  225. return true;
  226. } else {
  227. return false;
  228. }
  229. };
  230. // Scan a sequence of characters with code cc, and return information about
  231. // the number of delimiters and whether they are positioned such that
  232. // they can open and/or close emphasis or strong emphasis. A utility
  233. // function for strong/emph parsing.
  234. var scanDelims = function(cc) {
  235. var numdelims = 0;
  236. var first_close_delims = 0;
  237. var char_before, char_after, cc_after;
  238. var startpos = this.pos;
  239. char_before = this.pos === 0 ? '\n' :
  240. this.subject.charAt(this.pos - 1);
  241. while (this.peek() === cc) {
  242. numdelims++;
  243. this.pos++;
  244. }
  245. cc_after = this.peek();
  246. if (cc_after === -1) {
  247. char_after = '\n';
  248. } else {
  249. char_after = fromCodePoint(cc_after);
  250. }
  251. var can_open = numdelims > 0 && numdelims <= 3 && !(/\s/.test(char_after));
  252. var can_close = numdelims > 0 && numdelims <= 3 && !(/\s/.test(char_before));
  253. if (cc === C_UNDERSCORE) {
  254. can_open = can_open && !((/[a-z0-9]/i).test(char_before));
  255. can_close = can_close && !((/[a-z0-9]/i).test(char_after));
  256. }
  257. this.pos = startpos;
  258. return { numdelims: numdelims,
  259. can_open: can_open,
  260. can_close: can_close };
  261. };
  262. var Emph = function(ils) {
  263. return {t: 'Emph', c: ils};
  264. };
  265. var Strong = function(ils) {
  266. return {t: 'Strong', c: ils};
  267. };
  268. var Str = function(s) {
  269. return {t: 'Str', c: s};
  270. };
  271. // Attempt to parse emphasis or strong emphasis.
  272. var parseEmphasis = function(cc,inlines) {
  273. var startpos = this.pos;
  274. var c ;
  275. var first_close = 0;
  276. c = fromCodePoint(cc);
  277. var numdelims;
  278. var numclosedelims;
  279. var delimpos;
  280. // Get opening delimiters.
  281. res = this.scanDelims(cc);
  282. numdelims = res.numdelims;
  283. if (numdelims === 0) {
  284. this.pos = startpos;
  285. return false;
  286. }
  287. if (numdelims >= 4 || !res.can_open) {
  288. this.pos += numdelims;
  289. inlines.push(Str(this.subject.slice(startpos, startpos + numdelims)));
  290. return true;
  291. }
  292. this.pos += numdelims;
  293. var delims_to_match = numdelims;
  294. var current = [];
  295. var firstend;
  296. var firstpos;
  297. var state = 0;
  298. var can_close = false;
  299. var can_open = false;
  300. var last_emphasis_closer = null;
  301. while (this.last_emphasis_closer[c] >= this.pos) {
  302. res = this.scanDelims(cc);
  303. numclosedelims = res.numdelims;
  304. if (res.can_close) {
  305. if (last_emphasis_closer === null ||
  306. last_emphasis_closer < this.pos) {
  307. last_emphasis_closer = this.pos;
  308. }
  309. if (numclosedelims === 3 && delims_to_match === 3) {
  310. delims_to_match -= 3;
  311. this.pos += 3;
  312. current = [{t: 'Strong', c: [{t: 'Emph', c: current}]}];
  313. } else if (numclosedelims >= 2 && delims_to_match >= 2) {
  314. delims_to_match -= 2;
  315. this.pos += 2;
  316. firstend = current.length;
  317. firstpos = this.pos;
  318. current = [{t: 'Strong', c: current}];
  319. } else if (numclosedelims >= 1 && delims_to_match >= 1) {
  320. delims_to_match -= 1;
  321. this.pos += 1;
  322. firstend = current.length;
  323. firstpos = this.pos;
  324. current = [{t: 'Emph', c: current}];
  325. } else {
  326. if (!(this.parseInline(current,true))) {
  327. break;
  328. }
  329. }
  330. if (delims_to_match === 0) {
  331. Array.prototype.push.apply(inlines, current);
  332. return true;
  333. }
  334. } else if (!(this.parseInline(current,true))) {
  335. break;
  336. }
  337. }
  338. // we didn't match emphasis: fallback
  339. inlines.push(Str(this.subject.slice(startpos,
  340. startpos + delims_to_match)));
  341. if (delims_to_match < numdelims) {
  342. Array.prototype.push.apply(inlines, current.slice(0,firstend));
  343. this.pos = firstpos;
  344. } else { // delims_to_match === numdelims
  345. this.pos = startpos + delims_to_match;
  346. }
  347. if (last_emphasis_closer) {
  348. this.last_emphasis_closer[c] = last_emphasis_closer;
  349. }
  350. return true;
  351. };
  352. // Attempt to parse link title (sans quotes), returning the string
  353. // or null if no match.
  354. var parseLinkTitle = function() {
  355. var title = this.match(reLinkTitle);
  356. if (title) {
  357. // chop off quotes from title and unescape:
  358. return unescapeEntBS(title.substr(1, title.length - 2));
  359. } else {
  360. return null;
  361. }
  362. };
  363. // Attempt to parse link destination, returning the string or
  364. // null if no match.
  365. var parseLinkDestination = function() {
  366. var res = this.match(reLinkDestinationBraces);
  367. if (res) { // chop off surrounding <..>:
  368. return encodeURI(unescape(unescapeEntBS(res.substr(1, res.length - 2))));
  369. } else {
  370. res = this.match(reLinkDestination);
  371. if (res !== null) {
  372. return encodeURI(unescape(unescapeEntBS(res)));
  373. } else {
  374. return null;
  375. }
  376. }
  377. };
  378. // Attempt to parse a link label, returning number of characters parsed.
  379. var parseLinkLabel = function() {
  380. if (this.peek() != C_OPEN_BRACKET) {
  381. return 0;
  382. }
  383. var startpos = this.pos;
  384. var nest_level = 0;
  385. if (this.label_nest_level > 0) {
  386. // If we've already checked to the end of this subject
  387. // for a label, even with a different starting [, we
  388. // know we won't find one here and we can just return.
  389. // This avoids lots of backtracking.
  390. // Note: nest level 1 would be: [foo [bar]
  391. // nest level 2 would be: [foo [bar [baz]
  392. this.label_nest_level--;
  393. return 0;
  394. }
  395. this.pos++; // advance past [
  396. var c;
  397. while ((c = this.peek()) && c != -1 && (c != C_CLOSE_BRACKET || nest_level > 0)) {
  398. switch (c) {
  399. case C_BACKTICK:
  400. this.parseBackticks([]);
  401. break;
  402. case C_LESSTHAN:
  403. if (!(this.parseAutolink([]) || this.parseHtmlTag([]))) {
  404. this.pos++;
  405. }
  406. break;
  407. case C_OPEN_BRACKET: // nested []
  408. nest_level++;
  409. this.pos++;
  410. break;
  411. case C_CLOSE_BRACKET: // nested []
  412. nest_level--;
  413. this.pos++;
  414. break;
  415. case C_BACKSLASH:
  416. this.parseBackslash([]);
  417. break;
  418. default:
  419. this.parseString([]);
  420. }
  421. }
  422. if (c === C_CLOSE_BRACKET) {
  423. this.label_nest_level = 0;
  424. this.pos++; // advance past ]
  425. return this.pos - startpos;
  426. } else {
  427. if (c === -1) {
  428. this.label_nest_level = nest_level;
  429. }
  430. this.pos = startpos;
  431. return 0;
  432. }
  433. };
  434. // Parse raw link label, including surrounding [], and return
  435. // inline contents. (Note: this is not a method of InlineParser.)
  436. var parseRawLabel = function(s) {
  437. // note: parse without a refmap; we don't want links to resolve
  438. // in nested brackets!
  439. return new InlineParser().parse(s.substr(1, s.length - 2), {});
  440. };
  441. // Attempt to parse a link. If successful, return the link.
  442. var parseLink = function(inlines) {
  443. var startpos = this.pos;
  444. var reflabel;
  445. var n;
  446. var dest;
  447. var title;
  448. n = this.parseLinkLabel();
  449. if (n === 0) {
  450. return false;
  451. }
  452. var afterlabel = this.pos;
  453. var rawlabel = this.subject.substr(startpos, n);
  454. // if we got this far, we've parsed a label.
  455. // Try to parse an explicit link: [label](url "title")
  456. if (this.peek() == C_OPEN_PAREN) {
  457. this.pos++;
  458. if (this.spnl() &&
  459. ((dest = this.parseLinkDestination()) !== null) &&
  460. this.spnl() &&
  461. // make sure there's a space before the title:
  462. (/^\s/.test(this.subject.charAt(this.pos - 1)) &&
  463. (title = this.parseLinkTitle() || '') || true) &&
  464. this.spnl() &&
  465. this.match(/^\)/)) {
  466. inlines.push({ t: 'Link',
  467. destination: dest,
  468. title: title,
  469. label: parseRawLabel(rawlabel) });
  470. return true;
  471. } else {
  472. this.pos = startpos;
  473. return false;
  474. }
  475. }
  476. // If we're here, it wasn't an explicit link. Try to parse a reference link.
  477. // first, see if there's another label
  478. var savepos = this.pos;
  479. this.spnl();
  480. var beforelabel = this.pos;
  481. n = this.parseLinkLabel();
  482. if (n == 2) {
  483. // empty second label
  484. reflabel = rawlabel;
  485. } else if (n > 0) {
  486. reflabel = this.subject.slice(beforelabel, beforelabel + n);
  487. } else {
  488. this.pos = savepos;
  489. reflabel = rawlabel;
  490. }
  491. // lookup rawlabel in refmap
  492. var link = this.refmap[normalizeReference(reflabel)];
  493. if (link) {
  494. inlines.push({t: 'Link',
  495. destination: link.destination,
  496. title: link.title,
  497. label: parseRawLabel(rawlabel) });
  498. return true;
  499. } else {
  500. this.pos = startpos;
  501. return false;
  502. }
  503. // Nothing worked, rewind:
  504. this.pos = startpos;
  505. return false;
  506. };
  507. // Attempt to parse an entity, return Entity object if successful.
  508. var parseEntity = function(inlines) {
  509. var m;
  510. if ((m = this.match(reEntityHere))) {
  511. inlines.push({ t: 'Str', c: entityToChar(m) });
  512. return true;
  513. } else {
  514. return false;
  515. }
  516. };
  517. // Parse a run of ordinary characters, or a single character with
  518. // a special meaning in markdown, as a plain string, adding to inlines.
  519. var parseString = function(inlines) {
  520. var m;
  521. if ((m = this.match(reMain))) {
  522. inlines.push({ t: 'Str', c: m });
  523. return true;
  524. } else {
  525. return false;
  526. }
  527. };
  528. // Parse a newline. If it was preceded by two spaces, return a hard
  529. // line break; otherwise a soft line break.
  530. var parseNewline = function(inlines) {
  531. var m = this.match(/^ *\n/);
  532. if (m) {
  533. if (m.length > 2) {
  534. inlines.push({ t: 'Hardbreak' });
  535. } else if (m.length > 0) {
  536. inlines.push({ t: 'Softbreak' });
  537. }
  538. return true;
  539. }
  540. return false;
  541. };
  542. // Attempt to parse an image. If the opening '!' is not followed
  543. // by a link, return a literal '!'.
  544. var parseImage = function(inlines) {
  545. if (this.match(/^!/)) {
  546. var link = this.parseLink(inlines);
  547. if (link) {
  548. inlines[inlines.length - 1].t = 'Image';
  549. return true;
  550. } else {
  551. inlines.push({ t: 'Str', c: '!' });
  552. return true;
  553. }
  554. } else {
  555. return false;
  556. }
  557. };
  558. // Attempt to parse a link reference, modifying refmap.
  559. var parseReference = function(s, refmap) {
  560. this.subject = s;
  561. this.pos = 0;
  562. this.label_nest_level = 0;
  563. var rawlabel;
  564. var dest;
  565. var title;
  566. var matchChars;
  567. var startpos = this.pos;
  568. var match;
  569. // label:
  570. matchChars = this.parseLinkLabel();
  571. if (matchChars === 0) {
  572. return 0;
  573. } else {
  574. rawlabel = this.subject.substr(0, matchChars);
  575. }
  576. // colon:
  577. if (this.peek() === C_COLON) {
  578. this.pos++;
  579. } else {
  580. this.pos = startpos;
  581. return 0;
  582. }
  583. // link url
  584. this.spnl();
  585. dest = this.parseLinkDestination();
  586. if (dest === null || dest.length === 0) {
  587. this.pos = startpos;
  588. return 0;
  589. }
  590. var beforetitle = this.pos;
  591. this.spnl();
  592. title = this.parseLinkTitle();
  593. if (title === null) {
  594. title = '';
  595. // rewind before spaces
  596. this.pos = beforetitle;
  597. }
  598. // make sure we're at line end:
  599. if (this.match(/^ *(?:\n|$)/) === null) {
  600. this.pos = startpos;
  601. return 0;
  602. }
  603. var normlabel = normalizeReference(rawlabel);
  604. if (!refmap[normlabel]) {
  605. refmap[normlabel] = { destination: dest, title: title };
  606. }
  607. return this.pos - startpos;
  608. };
  609. // Parse the next inline element in subject, advancing subject position.
  610. // If memoize is set, memoize the result.
  611. // On success, add the result to the inlines list, and return true.
  612. // On failure, return false.
  613. var parseInline = function(inlines, memoize) {
  614. var startpos = this.pos;
  615. var origlen = inlines.length;
  616. var memoized = memoize && this.memo[startpos];
  617. if (memoized) {
  618. this.pos = memoized.endpos;
  619. Array.prototype.push.apply(inlines, memoized.inline);
  620. return true;
  621. }
  622. var c = this.peek();
  623. if (c === -1) {
  624. return false;
  625. }
  626. var res;
  627. switch(c) {
  628. case C_NEWLINE:
  629. case C_SPACE:
  630. res = this.parseNewline(inlines);
  631. break;
  632. case C_BACKSLASH:
  633. res = this.parseBackslash(inlines);
  634. break;
  635. case C_BACKTICK:
  636. res = this.parseBackticks(inlines);
  637. break;
  638. case C_ASTERISK:
  639. case C_UNDERSCORE:
  640. res = this.parseEmphasis(c, inlines);
  641. break;
  642. case C_OPEN_BRACKET:
  643. res = this.parseLink(inlines);
  644. break;
  645. case C_BANG:
  646. res = this.parseImage(inlines);
  647. break;
  648. case C_LESSTHAN:
  649. res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines);
  650. break;
  651. case C_AMPERSAND:
  652. res = this.parseEntity(inlines);
  653. break;
  654. default:
  655. res = this.parseString(inlines);
  656. break;
  657. }
  658. if (!res) {
  659. this.pos += 1;
  660. inlines.push({t: 'Str', c: fromCodePoint(c)});
  661. }
  662. if (memoize) {
  663. this.memo[startpos] = { inline: inlines.slice(origlen),
  664. endpos: this.pos };
  665. }
  666. return true;
  667. };
  668. // Parse s as a list of inlines, using refmap to resolve references.
  669. var parseInlines = function(s, refmap) {
  670. this.subject = s;
  671. this.pos = 0;
  672. this.refmap = refmap || {};
  673. this.memo = {};
  674. this.last_emphasis_closer = { '*': s.length, '_': s.length };
  675. var inlines = [];
  676. while (this.parseInline(inlines, false)) {
  677. }
  678. return inlines;
  679. };
  680. // The InlineParser object.
  681. function InlineParser(){
  682. return {
  683. subject: '',
  684. label_nest_level: 0, // used by parseLinkLabel method
  685. last_emphasis_closer: null, // used by parseEmphasis method
  686. pos: 0,
  687. refmap: {},
  688. memo: {},
  689. match: match,
  690. peek: peek,
  691. spnl: spnl,
  692. parseBackticks: parseBackticks,
  693. parseBackslash: parseBackslash,
  694. parseAutolink: parseAutolink,
  695. parseHtmlTag: parseHtmlTag,
  696. scanDelims: scanDelims,
  697. parseEmphasis: parseEmphasis,
  698. parseLinkTitle: parseLinkTitle,
  699. parseLinkDestination: parseLinkDestination,
  700. parseLinkLabel: parseLinkLabel,
  701. parseLink: parseLink,
  702. parseEntity: parseEntity,
  703. parseString: parseString,
  704. parseNewline: parseNewline,
  705. parseImage: parseImage,
  706. parseReference: parseReference,
  707. parseInline: parseInline,
  708. parse: parseInlines
  709. };
  710. }
  711. // DOC PARSER
  712. // These are methods of a DocParser object, defined below.
  713. var makeBlock = function(tag, start_line, start_column) {
  714. return { t: tag,
  715. open: true,
  716. last_line_blank: false,
  717. start_line: start_line,
  718. start_column: start_column,
  719. end_line: start_line,
  720. children: [],
  721. parent: null,
  722. // string_content is formed by concatenating strings, in finalize:
  723. string_content: "",
  724. strings: [],
  725. inline_content: []
  726. };
  727. };
  728. // Returns true if parent block can contain child block.
  729. var canContain = function(parent_type, child_type) {
  730. return ( parent_type == 'Document' ||
  731. parent_type == 'BlockQuote' ||
  732. parent_type == 'ListItem' ||
  733. (parent_type == 'List' && child_type == 'ListItem') );
  734. };
  735. // Returns true if block type can accept lines of text.
  736. var acceptsLines = function(block_type) {
  737. return ( block_type == 'Paragraph' ||
  738. block_type == 'IndentedCode' ||
  739. block_type == 'FencedCode' );
  740. };
  741. // Returns true if block ends with a blank line, descending if needed
  742. // into lists and sublists.
  743. var endsWithBlankLine = function(block) {
  744. if (block.last_line_blank) {
  745. return true;
  746. }
  747. if ((block.t == 'List' || block.t == 'ListItem') && block.children.length > 0) {
  748. return endsWithBlankLine(block.children[block.children.length - 1]);
  749. } else {
  750. return false;
  751. }
  752. };
  753. // Break out of all containing lists, resetting the tip of the
  754. // document to the parent of the highest list, and finalizing
  755. // all the lists. (This is used to implement the "two blank lines
  756. // break of of all lists" feature.)
  757. var breakOutOfLists = function(block, line_number) {
  758. var b = block;
  759. var last_list = null;
  760. do {
  761. if (b.t === 'List') {
  762. last_list = b;
  763. }
  764. b = b.parent;
  765. } while (b);
  766. if (last_list) {
  767. while (block != last_list) {
  768. this.finalize(block, line_number);
  769. block = block.parent;
  770. }
  771. this.finalize(last_list, line_number);
  772. this.tip = last_list.parent;
  773. }
  774. };
  775. // Add a line to the block at the tip. We assume the tip
  776. // can accept lines -- that check should be done before calling this.
  777. var addLine = function(ln, offset) {
  778. var s = ln.slice(offset);
  779. if (!(this.tip.open)) {
  780. throw({ msg: "Attempted to add line (" + ln + ") to closed container." });
  781. }
  782. this.tip.strings.push(s);
  783. };
  784. // Add block of type tag as a child of the tip. If the tip can't
  785. // accept children, close and finalize it and try its parent,
  786. // and so on til we find a block that can accept children.
  787. var addChild = function(tag, line_number, offset) {
  788. while (!canContain(this.tip.t, tag)) {
  789. this.finalize(this.tip, line_number);
  790. }
  791. var column_number = offset + 1; // offset 0 = column 1
  792. var newBlock = makeBlock(tag, line_number, column_number);
  793. this.tip.children.push(newBlock);
  794. newBlock.parent = this.tip;
  795. this.tip = newBlock;
  796. return newBlock;
  797. };
  798. // Parse a list marker and return data on the marker (type,
  799. // start, delimiter, bullet character, padding) or null.
  800. var parseListMarker = function(ln, offset) {
  801. var rest = ln.slice(offset);
  802. var match;
  803. var spaces_after_marker;
  804. var data = {};
  805. if (rest.match(reHrule)) {
  806. return null;
  807. }
  808. if ((match = rest.match(/^[*+-]( +|$)/))) {
  809. spaces_after_marker = match[1].length;
  810. data.type = 'Bullet';
  811. data.bullet_char = match[0][0];
  812. } else if ((match = rest.match(/^(\d+)([.)])( +|$)/))) {
  813. spaces_after_marker = match[3].length;
  814. data.type = 'Ordered';
  815. data.start = parseInt(match[1]);
  816. data.delimiter = match[2];
  817. } else {
  818. return null;
  819. }
  820. var blank_item = match[0].length === rest.length;
  821. if (spaces_after_marker >= 5 ||
  822. spaces_after_marker < 1 ||
  823. blank_item) {
  824. data.padding = match[0].length - spaces_after_marker + 1;
  825. } else {
  826. data.padding = match[0].length;
  827. }
  828. return data;
  829. };
  830. // Returns true if the two list items are of the same type,
  831. // with the same delimiter and bullet character. This is used
  832. // in agglomerating list items into lists.
  833. var listsMatch = function(list_data, item_data) {
  834. return (list_data.type === item_data.type &&
  835. list_data.delimiter === item_data.delimiter &&
  836. list_data.bullet_char === item_data.bullet_char);
  837. };
  838. // Analyze a line of text and update the document appropriately.
  839. // We parse markdown text by calling this on each line of input,
  840. // then finalizing the document.
  841. var incorporateLine = function(ln, line_number) {
  842. var all_matched = true;
  843. var last_child;
  844. var first_nonspace;
  845. var offset = 0;
  846. var match;
  847. var data;
  848. var blank;
  849. var indent;
  850. var last_matched_container;
  851. var i;
  852. var CODE_INDENT = 4;
  853. var container = this.doc;
  854. var oldtip = this.tip;
  855. // Convert tabs to spaces:
  856. ln = detabLine(ln);
  857. // For each containing block, try to parse the associated line start.
  858. // Bail out on failure: container will point to the last matching block.
  859. // Set all_matched to false if not all containers match.
  860. while (container.children.length > 0) {
  861. last_child = container.children[container.children.length - 1];
  862. if (!last_child.open) {
  863. break;
  864. }
  865. container = last_child;
  866. match = matchAt(/[^ ]/, ln, offset);
  867. if (match === null) {
  868. first_nonspace = ln.length;
  869. blank = true;
  870. } else {
  871. first_nonspace = match;
  872. blank = false;
  873. }
  874. indent = first_nonspace - offset;
  875. switch (container.t) {
  876. case 'BlockQuote':
  877. if (indent <= 3 && ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  878. offset = first_nonspace + 1;
  879. if (ln.charCodeAt(offset) === C_SPACE) {
  880. offset++;
  881. }
  882. } else {
  883. all_matched = false;
  884. }
  885. break;
  886. case 'ListItem':
  887. if (indent >= container.list_data.marker_offset +
  888. container.list_data.padding) {
  889. offset += container.list_data.marker_offset +
  890. container.list_data.padding;
  891. } else if (blank) {
  892. offset = first_nonspace;
  893. } else {
  894. all_matched = false;
  895. }
  896. break;
  897. case 'IndentedCode':
  898. if (indent >= CODE_INDENT) {
  899. offset += CODE_INDENT;
  900. } else if (blank) {
  901. offset = first_nonspace;
  902. } else {
  903. all_matched = false;
  904. }
  905. break;
  906. case 'ATXHeader':
  907. case 'SetextHeader':
  908. case 'HorizontalRule':
  909. // a header can never container > 1 line, so fail to match:
  910. all_matched = false;
  911. break;
  912. case 'FencedCode':
  913. // skip optional spaces of fence offset
  914. i = container.fence_offset;
  915. while (i > 0 && ln.charCodeAt(offset) === C_SPACE) {
  916. offset++;
  917. i--;
  918. }
  919. break;
  920. case 'HtmlBlock':
  921. if (blank) {
  922. all_matched = false;
  923. }
  924. break;
  925. case 'Paragraph':
  926. if (blank) {
  927. container.last_line_blank = true;
  928. all_matched = false;
  929. }
  930. break;
  931. default:
  932. }
  933. if (!all_matched) {
  934. container = container.parent; // back up to last matching block
  935. break;
  936. }
  937. }
  938. last_matched_container = container;
  939. // This function is used to finalize and close any unmatched
  940. // blocks. We aren't ready to do this now, because we might
  941. // have a lazy paragraph continuation, in which case we don't
  942. // want to close unmatched blocks. So we store this closure for
  943. // use later, when we have more information.
  944. var closeUnmatchedBlocks = function(mythis) {
  945. // finalize any blocks not matched
  946. while (!already_done && oldtip != last_matched_container) {
  947. mythis.finalize(oldtip, line_number);
  948. oldtip = oldtip.parent;
  949. }
  950. var already_done = true;
  951. };
  952. // Check to see if we've hit 2nd blank line; if so break out of list:
  953. if (blank && container.last_line_blank) {
  954. this.breakOutOfLists(container, line_number);
  955. }
  956. // Unless last matched container is a code block, try new container starts,
  957. // adding children to the last matched container:
  958. while (container.t != 'FencedCode' &&
  959. container.t != 'IndentedCode' &&
  960. container.t != 'HtmlBlock' &&
  961. // this is a little performance optimization:
  962. matchAt(/^[ #`~*+_=<>0-9-]/,ln,offset) !== null) {
  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. if (indent >= CODE_INDENT) {
  973. // indented code
  974. if (this.tip.t != 'Paragraph' && !blank) {
  975. offset += CODE_INDENT;
  976. closeUnmatchedBlocks(this);
  977. container = this.addChild('IndentedCode', line_number, offset);
  978. } else { // indent > 4 in a lazy paragraph continuation
  979. break;
  980. }
  981. } else if (ln.charCodeAt(first_nonspace) === C_GREATERTHAN) {
  982. // blockquote
  983. offset = first_nonspace + 1;
  984. // optional following space
  985. if (ln.charCodeAt(offset) === C_SPACE) {
  986. offset++;
  987. }
  988. closeUnmatchedBlocks(this);
  989. container = this.addChild('BlockQuote', line_number, offset);
  990. } else if ((match = ln.slice(first_nonspace).match(/^#{1,6}(?: +|$)/))) {
  991. // ATX header
  992. offset = first_nonspace + match[0].length;
  993. closeUnmatchedBlocks(this);
  994. container = this.addChild('ATXHeader', line_number, first_nonspace);
  995. container.level = match[0].trim().length; // number of #s
  996. // remove trailing ###s:
  997. container.strings =
  998. [ln.slice(offset).replace(/(?:(\\#) *#*| *#+) *$/,'$1')];
  999. break;
  1000. } else if ((match = ln.slice(first_nonspace).match(/^`{3,}(?!.*`)|^~{3,}(?!.*~)/))) {
  1001. // fenced code block
  1002. var fence_length = match[0].length;
  1003. closeUnmatchedBlocks(this);
  1004. container = this.addChild('FencedCode', line_number, first_nonspace);
  1005. container.fence_length = fence_length;
  1006. container.fence_char = match[0][0];
  1007. container.fence_offset = first_nonspace - offset;
  1008. offset = first_nonspace + fence_length;
  1009. break;
  1010. } else if (matchAt(reHtmlBlockOpen, ln, first_nonspace) !== null) {
  1011. // html block
  1012. closeUnmatchedBlocks(this);
  1013. container = this.addChild('HtmlBlock', line_number, first_nonspace);
  1014. // note, we don't adjust offset because the tag is part of the text
  1015. break;
  1016. } else if (container.t == 'Paragraph' &&
  1017. container.strings.length === 1 &&
  1018. ((match = ln.slice(first_nonspace).match(/^(?:=+|-+) *$/)))) {
  1019. // setext header line
  1020. closeUnmatchedBlocks(this);
  1021. container.t = 'SetextHeader'; // convert Paragraph to SetextHeader
  1022. container.level = match[0][0] === '=' ? 1 : 2;
  1023. offset = ln.length;
  1024. } else if (matchAt(reHrule, ln, first_nonspace) !== null) {
  1025. // hrule
  1026. closeUnmatchedBlocks(this);
  1027. container = this.addChild('HorizontalRule', line_number, first_nonspace);
  1028. offset = ln.length - 1;
  1029. break;
  1030. } else if ((data = parseListMarker(ln, first_nonspace))) {
  1031. // list item
  1032. closeUnmatchedBlocks(this);
  1033. data.marker_offset = indent;
  1034. offset = first_nonspace + data.padding;
  1035. // add the list if needed
  1036. if (container.t !== 'List' ||
  1037. !(listsMatch(container.list_data, data))) {
  1038. container = this.addChild('List', line_number, first_nonspace);
  1039. container.list_data = data;
  1040. }
  1041. // add the list item
  1042. container = this.addChild('ListItem', line_number, first_nonspace);
  1043. container.list_data = data;
  1044. } else {
  1045. break;
  1046. }
  1047. if (acceptsLines(container.t)) {
  1048. // if it's a line container, it can't contain other containers
  1049. break;
  1050. }
  1051. }
  1052. // What remains at the offset is a text line. Add the text to the
  1053. // appropriate container.
  1054. match = matchAt(/[^ ]/, ln, offset);
  1055. if (match === null) {
  1056. first_nonspace = ln.length;
  1057. blank = true;
  1058. } else {
  1059. first_nonspace = match;
  1060. blank = false;
  1061. }
  1062. indent = first_nonspace - offset;
  1063. // First check for a lazy paragraph continuation:
  1064. if (this.tip !== last_matched_container &&
  1065. !blank &&
  1066. this.tip.t == 'Paragraph' &&
  1067. this.tip.strings.length > 0) {
  1068. // lazy paragraph continuation
  1069. this.last_line_blank = false;
  1070. this.addLine(ln, offset);
  1071. } else { // not a lazy continuation
  1072. // finalize any blocks not matched
  1073. closeUnmatchedBlocks(this);
  1074. // Block quote lines are never blank as they start with >
  1075. // and we don't count blanks in fenced code for purposes of tight/loose
  1076. // lists or breaking out of lists. We also don't set last_line_blank
  1077. // on an empty list item.
  1078. container.last_line_blank = blank &&
  1079. !(container.t == 'BlockQuote' ||
  1080. container.t == 'FencedCode' ||
  1081. (container.t == 'ListItem' &&
  1082. container.children.length === 0 &&
  1083. container.start_line == line_number));
  1084. var cont = container;
  1085. while (cont.parent) {
  1086. cont.parent.last_line_blank = false;
  1087. cont = cont.parent;
  1088. }
  1089. switch (container.t) {
  1090. case 'IndentedCode':
  1091. case 'HtmlBlock':
  1092. this.addLine(ln, offset);
  1093. break;
  1094. case 'FencedCode':
  1095. // check for closing code fence:
  1096. match = (indent <= 3 &&
  1097. ln.charAt(first_nonspace) == container.fence_char &&
  1098. ln.slice(first_nonspace).match(/^(?:`{3,}|~{3,})(?= *$)/));
  1099. if (match && match[0].length >= container.fence_length) {
  1100. // don't add closing fence to container; instead, close it:
  1101. this.finalize(container, line_number);
  1102. } else {
  1103. this.addLine(ln, offset);
  1104. }
  1105. break;
  1106. case 'ATXHeader':
  1107. case 'SetextHeader':
  1108. case 'HorizontalRule':
  1109. // nothing to do; we already added the contents.
  1110. break;
  1111. default:
  1112. if (acceptsLines(container.t)) {
  1113. this.addLine(ln, first_nonspace);
  1114. } else if (blank) {
  1115. // do nothing
  1116. } else if (container.t != 'HorizontalRule' &&
  1117. container.t != 'SetextHeader') {
  1118. // create paragraph container for line
  1119. container = this.addChild('Paragraph', line_number, first_nonspace);
  1120. this.addLine(ln, first_nonspace);
  1121. } else {
  1122. console.log("Line " + line_number.toString() +
  1123. " with container type " + container.t +
  1124. " did not match any condition.");
  1125. }
  1126. }
  1127. }
  1128. };
  1129. // Finalize a block. Close it and do any necessary postprocessing,
  1130. // e.g. creating string_content from strings, setting the 'tight'
  1131. // or 'loose' status of a list, and parsing the beginnings
  1132. // of paragraphs for reference definitions. Reset the tip to the
  1133. // parent of the closed block.
  1134. var finalize = function(block, line_number) {
  1135. var pos;
  1136. // don't do anything if the block is already closed
  1137. if (!block.open) {
  1138. return 0;
  1139. }
  1140. block.open = false;
  1141. if (line_number > block.start_line) {
  1142. block.end_line = line_number - 1;
  1143. } else {
  1144. block.end_line = line_number;
  1145. }
  1146. switch (block.t) {
  1147. case 'Paragraph':
  1148. block.string_content = block.strings.join('\n').replace(/^ */m,'');
  1149. // try parsing the beginning as link reference definitions:
  1150. while (block.string_content.charCodeAt(0) === C_OPEN_BRACKET &&
  1151. (pos = this.inlineParser.parseReference(block.string_content,
  1152. this.refmap))) {
  1153. block.string_content = block.string_content.slice(pos);
  1154. if (isBlank(block.string_content)) {
  1155. block.t = 'ReferenceDef';
  1156. break;
  1157. }
  1158. }
  1159. break;
  1160. case 'ATXHeader':
  1161. case 'SetextHeader':
  1162. case 'HtmlBlock':
  1163. block.string_content = block.strings.join('\n');
  1164. break;
  1165. case 'IndentedCode':
  1166. block.string_content = block.strings.join('\n').replace(/(\n *)*$/,'\n');
  1167. break;
  1168. case 'FencedCode':
  1169. // first line becomes info string
  1170. block.info = unescapeEntBS(block.strings[0].trim());
  1171. if (block.strings.length == 1) {
  1172. block.string_content = '';
  1173. } else {
  1174. block.string_content = block.strings.slice(1).join('\n') + '\n';
  1175. }
  1176. break;
  1177. case 'List':
  1178. block.tight = true; // tight by default
  1179. var numitems = block.children.length;
  1180. var i = 0;
  1181. while (i < numitems) {
  1182. var item = block.children[i];
  1183. // check for non-final list item ending with blank line:
  1184. var last_item = i == numitems - 1;
  1185. if (endsWithBlankLine(item) && !last_item) {
  1186. block.tight = false;
  1187. break;
  1188. }
  1189. // recurse into children of list item, to see if there are
  1190. // spaces between any of them:
  1191. var numsubitems = item.children.length;
  1192. var j = 0;
  1193. while (j < numsubitems) {
  1194. var subitem = item.children[j];
  1195. var last_subitem = j == numsubitems - 1;
  1196. if (endsWithBlankLine(subitem) && !(last_item && last_subitem)) {
  1197. block.tight = false;
  1198. break;
  1199. }
  1200. j++;
  1201. }
  1202. i++;
  1203. }
  1204. break;
  1205. default:
  1206. break;
  1207. }
  1208. this.tip = block.parent || this.top;
  1209. };
  1210. // Walk through a block & children recursively, parsing string content
  1211. // into inline content where appropriate.
  1212. var processInlines = function(block) {
  1213. switch(block.t) {
  1214. case 'Paragraph':
  1215. case 'SetextHeader':
  1216. case 'ATXHeader':
  1217. block.inline_content =
  1218. this.inlineParser.parse(block.string_content.trim(), this.refmap);
  1219. block.string_content = "";
  1220. break;
  1221. default:
  1222. break;
  1223. }
  1224. if (block.children) {
  1225. for (var i = 0; i < block.children.length; i++) {
  1226. this.processInlines(block.children[i]);
  1227. }
  1228. }
  1229. };
  1230. // The main parsing function. Returns a parsed document AST.
  1231. var parse = function(input) {
  1232. this.doc = makeBlock('Document', 1, 1);
  1233. this.tip = this.doc;
  1234. this.refmap = {};
  1235. var lines = input.replace(/\n$/,'').split(/\r\n|\n|\r/);
  1236. var len = lines.length;
  1237. for (var i = 0; i < len; i++) {
  1238. this.incorporateLine(lines[i], i+1);
  1239. }
  1240. while (this.tip) {
  1241. this.finalize(this.tip, len - 1);
  1242. }
  1243. this.processInlines(this.doc);
  1244. return this.doc;
  1245. };
  1246. // The DocParser object.
  1247. function DocParser(){
  1248. return {
  1249. doc: makeBlock('Document', 1, 1),
  1250. tip: this.doc,
  1251. refmap: {},
  1252. inlineParser: new InlineParser(),
  1253. breakOutOfLists: breakOutOfLists,
  1254. addLine: addLine,
  1255. addChild: addChild,
  1256. incorporateLine: incorporateLine,
  1257. finalize: finalize,
  1258. processInlines: processInlines,
  1259. parse: parse
  1260. };
  1261. }
  1262. module.exports.DocParser = DocParser;
  1263. module.exports.HtmlRenderer = require('./html-renderer.js');