aboutsummaryrefslogtreecommitdiff
path: root/js/lib/inlines.js
blob: 4f1f16a01d34fdfa0c745796cdf113868df325b4 (plain)
  1. var fromCodePoint = require('./from-code-point.js');
  2. var entityToChar = require('./html5-entities.js').entityToChar;
  3. // Constants for character codes:
  4. var C_NEWLINE = 10;
  5. var C_SPACE = 32;
  6. var C_ASTERISK = 42;
  7. var C_UNDERSCORE = 95;
  8. var C_BACKTICK = 96;
  9. var C_OPEN_BRACKET = 91;
  10. var C_CLOSE_BRACKET = 93;
  11. var C_LESSTHAN = 60;
  12. var C_GREATERTHAN = 62;
  13. var C_BANG = 33;
  14. var C_BACKSLASH = 92;
  15. var C_AMPERSAND = 38;
  16. var C_OPEN_PAREN = 40;
  17. var C_COLON = 58;
  18. // Some regexps used in inline parser:
  19. var ESCAPABLE = '[!"#$%&\'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]';
  20. var ESCAPED_CHAR = '\\\\' + ESCAPABLE;
  21. var IN_DOUBLE_QUOTES = '"(' + ESCAPED_CHAR + '|[^"\\x00])*"';
  22. var IN_SINGLE_QUOTES = '\'(' + ESCAPED_CHAR + '|[^\'\\x00])*\'';
  23. var IN_PARENS = '\\((' + ESCAPED_CHAR + '|[^)\\x00])*\\)';
  24. var REG_CHAR = '[^\\\\()\\x00-\\x20]';
  25. var IN_PARENS_NOSP = '\\((' + REG_CHAR + '|' + ESCAPED_CHAR + ')*\\)';
  26. var TAGNAME = '[A-Za-z][A-Za-z0-9]*';
  27. var ATTRIBUTENAME = '[a-zA-Z_:][a-zA-Z0-9:._-]*';
  28. var UNQUOTEDVALUE = "[^\"'=<>`\\x00-\\x20]+";
  29. var SINGLEQUOTEDVALUE = "'[^']*'";
  30. var DOUBLEQUOTEDVALUE = '"[^"]*"';
  31. var ATTRIBUTEVALUE = "(?:" + UNQUOTEDVALUE + "|" + SINGLEQUOTEDVALUE + "|" + DOUBLEQUOTEDVALUE + ")";
  32. var ATTRIBUTEVALUESPEC = "(?:" + "\\s*=" + "\\s*" + ATTRIBUTEVALUE + ")";
  33. var ATTRIBUTE = "(?:" + "\\s+" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC + "?)";
  34. var OPENTAG = "<" + TAGNAME + ATTRIBUTE + "*" + "\\s*/?>";
  35. var CLOSETAG = "</" + TAGNAME + "\\s*[>]";
  36. var HTMLCOMMENT = "<!--([^-]+|[-][^-]+)*-->";
  37. var PROCESSINGINSTRUCTION = "[<][?].*?[?][>]";
  38. var DECLARATION = "<![A-Z]+" + "\\s+[^>]*>";
  39. var CDATA = "<!\\[CDATA\\[([^\\]]+|\\][^\\]]|\\]\\][^>])*\\]\\]>";
  40. var HTMLTAG = "(?:" + OPENTAG + "|" + CLOSETAG + "|" + HTMLCOMMENT + "|" +
  41. PROCESSINGINSTRUCTION + "|" + DECLARATION + "|" + CDATA + ")";
  42. var ENTITY = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});";
  43. var reHtmlTag = new RegExp('^' + HTMLTAG, 'i');
  44. var reLinkTitle = new RegExp(
  45. '^(?:"(' + ESCAPED_CHAR + '|[^"\\x00])*"' +
  46. '|' +
  47. '\'(' + ESCAPED_CHAR + '|[^\'\\x00])*\'' +
  48. '|' +
  49. '\\((' + ESCAPED_CHAR + '|[^)\\x00])*\\))');
  50. var reLinkDestinationBraces = new RegExp(
  51. '^(?:[<](?:[^<>\\n\\\\\\x00]' + '|' + ESCAPED_CHAR + '|' + '\\\\)*[>])');
  52. var reLinkDestination = new RegExp(
  53. '^(?:' + REG_CHAR + '+|' + ESCAPED_CHAR + '|' + IN_PARENS_NOSP + ')*');
  54. var reEscapable = new RegExp(ESCAPABLE);
  55. var reAllEscapedChar = new RegExp('\\\\(' + ESCAPABLE + ')', 'g');
  56. var reEscapedChar = new RegExp('^\\\\(' + ESCAPABLE + ')');
  57. var reEntityHere = new RegExp('^' + ENTITY, 'i');
  58. var reEntity = new RegExp(ENTITY, 'gi');
  59. // Matches a character with a special meaning in markdown,
  60. // or a string of non-special characters. Note: we match
  61. // clumps of _ or * or `, because they need to be handled in groups.
  62. var reMain = /^(?:[_*`\n]+|[\[\]\\!<&*_]|(?: *[^\n `\[\]\\!<&*_]+)+|[ \n]+)/m;
  63. // Replace entities and backslash escapes with literal characters.
  64. var unescapeString = function(s) {
  65. return s.replace(reAllEscapedChar, '$1')
  66. .replace(reEntity, entityToChar);
  67. };
  68. // Normalize reference label: collapse internal whitespace
  69. // to single space, remove leading/trailing whitespace, case fold.
  70. var normalizeReference = function(s) {
  71. return s.trim()
  72. .replace(/\s+/,' ')
  73. .toUpperCase();
  74. };
  75. // INLINE PARSER
  76. // These are methods of an InlineParser object, defined below.
  77. // An InlineParser keeps track of a subject (a string to be
  78. // parsed) and a position in that subject.
  79. // If re matches at current position in the subject, advance
  80. // position in subject and return the match; otherwise return null.
  81. var match = function(re) {
  82. var match = re.exec(this.subject.slice(this.pos));
  83. if (match) {
  84. this.pos += match.index + match[0].length;
  85. return match[0];
  86. } else {
  87. return null;
  88. }
  89. };
  90. // Returns the code for the character at the current subject position, or -1
  91. // there are no more characters.
  92. var peek = function() {
  93. if (this.pos < this.subject.length) {
  94. return this.subject.charCodeAt(this.pos);
  95. } else {
  96. return -1;
  97. }
  98. };
  99. // Parse zero or more space characters, including at most one newline
  100. var spnl = function() {
  101. this.match(/^ *(?:\n *)?/);
  102. return 1;
  103. };
  104. // All of the parsers below try to match something at the current position
  105. // in the subject. If they succeed in matching anything, they
  106. // return the inline matched, advancing the subject.
  107. // Attempt to parse backticks, returning either a backtick code span or a
  108. // literal sequence of backticks.
  109. var parseBackticks = function(inlines) {
  110. var startpos = this.pos;
  111. var ticks = this.match(/^`+/);
  112. if (!ticks) {
  113. return 0;
  114. }
  115. var afterOpenTicks = this.pos;
  116. var foundCode = false;
  117. var match;
  118. while (!foundCode && (match = this.match(/`+/m))) {
  119. if (match == ticks) {
  120. inlines.push({ t: 'Code', c: this.subject.slice(afterOpenTicks,
  121. this.pos - ticks.length)
  122. .replace(/[ \n]+/g,' ')
  123. .trim() });
  124. return true;
  125. }
  126. }
  127. // If we got here, we didn't match a closing backtick sequence.
  128. this.pos = afterOpenTicks;
  129. inlines.push({ t: 'Str', c: ticks });
  130. return true;
  131. };
  132. // Parse a backslash-escaped special character, adding either the escaped
  133. // character, a hard line break (if the backslash is followed by a newline),
  134. // or a literal backslash to the 'inlines' list.
  135. var parseBackslash = function(inlines) {
  136. var subj = this.subject,
  137. pos = this.pos;
  138. if (subj.charCodeAt(pos) === C_BACKSLASH) {
  139. if (subj.charAt(pos + 1) === '\n') {
  140. this.pos = this.pos + 2;
  141. inlines.push({ t: 'Hardbreak' });
  142. } else if (reEscapable.test(subj.charAt(pos + 1))) {
  143. this.pos = this.pos + 2;
  144. inlines.push({ t: 'Str', c: subj.charAt(pos + 1) });
  145. } else {
  146. this.pos++;
  147. inlines.push({t: 'Str', c: '\\'});
  148. }
  149. return true;
  150. } else {
  151. return false;
  152. }
  153. };
  154. // Attempt to parse an autolink (URL or email in pointy brackets).
  155. var parseAutolink = function(inlines) {
  156. var m;
  157. var dest;
  158. 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
  159. dest = m.slice(1,-1);
  160. inlines.push(
  161. {t: 'Link',
  162. label: [{ t: 'Str', c: dest }],
  163. destination: 'mailto:' + encodeURI(unescape(dest)) });
  164. return true;
  165. } 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))) {
  166. dest = m.slice(1,-1);
  167. inlines.push({
  168. t: 'Link',
  169. label: [{ t: 'Str', c: dest }],
  170. destination: encodeURI(unescape(dest)) });
  171. return true;
  172. } else {
  173. return false;
  174. }
  175. };
  176. // Attempt to parse a raw HTML tag.
  177. var parseHtmlTag = function(inlines) {
  178. var m = this.match(reHtmlTag);
  179. if (m) {
  180. inlines.push({ t: 'Html', c: m });
  181. return true;
  182. } else {
  183. return false;
  184. }
  185. };
  186. // Scan a sequence of characters with code cc, and return information about
  187. // the number of delimiters and whether they are positioned such that
  188. // they can open and/or close emphasis or strong emphasis. A utility
  189. // function for strong/emph parsing.
  190. var scanDelims = function(cc) {
  191. var numdelims = 0;
  192. var first_close_delims = 0;
  193. var char_before, char_after, cc_after;
  194. var startpos = this.pos;
  195. char_before = this.pos === 0 ? '\n' :
  196. this.subject.charAt(this.pos - 1);
  197. while (this.peek() === cc) {
  198. numdelims++;
  199. this.pos++;
  200. }
  201. cc_after = this.peek();
  202. if (cc_after === -1) {
  203. char_after = '\n';
  204. } else {
  205. char_after = fromCodePoint(cc_after);
  206. }
  207. var can_open = numdelims > 0 && !(/\s/.test(char_after));
  208. var can_close = numdelims > 0 && !(/\s/.test(char_before));
  209. if (cc === C_UNDERSCORE) {
  210. can_open = can_open && !((/[a-z0-9]/i).test(char_before));
  211. can_close = can_close && !((/[a-z0-9]/i).test(char_after));
  212. }
  213. this.pos = startpos;
  214. return { numdelims: numdelims,
  215. can_open: can_open,
  216. can_close: can_close };
  217. };
  218. var Emph = function(ils) {
  219. return {t: 'Emph', c: ils};
  220. };
  221. var Strong = function(ils) {
  222. return {t: 'Strong', c: ils};
  223. };
  224. var Str = function(s) {
  225. return {t: 'Str', c: s};
  226. };
  227. // Attempt to parse emphasis or strong emphasis.
  228. var parseEmphasis = function(cc,inlines) {
  229. var startpos = this.pos;
  230. var res = this.scanDelims(cc);
  231. var numdelims = res.numdelims;
  232. var usedelims;
  233. if (numdelims === 0) {
  234. this.pos = startpos;
  235. return false;
  236. }
  237. if (res.can_close) {
  238. // Walk the stack and find a matching opener, if possible
  239. var opener = this.emphasis_openers;
  240. while (opener) {
  241. if (opener.cc === cc) { // we have a match!
  242. if (numdelims < 3 || opener.numdelims < 3) {
  243. usedelims = numdelims <= opener.numdelims ? numdelims : opener.numdelims;
  244. } else { // numdelims >= 3 && opener.numdelims >= 3
  245. usedelims = numdelims % 2 === 0 ? 2 : 1;
  246. }
  247. var X = usedelims === 1 ? Emph : Strong;
  248. if (opener.numdelims == usedelims) { // all openers used
  249. this.pos += usedelims;
  250. inlines[opener.pos] = X(inlines.slice(opener.pos + 1));
  251. inlines.splice(opener.pos + 1, inlines.length - (opener.pos + 1));
  252. // Remove entries after this, to prevent overlapping nesting:
  253. this.emphasis_openers = opener.previous;
  254. return true;
  255. } else if (opener.numdelims > usedelims) { // only some openers used
  256. this.pos += usedelims;
  257. opener.numdelims -= usedelims;
  258. inlines[opener.pos].c =
  259. inlines[opener.pos].c.slice(0, opener.numdelims);
  260. inlines[opener.pos + 1] = X(inlines.slice(opener.pos + 1));
  261. inlines.splice(opener.pos + 2, inlines.length - (opener.pos + 2));
  262. // Remove entries after this, to prevent overlapping nesting:
  263. this.emphasis_openers = opener;
  264. return true;
  265. } else { // usedelims > opener.numdelims, should never happen
  266. throw new Error("Logic error: usedelims > opener.numdelims");
  267. }
  268. }
  269. opener = opener.previous;
  270. }
  271. }
  272. // If we're here, we didn't match a closer.
  273. this.pos += numdelims;
  274. inlines.push(Str(this.subject.slice(startpos, startpos + numdelims)));
  275. if (res.can_open) {
  276. // Add entry to stack for this opener
  277. this.emphasis_openers = { cc: cc,
  278. numdelims: numdelims,
  279. pos: inlines.length - 1,
  280. previous: this.emphasis_openers };
  281. }
  282. return true;
  283. };
  284. // Attempt to parse link title (sans quotes), returning the string
  285. // or null if no match.
  286. var parseLinkTitle = function() {
  287. var title = this.match(reLinkTitle);
  288. if (title) {
  289. // chop off quotes from title and unescape:
  290. return unescapeString(title.substr(1, title.length - 2));
  291. } else {
  292. return null;
  293. }
  294. };
  295. // Attempt to parse link destination, returning the string or
  296. // null if no match.
  297. var parseLinkDestination = function() {
  298. var res = this.match(reLinkDestinationBraces);
  299. if (res) { // chop off surrounding <..>:
  300. return encodeURI(unescape(unescapeString(res.substr(1, res.length - 2))));
  301. } else {
  302. res = this.match(reLinkDestination);
  303. if (res !== null) {
  304. return encodeURI(unescape(unescapeString(res)));
  305. } else {
  306. return null;
  307. }
  308. }
  309. };
  310. // Attempt to parse a link label, returning number of characters parsed.
  311. var parseLinkLabel = function() {
  312. if (this.peek() != C_OPEN_BRACKET) {
  313. return 0;
  314. }
  315. var startpos = this.pos;
  316. var nest_level = 0;
  317. if (this.label_nest_level > 0) {
  318. // If we've already checked to the end of this subject
  319. // for a label, even with a different starting [, we
  320. // know we won't find one here and we can just return.
  321. // This avoids lots of backtracking.
  322. // Note: nest level 1 would be: [foo [bar]
  323. // nest level 2 would be: [foo [bar [baz]
  324. this.label_nest_level--;
  325. return 0;
  326. }
  327. this.pos++; // advance past [
  328. var c;
  329. while ((c = this.peek()) && c != -1 && (c != C_CLOSE_BRACKET || nest_level > 0)) {
  330. switch (c) {
  331. case C_BACKTICK:
  332. this.parseBackticks([]);
  333. break;
  334. case C_LESSTHAN:
  335. if (!(this.parseAutolink([]) || this.parseHtmlTag([]))) {
  336. this.pos++;
  337. }
  338. break;
  339. case C_OPEN_BRACKET: // nested []
  340. nest_level++;
  341. this.pos++;
  342. break;
  343. case C_CLOSE_BRACKET: // nested []
  344. nest_level--;
  345. this.pos++;
  346. break;
  347. case C_BACKSLASH:
  348. this.parseBackslash([]);
  349. break;
  350. default:
  351. this.parseString([]);
  352. }
  353. }
  354. if (c === C_CLOSE_BRACKET) {
  355. this.label_nest_level = 0;
  356. this.pos++; // advance past ]
  357. return this.pos - startpos;
  358. } else {
  359. if (c === -1) {
  360. this.label_nest_level = nest_level;
  361. }
  362. this.pos = startpos;
  363. return 0;
  364. }
  365. };
  366. // Parse raw link label, including surrounding [], and return
  367. // inline contents. (Note: this is not a method of InlineParser.)
  368. var parseRawLabel = function(s) {
  369. // note: parse without a refmap; we don't want links to resolve
  370. // in nested brackets!
  371. return new InlineParser().parse(s.substr(1, s.length - 2), {});
  372. };
  373. // Attempt to parse a link. If successful, return the link.
  374. var parseLink = function(inlines) {
  375. var startpos = this.pos;
  376. var reflabel;
  377. var n;
  378. var dest;
  379. var title;
  380. n = this.parseLinkLabel();
  381. if (n === 0) {
  382. return false;
  383. }
  384. var afterlabel = this.pos;
  385. var rawlabel = this.subject.substr(startpos, n);
  386. // if we got this far, we've parsed a label.
  387. // Try to parse an explicit link: [label](url "title")
  388. if (this.peek() == C_OPEN_PAREN) {
  389. this.pos++;
  390. if (this.spnl() &&
  391. ((dest = this.parseLinkDestination()) !== null) &&
  392. this.spnl() &&
  393. // make sure there's a space before the title:
  394. (/^\s/.test(this.subject.charAt(this.pos - 1)) &&
  395. (title = this.parseLinkTitle() || '') || true) &&
  396. this.spnl() &&
  397. this.match(/^\)/)) {
  398. inlines.push({ t: 'Link',
  399. destination: dest,
  400. title: title,
  401. label: parseRawLabel(rawlabel) });
  402. return true;
  403. } else {
  404. this.pos = startpos;
  405. return false;
  406. }
  407. }
  408. // If we're here, it wasn't an explicit link. Try to parse a reference link.
  409. // first, see if there's another label
  410. var savepos = this.pos;
  411. this.spnl();
  412. var beforelabel = this.pos;
  413. n = this.parseLinkLabel();
  414. if (n == 2) {
  415. // empty second label
  416. reflabel = rawlabel;
  417. } else if (n > 0) {
  418. reflabel = this.subject.slice(beforelabel, beforelabel + n);
  419. } else {
  420. this.pos = savepos;
  421. reflabel = rawlabel;
  422. }
  423. // lookup rawlabel in refmap
  424. var link = this.refmap[normalizeReference(reflabel)];
  425. if (link) {
  426. inlines.push({t: 'Link',
  427. destination: link.destination,
  428. title: link.title,
  429. label: parseRawLabel(rawlabel) });
  430. return true;
  431. } else {
  432. this.pos = startpos;
  433. return false;
  434. }
  435. // Nothing worked, rewind:
  436. this.pos = startpos;
  437. return false;
  438. };
  439. // Attempt to parse an entity, return Entity object if successful.
  440. var parseEntity = function(inlines) {
  441. var m;
  442. if ((m = this.match(reEntityHere))) {
  443. inlines.push({ t: 'Str', c: entityToChar(m) });
  444. return true;
  445. } else {
  446. return false;
  447. }
  448. };
  449. // Parse a run of ordinary characters, or a single character with
  450. // a special meaning in markdown, as a plain string, adding to inlines.
  451. var parseString = function(inlines) {
  452. var m;
  453. if ((m = this.match(reMain))) {
  454. inlines.push({ t: 'Str', c: m });
  455. return true;
  456. } else {
  457. return false;
  458. }
  459. };
  460. // Parse a newline. If it was preceded by two spaces, return a hard
  461. // line break; otherwise a soft line break.
  462. var parseNewline = function(inlines) {
  463. var m = this.match(/^ *\n/);
  464. if (m) {
  465. if (m.length > 2) {
  466. inlines.push({ t: 'Hardbreak' });
  467. } else if (m.length > 0) {
  468. inlines.push({ t: 'Softbreak' });
  469. }
  470. return true;
  471. }
  472. return false;
  473. };
  474. // Attempt to parse an image. If the opening '!' is not followed
  475. // by a link, return a literal '!'.
  476. var parseImage = function(inlines) {
  477. if (this.match(/^!/)) {
  478. var link = this.parseLink(inlines);
  479. if (link) {
  480. inlines[inlines.length - 1].t = 'Image';
  481. return true;
  482. } else {
  483. inlines.push({ t: 'Str', c: '!' });
  484. return true;
  485. }
  486. } else {
  487. return false;
  488. }
  489. };
  490. // Attempt to parse a link reference, modifying refmap.
  491. var parseReference = function(s, refmap) {
  492. this.subject = s;
  493. this.pos = 0;
  494. this.label_nest_level = 0;
  495. var rawlabel;
  496. var dest;
  497. var title;
  498. var matchChars;
  499. var startpos = this.pos;
  500. var match;
  501. // label:
  502. matchChars = this.parseLinkLabel();
  503. if (matchChars === 0) {
  504. return 0;
  505. } else {
  506. rawlabel = this.subject.substr(0, matchChars);
  507. }
  508. // colon:
  509. if (this.peek() === C_COLON) {
  510. this.pos++;
  511. } else {
  512. this.pos = startpos;
  513. return 0;
  514. }
  515. // link url
  516. this.spnl();
  517. dest = this.parseLinkDestination();
  518. if (dest === null || dest.length === 0) {
  519. this.pos = startpos;
  520. return 0;
  521. }
  522. var beforetitle = this.pos;
  523. this.spnl();
  524. title = this.parseLinkTitle();
  525. if (title === null) {
  526. title = '';
  527. // rewind before spaces
  528. this.pos = beforetitle;
  529. }
  530. // make sure we're at line end:
  531. if (this.match(/^ *(?:\n|$)/) === null) {
  532. this.pos = startpos;
  533. return 0;
  534. }
  535. var normlabel = normalizeReference(rawlabel);
  536. if (!refmap[normlabel]) {
  537. refmap[normlabel] = { destination: dest, title: title };
  538. }
  539. return this.pos - startpos;
  540. };
  541. // Parse the next inline element in subject, advancing subject position.
  542. // On success, add the result to the inlines list, and return true.
  543. // On failure, return false.
  544. var parseInline = function(inlines) {
  545. var startpos = this.pos;
  546. var origlen = inlines.length;
  547. var c = this.peek();
  548. if (c === -1) {
  549. return false;
  550. }
  551. var res;
  552. switch(c) {
  553. case C_NEWLINE:
  554. case C_SPACE:
  555. res = this.parseNewline(inlines);
  556. break;
  557. case C_BACKSLASH:
  558. res = this.parseBackslash(inlines);
  559. break;
  560. case C_BACKTICK:
  561. res = this.parseBackticks(inlines);
  562. break;
  563. case C_ASTERISK:
  564. case C_UNDERSCORE:
  565. res = this.parseEmphasis(c, inlines);
  566. break;
  567. case C_OPEN_BRACKET:
  568. res = this.parseLink(inlines);
  569. break;
  570. case C_BANG:
  571. res = this.parseImage(inlines);
  572. break;
  573. case C_LESSTHAN:
  574. res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines);
  575. break;
  576. case C_AMPERSAND:
  577. res = this.parseEntity(inlines);
  578. break;
  579. default:
  580. res = this.parseString(inlines);
  581. break;
  582. }
  583. if (!res) {
  584. this.pos += 1;
  585. inlines.push({t: 'Str', c: fromCodePoint(c)});
  586. }
  587. return true;
  588. };
  589. // Parse s as a list of inlines, using refmap to resolve references.
  590. var parseInlines = function(s, refmap) {
  591. this.subject = s;
  592. this.pos = 0;
  593. this.refmap = refmap || {};
  594. this.emphasis_openers = null;
  595. var inlines = [];
  596. while (this.parseInline(inlines)) {
  597. }
  598. return inlines;
  599. };
  600. // The InlineParser object.
  601. function InlineParser(){
  602. return {
  603. subject: '',
  604. label_nest_level: 0, // used by parseLinkLabel method
  605. emphasis_openers: null, // used by parseEmphasis method
  606. pos: 0,
  607. refmap: {},
  608. match: match,
  609. peek: peek,
  610. spnl: spnl,
  611. unescapeString: unescapeString,
  612. parseBackticks: parseBackticks,
  613. parseBackslash: parseBackslash,
  614. parseAutolink: parseAutolink,
  615. parseHtmlTag: parseHtmlTag,
  616. scanDelims: scanDelims,
  617. parseEmphasis: parseEmphasis,
  618. parseLinkTitle: parseLinkTitle,
  619. parseLinkDestination: parseLinkDestination,
  620. parseLinkLabel: parseLinkLabel,
  621. parseLink: parseLink,
  622. parseEntity: parseEntity,
  623. parseString: parseString,
  624. parseNewline: parseNewline,
  625. parseImage: parseImage,
  626. parseReference: parseReference,
  627. parseInline: parseInline,
  628. parse: parseInlines
  629. };
  630. }
  631. module.exports = InlineParser;