aboutsummaryrefslogtreecommitdiff
path: root/js/lib/inlines.js
blob: 96e8753b12fe040e61a30d338abc03112464122e (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 res = this.scanDelims(cc);
  230. var numdelims = res.numdelims;
  231. var startpos = this.pos;
  232. if (numdelims === 0) {
  233. return false;
  234. }
  235. this.pos += numdelims;
  236. inlines.push(Str(this.subject.slice(startpos, this.pos)));
  237. // Add entry to stack for this opener
  238. this.delimiters = { cc: cc,
  239. numdelims: numdelims,
  240. pos: inlines.length - 1,
  241. previous: this.delimiters,
  242. next: null,
  243. can_open: res.can_open,
  244. can_close: res.can_close};
  245. if (this.delimiters.previous !== null) {
  246. this.delimiters.previous.next = this.delimiters;
  247. }
  248. return true;
  249. };
  250. var removeDelimiter = function(delim) {
  251. if (delim.previous !== null) {
  252. delim.previous.next = delim.next;
  253. }
  254. if (delim.next === null) {
  255. // top of stack
  256. this.delimiters = delim.previous;
  257. } else {
  258. delim.next.previous = delim.previous;
  259. }
  260. };
  261. var removeGaps = function(inlines) {
  262. // remove gaps from inlines
  263. var i, j;
  264. j = 0;
  265. for (i = 0 ; i < inlines.length; i++) {
  266. if (inlines[i] !== null) {
  267. inlines[j] = inlines[i];
  268. j++;
  269. }
  270. }
  271. inlines.splice(j);
  272. };
  273. var processEmphasis = function(inlines, stack_bottom) {
  274. var opener, closer;
  275. var opener_inl, closer_inl;
  276. var nextstack, tempstack;
  277. var use_delims;
  278. var contents;
  279. var tmp;
  280. var emph;
  281. var i,j;
  282. // find first closer above stack_bottom:
  283. closer = this.delimiters;
  284. while (closer !== null && closer.previous !== stack_bottom) {
  285. closer = closer.previous;
  286. }
  287. // move forward, looking for closers, and handling each
  288. while (closer !== null) {
  289. if (closer.can_close && (closer.cc === C_UNDERSCORE || closer.cc === C_ASTERISK)) {
  290. // found emphasis closer. now look back for first matching opener:
  291. opener = closer.previous;
  292. while (opener !== null && opener !== stack_bottom) {
  293. if (opener.cc === closer.cc && opener.can_open) {
  294. break;
  295. }
  296. opener = opener.previous;
  297. }
  298. if (opener !== null && opener !== stack_bottom) {
  299. // calculate actual number of delimiters used from this closer
  300. if (closer.numdelims < 3 || opener.numdelims < 3) {
  301. use_delims = closer.numdelims <= opener.numdelims ?
  302. closer.numdelims : opener.numdelims;
  303. } else {
  304. use_delims = closer.numdelims % 2 === 0 ? 2 : 1;
  305. }
  306. opener_inl = inlines[opener.pos];
  307. closer_inl = inlines[closer.pos];
  308. // remove used delimiters from stack elts and inlines
  309. opener.numdelims -= use_delims;
  310. closer.numdelims -= use_delims;
  311. opener_inl.c = opener_inl.c.slice(0, opener_inl.c.length - use_delims);
  312. closer_inl.c = closer_inl.c.slice(0, closer_inl.c.length - use_delims);
  313. // build contents for new emph element
  314. contents = inlines.slice(opener.pos + 1, closer.pos);
  315. removeGaps(contents);
  316. emph = use_delims === 1 ? Emph(contents) : Strong(contents);
  317. // insert into list of inlines
  318. inlines[opener.pos + 1] = emph;
  319. for (i = opener.pos + 2; i < closer.pos; i++) {
  320. inlines[i] = null;
  321. }
  322. // remove elts btw opener and closer in delimiters stack
  323. tempstack = closer.previous;
  324. while (tempstack !== null && tempstack !== opener) {
  325. nextstack = tempstack.previous;
  326. this.removeDelimiter(tempstack);
  327. tempstack = nextstack;
  328. }
  329. // if opener has 0 delims, remove it and the inline
  330. if (opener.numdelims === 0) {
  331. inlines[opener.pos] = null;
  332. this.removeDelimiter(opener);
  333. }
  334. if (closer.numdelims === 0) {
  335. inlines[closer.pos] = null;
  336. tempstack = closer.next;
  337. this.removeDelimiter(closer);
  338. closer = tempstack;
  339. }
  340. } else {
  341. closer = closer.next;
  342. }
  343. } else {
  344. closer = closer.next;
  345. }
  346. }
  347. removeGaps(inlines);
  348. // remove all delimiters
  349. while (this.delimiters != stack_bottom) {
  350. this.removeDelimiter(this.delimiters);
  351. }
  352. };
  353. // Attempt to parse link title (sans quotes), returning the string
  354. // or null if no match.
  355. var parseLinkTitle = function() {
  356. var title = this.match(reLinkTitle);
  357. if (title) {
  358. // chop off quotes from title and unescape:
  359. return unescapeString(title.substr(1, title.length - 2));
  360. } else {
  361. return null;
  362. }
  363. };
  364. // Attempt to parse link destination, returning the string or
  365. // null if no match.
  366. var parseLinkDestination = function() {
  367. var res = this.match(reLinkDestinationBraces);
  368. if (res) { // chop off surrounding <..>:
  369. return encodeURI(unescape(unescapeString(res.substr(1, res.length - 2))));
  370. } else {
  371. res = this.match(reLinkDestination);
  372. if (res !== null) {
  373. return encodeURI(unescape(unescapeString(res)));
  374. } else {
  375. return null;
  376. }
  377. }
  378. };
  379. // Attempt to parse a link label, returning number of characters parsed.
  380. var parseLinkLabel = function() {
  381. var match = this.match(/^\[(?:[^\\\[\]]|\\[\[\]]){0,1000}\]/);
  382. return match === null ? 0 : match.length;
  383. };
  384. // Parse raw link label, including surrounding [], and return
  385. // inline contents. (Note: this is not a method of InlineParser.)
  386. var parseRawLabel = function(s) {
  387. // note: parse without a refmap; we don't want links to resolve
  388. // in nested brackets!
  389. return new InlineParser().parse(s.substr(1, s.length - 2), {});
  390. };
  391. // Add open bracket to delimiter stack and add a Str to inlines.
  392. var parseOpenBracket = function(inlines) {
  393. var startpos = this.pos;
  394. this.pos += 1;
  395. inlines.push(Str("["));
  396. // Add entry to stack for this opener
  397. this.delimiters = { cc: C_OPEN_BRACKET,
  398. numdelims: 1,
  399. pos: inlines.length - 1,
  400. previous: this.delimiters,
  401. next: null,
  402. can_open: true,
  403. can_close: false,
  404. index: startpos };
  405. if (this.delimiters.previous !== null) {
  406. this.delimiters.previous.next = this.delimiters;
  407. }
  408. return true;
  409. };
  410. // IF next character is [, and ! delimiter to delimiter stack and
  411. // add a Str to inlines. Otherwise just add a Str.
  412. var parseBang = function(inlines) {
  413. var startpos = this.pos;
  414. this.pos += 1;
  415. if (this.peek() === C_OPEN_BRACKET) {
  416. this.pos += 1;
  417. inlines.push(Str("!["));
  418. // Add entry to stack for this opener
  419. this.delimiters = { cc: C_BANG,
  420. numdelims: 1,
  421. pos: inlines.length - 1,
  422. previous: this.delimiters,
  423. next: null,
  424. can_open: true,
  425. can_close: false,
  426. index: startpos + 1 };
  427. if (this.delimiters.previous !== null) {
  428. this.delimiters.previous.next = this.delimiters;
  429. }
  430. } else {
  431. inlines.push(Str("!"));
  432. }
  433. return true;
  434. };
  435. // Try to match close bracket against an opening in the delimiter
  436. // stack. Add either a link or image, or a plain [ character,
  437. // to the inlines stack. If there is a matching delimiter,
  438. // remove it from the delimiter stack.
  439. var parseCloseBracket = function(inlines) {
  440. var startpos;
  441. var is_image;
  442. var dest;
  443. var title;
  444. var matched = false;
  445. var link_text;
  446. var i;
  447. var opener, closer_above, tempstack;
  448. this.pos += 1;
  449. startpos = this.pos;
  450. // look through stack of delimiters for a [ or !
  451. opener = this.delimiters;
  452. while (opener !== null) {
  453. if (opener.cc === C_OPEN_BRACKET || opener.cc === C_BANG) {
  454. break;
  455. }
  456. opener = opener.previous;
  457. }
  458. if (opener === null) {
  459. // no matched opener, just return a literal
  460. inlines.push(Str("]"));
  461. return true;
  462. }
  463. // If we got here, open is a potential opener
  464. is_image = opener.cc === C_BANG;
  465. // instead of copying a slice, we null out the
  466. // parts of inlines that don't correspond to link_text;
  467. // later, we'll collapse them. This is awkward, and could
  468. // be simplified if we made inlines a linked list rather than
  469. // an array:
  470. link_text = inlines.slice(0);
  471. for (i = 0; i < opener.pos + 1; i++) {
  472. link_text[i] = null;
  473. }
  474. // Check to see if we have a link/image
  475. // Inline link?
  476. if (this.peek() === C_OPEN_PAREN) {
  477. this.pos++;
  478. if (this.spnl() &&
  479. ((dest = this.parseLinkDestination()) !== null) &&
  480. this.spnl() &&
  481. // make sure there's a space before the title:
  482. (/^\s/.test(this.subject.charAt(this.pos - 1)) &&
  483. (title = this.parseLinkTitle() || '') || true) &&
  484. this.spnl() &&
  485. this.match(/^\)/)) {
  486. matched = true;
  487. }
  488. } else {
  489. // Next, see if there's a link label
  490. var savepos = this.pos;
  491. this.spnl();
  492. var beforelabel = this.pos;
  493. n = this.parseLinkLabel();
  494. if (n === 0 || n === 2) {
  495. // empty or missing second label
  496. reflabel = this.subject.slice(opener.index, startpos);
  497. } else {
  498. reflabel = this.subject.slice(beforelabel, beforelabel + n);
  499. }
  500. if (n === 0) {
  501. // If shortcut reference link, rewind before spaces we skipped.
  502. this.pos = savepos;
  503. }
  504. // lookup rawlabel in refmap
  505. var link = this.refmap[normalizeReference(reflabel)];
  506. if (link) {
  507. dest = link.destination;
  508. title = link.title;
  509. matched = true;
  510. }
  511. }
  512. if (matched) {
  513. this.processEmphasis(link_text, opener.previous);
  514. // remove the part of inlines that became link_text.
  515. // see note above on why we need to do this instead of splice:
  516. for (i = opener.pos; i < inlines.length; i++) {
  517. inlines[i] = null;
  518. }
  519. // processEmphasis will remove this and later delimiters.
  520. // Now, for a link, we also remove earlier link openers.
  521. // (no links in links)
  522. if (!is_image) {
  523. opener = this.delimiters;
  524. closer_above = null;
  525. while (opener !== null) {
  526. if (opener.cc === C_OPEN_BRACKET) {
  527. if (closer_above) {
  528. closer_above.previous = opener.previous;
  529. } else {
  530. this.delimiters = opener.previous;
  531. }
  532. } else {
  533. closer_above = opener;
  534. }
  535. opener = opener.previous;
  536. }
  537. }
  538. inlines.push({t: is_image ? 'Image' : 'Link',
  539. destination: dest,
  540. title: title,
  541. label: link_text});
  542. return true;
  543. } else { // no match
  544. this.removeDelimiter(opener); // remove this opener from stack
  545. this.pos = startpos;
  546. inlines.push(Str("]"));
  547. return true;
  548. }
  549. };
  550. // Attempt to parse an entity, return Entity object if successful.
  551. var parseEntity = function(inlines) {
  552. var m;
  553. if ((m = this.match(reEntityHere))) {
  554. inlines.push({ t: 'Str', c: entityToChar(m) });
  555. return true;
  556. } else {
  557. return false;
  558. }
  559. };
  560. // Parse a run of ordinary characters, or a single character with
  561. // a special meaning in markdown, as a plain string, adding to inlines.
  562. var parseString = function(inlines) {
  563. var m;
  564. if ((m = this.match(reMain))) {
  565. inlines.push({ t: 'Str', c: m });
  566. return true;
  567. } else {
  568. return false;
  569. }
  570. };
  571. // Parse a newline. If it was preceded by two spaces, return a hard
  572. // line break; otherwise a soft line break.
  573. var parseNewline = function(inlines) {
  574. var m = this.match(/^ *\n/);
  575. if (m) {
  576. if (m.length > 2) {
  577. inlines.push({ t: 'Hardbreak' });
  578. } else if (m.length > 0) {
  579. inlines.push({ t: 'Softbreak' });
  580. }
  581. return true;
  582. }
  583. return false;
  584. };
  585. // Attempt to parse an image. If the opening '!' is not followed
  586. // by a link, return a literal '!'.
  587. var parseImage = function(inlines) {
  588. if (this.match(/^!/)) {
  589. var link = this.parseLink(inlines);
  590. if (link) {
  591. inlines[inlines.length - 1].t = 'Image';
  592. return true;
  593. } else {
  594. inlines.push({ t: 'Str', c: '!' });
  595. return true;
  596. }
  597. } else {
  598. return false;
  599. }
  600. };
  601. // Attempt to parse a link reference, modifying refmap.
  602. var parseReference = function(s, refmap) {
  603. this.subject = s;
  604. this.pos = 0;
  605. this.label_nest_level = 0;
  606. var rawlabel;
  607. var dest;
  608. var title;
  609. var matchChars;
  610. var startpos = this.pos;
  611. var match;
  612. // label:
  613. matchChars = this.parseLinkLabel();
  614. if (matchChars === 0) {
  615. return 0;
  616. } else {
  617. rawlabel = this.subject.substr(0, matchChars);
  618. }
  619. // colon:
  620. if (this.peek() === C_COLON) {
  621. this.pos++;
  622. } else {
  623. this.pos = startpos;
  624. return 0;
  625. }
  626. // link url
  627. this.spnl();
  628. dest = this.parseLinkDestination();
  629. if (dest === null || dest.length === 0) {
  630. this.pos = startpos;
  631. return 0;
  632. }
  633. var beforetitle = this.pos;
  634. this.spnl();
  635. title = this.parseLinkTitle();
  636. if (title === null) {
  637. title = '';
  638. // rewind before spaces
  639. this.pos = beforetitle;
  640. }
  641. // make sure we're at line end:
  642. if (this.match(/^ *(?:\n|$)/) === null) {
  643. this.pos = startpos;
  644. return 0;
  645. }
  646. var normlabel = normalizeReference(rawlabel);
  647. if (!refmap[normlabel]) {
  648. refmap[normlabel] = { destination: dest, title: title };
  649. }
  650. return this.pos - startpos;
  651. };
  652. // Parse the next inline element in subject, advancing subject position.
  653. // On success, add the result to the inlines list, and return true.
  654. // On failure, return false.
  655. var parseInline = function(inlines) {
  656. var startpos = this.pos;
  657. var origlen = inlines.length;
  658. var c = this.peek();
  659. if (c === -1) {
  660. return false;
  661. }
  662. var res;
  663. switch(c) {
  664. case C_NEWLINE:
  665. case C_SPACE:
  666. res = this.parseNewline(inlines);
  667. break;
  668. case C_BACKSLASH:
  669. res = this.parseBackslash(inlines);
  670. break;
  671. case C_BACKTICK:
  672. res = this.parseBackticks(inlines);
  673. break;
  674. case C_ASTERISK:
  675. case C_UNDERSCORE:
  676. res = this.parseEmphasis(c, inlines);
  677. break;
  678. case C_OPEN_BRACKET:
  679. res = this.parseOpenBracket(inlines);
  680. break;
  681. case C_BANG:
  682. res = this.parseBang(inlines);
  683. break;
  684. case C_CLOSE_BRACKET:
  685. res = this.parseCloseBracket(inlines);
  686. break;
  687. case C_LESSTHAN:
  688. res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines);
  689. break;
  690. case C_AMPERSAND:
  691. res = this.parseEntity(inlines);
  692. break;
  693. default:
  694. res = this.parseString(inlines);
  695. break;
  696. }
  697. if (!res) {
  698. this.pos += 1;
  699. inlines.push({t: 'Str', c: fromCodePoint(c)});
  700. }
  701. return true;
  702. };
  703. // Parse s as a list of inlines, using refmap to resolve references.
  704. var parseInlines = function(s, refmap) {
  705. this.subject = s;
  706. this.pos = 0;
  707. this.refmap = refmap || {};
  708. this.delimiters = null;
  709. var inlines = [];
  710. while (this.parseInline(inlines)) {
  711. }
  712. this.processEmphasis(inlines, null);
  713. return inlines;
  714. };
  715. // The InlineParser object.
  716. function InlineParser(){
  717. return {
  718. subject: '',
  719. label_nest_level: 0, // used by parseLinkLabel method
  720. delimiters: null, // used by parseEmphasis method
  721. pos: 0,
  722. refmap: {},
  723. match: match,
  724. peek: peek,
  725. spnl: spnl,
  726. unescapeString: unescapeString,
  727. parseBackticks: parseBackticks,
  728. parseBackslash: parseBackslash,
  729. parseAutolink: parseAutolink,
  730. parseHtmlTag: parseHtmlTag,
  731. scanDelims: scanDelims,
  732. parseEmphasis: parseEmphasis,
  733. parseLinkTitle: parseLinkTitle,
  734. parseLinkDestination: parseLinkDestination,
  735. parseLinkLabel: parseLinkLabel,
  736. parseOpenBracket: parseOpenBracket,
  737. parseCloseBracket: parseCloseBracket,
  738. parseBang: parseBang,
  739. parseEntity: parseEntity,
  740. parseString: parseString,
  741. parseNewline: parseNewline,
  742. parseReference: parseReference,
  743. parseInline: parseInline,
  744. processEmphasis: processEmphasis,
  745. removeDelimiter: removeDelimiter,
  746. parse: parseInlines
  747. };
  748. }
  749. module.exports = InlineParser;