aboutsummaryrefslogtreecommitdiff
path: root/js/lib/inlines.js
blob: a3355b491095feeb99d972a792e7d7ef7c631e0a (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. /* TODO
  354. var numdelims = res.numdelims;
  355. var usedelims;
  356. if (res.can_close) {
  357. // Walk the stack and find a matching opener, if possible
  358. var opener = this.delimiters;
  359. while (opener) {
  360. if (opener.cc === cc) { // we have a match!
  361. if (numdelims < 3 || opener.numdelims < 3) {
  362. usedelims = numdelims <= opener.numdelims ? numdelims : opener.numdelims;
  363. } else { // numdelims >= 3 && opener.numdelims >= 3
  364. usedelims = numdelims % 2 === 0 ? 2 : 1;
  365. }
  366. var X = usedelims === 1 ? Emph : Strong;
  367. if (opener.numdelims == usedelims) { // all openers used
  368. this.pos += usedelims;
  369. inlines[opener.pos] = X(inlines.slice(opener.pos + 1));
  370. inlines.splice(opener.pos + 1, inlines.length - (opener.pos + 1));
  371. // Remove entries after this, to prevent overlapping nesting:
  372. this.delimiters = opener.previous;
  373. return true;
  374. } else if (opener.numdelims > usedelims) { // only some openers used
  375. this.pos += usedelims;
  376. opener.numdelims -= usedelims;
  377. inlines[opener.pos].c =
  378. inlines[opener.pos].c.slice(0, opener.numdelims);
  379. inlines[opener.pos + 1] = X(inlines.slice(opener.pos + 1));
  380. inlines.splice(opener.pos + 2, inlines.length - (opener.pos + 2));
  381. // Remove entries after this, to prevent overlapping nesting:
  382. this.delimiters = opener;
  383. return true;
  384. } else { // usedelims > opener.numdelims, should never happen
  385. throw new Error("Logic error: usedelims > opener.numdelims");
  386. }
  387. }
  388. opener = opener.previous;
  389. }
  390. }
  391. // If we're here, we didn't match a closer.
  392. */
  393. // Attempt to parse link title (sans quotes), returning the string
  394. // or null if no match.
  395. var parseLinkTitle = function() {
  396. var title = this.match(reLinkTitle);
  397. if (title) {
  398. // chop off quotes from title and unescape:
  399. return unescapeString(title.substr(1, title.length - 2));
  400. } else {
  401. return null;
  402. }
  403. };
  404. // Attempt to parse link destination, returning the string or
  405. // null if no match.
  406. var parseLinkDestination = function() {
  407. var res = this.match(reLinkDestinationBraces);
  408. if (res) { // chop off surrounding <..>:
  409. return encodeURI(unescape(unescapeString(res.substr(1, res.length - 2))));
  410. } else {
  411. res = this.match(reLinkDestination);
  412. if (res !== null) {
  413. return encodeURI(unescape(unescapeString(res)));
  414. } else {
  415. return null;
  416. }
  417. }
  418. };
  419. // Attempt to parse a link label, returning number of characters parsed.
  420. var parseLinkLabel = function() {
  421. var match = this.match(/^\[(?:[^\\\[\]]|\\[\[\]]){0,1000}\]/);
  422. return match === null ? 0 : match.length;
  423. };
  424. // Parse raw link label, including surrounding [], and return
  425. // inline contents. (Note: this is not a method of InlineParser.)
  426. var parseRawLabel = function(s) {
  427. // note: parse without a refmap; we don't want links to resolve
  428. // in nested brackets!
  429. return new InlineParser().parse(s.substr(1, s.length - 2), {});
  430. };
  431. // Add open bracket to delimiter stack and add a Str to inlines.
  432. var parseOpenBracket = function(inlines) {
  433. var startpos = this.pos;
  434. this.pos += 1;
  435. inlines.push(Str("["));
  436. // Add entry to stack for this opener
  437. this.delimiters = { cc: C_OPEN_BRACKET,
  438. numdelims: 1,
  439. pos: inlines.length - 1,
  440. previous: this.delimiters,
  441. next: null,
  442. can_open: true,
  443. can_close: false,
  444. index: startpos };
  445. if (this.delimiters.previous != null) {
  446. this.delimiters.previous.next = this.delimiters;
  447. }
  448. return true;
  449. };
  450. // IF next character is [, and ! delimiter to delimiter stack and
  451. // add a Str to inlines. Otherwise just add a Str.
  452. var parseBang = function(inlines) {
  453. var startpos = this.pos;
  454. this.pos += 1;
  455. if (this.peek() === C_OPEN_BRACKET) {
  456. this.pos += 1;
  457. inlines.push(Str("!["));
  458. // Add entry to stack for this opener
  459. this.delimiters = { cc: C_BANG,
  460. numdelims: 1,
  461. pos: inlines.length - 1,
  462. previous: this.delimiters,
  463. next: null,
  464. can_open: true,
  465. can_close: false,
  466. index: startpos + 1 };
  467. if (this.delimiters.previous != null) {
  468. this.delimiters.previous.next = this.delimiters;
  469. }
  470. } else {
  471. inlines.push(Str("!"));
  472. }
  473. return true;
  474. };
  475. // Try to match close bracket against an opening in the delimiter
  476. // stack. Add either a link or image, or a plain [ character,
  477. // to the inlines stack. If there is a matching delimiter,
  478. // remove it from the delimiter stack.
  479. var parseCloseBracket = function(inlines) {
  480. var startpos;
  481. var is_image;
  482. var dest;
  483. var title;
  484. var matched = false;
  485. var link_text;
  486. var i;
  487. var opener, closer_above, tempstack;
  488. this.pos += 1;
  489. startpos = this.pos;
  490. // look through stack of delimiters for a [ or !
  491. opener = this.delimiters;
  492. while (opener !== null) {
  493. if (opener.cc === C_OPEN_BRACKET || opener.cc === C_BANG) {
  494. break;
  495. }
  496. opener = opener.previous;
  497. }
  498. if (opener === null) {
  499. // no matched opener, just return a literal
  500. inlines.push(Str("]"));
  501. return true;
  502. }
  503. // If we got here, open is a potential opener
  504. is_image = opener.cc === C_BANG;
  505. // instead of copying a slice, we null out the
  506. // parts of inlines that don't correspond to link_text;
  507. // later, we'll collapse them. This is awkward, and could
  508. // be simplified if we made inlines a linked list rather than
  509. // an array:
  510. link_text = inlines.slice(0);
  511. for (i = 0; i < opener.pos + 1; i++) {
  512. link_text[i] = null;
  513. }
  514. // Check to see if we have a link/image
  515. // Inline link?
  516. if (this.peek() == C_OPEN_PAREN) {
  517. this.pos++;
  518. if (this.spnl() &&
  519. ((dest = this.parseLinkDestination()) !== null) &&
  520. this.spnl() &&
  521. // make sure there's a space before the title:
  522. (/^\s/.test(this.subject.charAt(this.pos - 1)) &&
  523. (title = this.parseLinkTitle() || '') || true) &&
  524. this.spnl() &&
  525. this.match(/^\)/)) {
  526. matched = true;
  527. }
  528. } else {
  529. // Next, see if there's a link label
  530. var savepos = this.pos;
  531. this.spnl();
  532. var beforelabel = this.pos;
  533. n = this.parseLinkLabel();
  534. if (n === 0 || n === 2) {
  535. // empty or missing second label
  536. reflabel = this.subject.slice(opener.index, startpos);
  537. } else {
  538. reflabel = this.subject.slice(beforelabel, beforelabel + n);
  539. }
  540. // lookup rawlabel in refmap
  541. var link = this.refmap[normalizeReference(reflabel)];
  542. if (link) {
  543. dest = link.destination;
  544. title = link.title;
  545. matched = true;
  546. }
  547. }
  548. if (matched) {
  549. this.processEmphasis(link_text, opener.previous);
  550. // remove the part of inlines that became link_text.
  551. // see note above on why we need to do this instead of splice:
  552. for (i = opener.pos; i < inlines.length; i++) {
  553. inlines[i] = null;
  554. }
  555. // processEmphasis will remove this and later delimiters.
  556. // Now we also remove earlier ones of the same kind (so,
  557. // no links in links, no images in images).
  558. opener = this.delimiters;
  559. closer_above = null;
  560. while (opener !== null) {
  561. if (opener.cc === (is_image ? C_BANG : C_OPEN_BRACKET)) {
  562. if (closer_above) {
  563. closer_above.previous = opener.previous;
  564. } else {
  565. this.delimiters = opener.previous;
  566. }
  567. } else {
  568. closer_above = opener;
  569. }
  570. opener = opener.previous;
  571. }
  572. inlines.push({t: is_image ? 'Image' : 'Link',
  573. destination: dest,
  574. title: title,
  575. label: link_text});
  576. return true;
  577. } else { // no match
  578. this.removeDelimiter(opener); // remove this opener from stack
  579. this.pos = startpos;
  580. inlines.push(Str("]"));
  581. return true;
  582. }
  583. };
  584. // Attempt to parse an entity, return Entity object if successful.
  585. var parseEntity = function(inlines) {
  586. var m;
  587. if ((m = this.match(reEntityHere))) {
  588. inlines.push({ t: 'Str', c: entityToChar(m) });
  589. return true;
  590. } else {
  591. return false;
  592. }
  593. };
  594. // Parse a run of ordinary characters, or a single character with
  595. // a special meaning in markdown, as a plain string, adding to inlines.
  596. var parseString = function(inlines) {
  597. var m;
  598. if ((m = this.match(reMain))) {
  599. inlines.push({ t: 'Str', c: m });
  600. return true;
  601. } else {
  602. return false;
  603. }
  604. };
  605. // Parse a newline. If it was preceded by two spaces, return a hard
  606. // line break; otherwise a soft line break.
  607. var parseNewline = function(inlines) {
  608. var m = this.match(/^ *\n/);
  609. if (m) {
  610. if (m.length > 2) {
  611. inlines.push({ t: 'Hardbreak' });
  612. } else if (m.length > 0) {
  613. inlines.push({ t: 'Softbreak' });
  614. }
  615. return true;
  616. }
  617. return false;
  618. };
  619. // Attempt to parse an image. If the opening '!' is not followed
  620. // by a link, return a literal '!'.
  621. var parseImage = function(inlines) {
  622. if (this.match(/^!/)) {
  623. var link = this.parseLink(inlines);
  624. if (link) {
  625. inlines[inlines.length - 1].t = 'Image';
  626. return true;
  627. } else {
  628. inlines.push({ t: 'Str', c: '!' });
  629. return true;
  630. }
  631. } else {
  632. return false;
  633. }
  634. };
  635. // Attempt to parse a link reference, modifying refmap.
  636. var parseReference = function(s, refmap) {
  637. this.subject = s;
  638. this.pos = 0;
  639. this.label_nest_level = 0;
  640. var rawlabel;
  641. var dest;
  642. var title;
  643. var matchChars;
  644. var startpos = this.pos;
  645. var match;
  646. // label:
  647. matchChars = this.parseLinkLabel();
  648. if (matchChars === 0) {
  649. return 0;
  650. } else {
  651. rawlabel = this.subject.substr(0, matchChars);
  652. }
  653. // colon:
  654. if (this.peek() === C_COLON) {
  655. this.pos++;
  656. } else {
  657. this.pos = startpos;
  658. return 0;
  659. }
  660. // link url
  661. this.spnl();
  662. dest = this.parseLinkDestination();
  663. if (dest === null || dest.length === 0) {
  664. this.pos = startpos;
  665. return 0;
  666. }
  667. var beforetitle = this.pos;
  668. this.spnl();
  669. title = this.parseLinkTitle();
  670. if (title === null) {
  671. title = '';
  672. // rewind before spaces
  673. this.pos = beforetitle;
  674. }
  675. // make sure we're at line end:
  676. if (this.match(/^ *(?:\n|$)/) === null) {
  677. this.pos = startpos;
  678. return 0;
  679. }
  680. var normlabel = normalizeReference(rawlabel);
  681. if (!refmap[normlabel]) {
  682. refmap[normlabel] = { destination: dest, title: title };
  683. }
  684. return this.pos - startpos;
  685. };
  686. // Parse the next inline element in subject, advancing subject position.
  687. // On success, add the result to the inlines list, and return true.
  688. // On failure, return false.
  689. var parseInline = function(inlines) {
  690. var startpos = this.pos;
  691. var origlen = inlines.length;
  692. var c = this.peek();
  693. if (c === -1) {
  694. return false;
  695. }
  696. var res;
  697. switch(c) {
  698. case C_NEWLINE:
  699. case C_SPACE:
  700. res = this.parseNewline(inlines);
  701. break;
  702. case C_BACKSLASH:
  703. res = this.parseBackslash(inlines);
  704. break;
  705. case C_BACKTICK:
  706. res = this.parseBackticks(inlines);
  707. break;
  708. case C_ASTERISK:
  709. case C_UNDERSCORE:
  710. res = this.parseEmphasis(c, inlines);
  711. break;
  712. case C_OPEN_BRACKET:
  713. res = this.parseOpenBracket(inlines);
  714. break;
  715. case C_BANG:
  716. res = this.parseBang(inlines);
  717. break;
  718. case C_CLOSE_BRACKET:
  719. res = this.parseCloseBracket(inlines);
  720. break;
  721. case C_LESSTHAN:
  722. res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines);
  723. break;
  724. case C_AMPERSAND:
  725. res = this.parseEntity(inlines);
  726. break;
  727. default:
  728. res = this.parseString(inlines);
  729. break;
  730. }
  731. if (!res) {
  732. this.pos += 1;
  733. inlines.push({t: 'Str', c: fromCodePoint(c)});
  734. }
  735. return true;
  736. };
  737. // Parse s as a list of inlines, using refmap to resolve references.
  738. var parseInlines = function(s, refmap) {
  739. this.subject = s;
  740. this.pos = 0;
  741. this.refmap = refmap || {};
  742. this.delimiters = null;
  743. var inlines = [];
  744. while (this.parseInline(inlines)) {
  745. }
  746. this.processEmphasis(inlines, null);
  747. return inlines;
  748. };
  749. // The InlineParser object.
  750. function InlineParser(){
  751. return {
  752. subject: '',
  753. label_nest_level: 0, // used by parseLinkLabel method
  754. delimiters: null, // used by parseEmphasis method
  755. pos: 0,
  756. refmap: {},
  757. match: match,
  758. peek: peek,
  759. spnl: spnl,
  760. unescapeString: unescapeString,
  761. parseBackticks: parseBackticks,
  762. parseBackslash: parseBackslash,
  763. parseAutolink: parseAutolink,
  764. parseHtmlTag: parseHtmlTag,
  765. scanDelims: scanDelims,
  766. parseEmphasis: parseEmphasis,
  767. parseLinkTitle: parseLinkTitle,
  768. parseLinkDestination: parseLinkDestination,
  769. parseLinkLabel: parseLinkLabel,
  770. parseOpenBracket: parseOpenBracket,
  771. parseCloseBracket: parseCloseBracket,
  772. parseBang: parseBang,
  773. parseEntity: parseEntity,
  774. parseString: parseString,
  775. parseNewline: parseNewline,
  776. parseReference: parseReference,
  777. parseInline: parseInline,
  778. processEmphasis: processEmphasis,
  779. removeDelimiter: removeDelimiter,
  780. parse: parseInlines
  781. };
  782. }
  783. module.exports = InlineParser;