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