aboutsummaryrefslogtreecommitdiff
path: root/js/lib/inlines.js
blob: 1f4d194c77e06ace6f914b00d06bf6af29bf605a (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. // lookup rawlabel in refmap
  501. var link = this.refmap[normalizeReference(reflabel)];
  502. if (link) {
  503. dest = link.destination;
  504. title = link.title;
  505. matched = true;
  506. }
  507. }
  508. if (matched) {
  509. this.processEmphasis(link_text, opener.previous);
  510. // remove the part of inlines that became link_text.
  511. // see note above on why we need to do this instead of splice:
  512. for (i = opener.pos; i < inlines.length; i++) {
  513. inlines[i] = null;
  514. }
  515. // processEmphasis will remove this and later delimiters.
  516. // Now, for a link, we also remove earlier link openers.
  517. // (no links in links)
  518. if (!is_image) {
  519. opener = this.delimiters;
  520. closer_above = null;
  521. while (opener !== null) {
  522. if (opener.cc === C_OPEN_BRACKET) {
  523. if (closer_above) {
  524. closer_above.previous = opener.previous;
  525. } else {
  526. this.delimiters = opener.previous;
  527. }
  528. } else {
  529. closer_above = opener;
  530. }
  531. opener = opener.previous;
  532. }
  533. }
  534. inlines.push({t: is_image ? 'Image' : 'Link',
  535. destination: dest,
  536. title: title,
  537. label: link_text});
  538. return true;
  539. } else { // no match
  540. this.removeDelimiter(opener); // remove this opener from stack
  541. this.pos = startpos;
  542. inlines.push(Str("]"));
  543. return true;
  544. }
  545. };
  546. // Attempt to parse an entity, return Entity object if successful.
  547. var parseEntity = function(inlines) {
  548. var m;
  549. if ((m = this.match(reEntityHere))) {
  550. inlines.push({ t: 'Str', c: entityToChar(m) });
  551. return true;
  552. } else {
  553. return false;
  554. }
  555. };
  556. // Parse a run of ordinary characters, or a single character with
  557. // a special meaning in markdown, as a plain string, adding to inlines.
  558. var parseString = function(inlines) {
  559. var m;
  560. if ((m = this.match(reMain))) {
  561. inlines.push({ t: 'Str', c: m });
  562. return true;
  563. } else {
  564. return false;
  565. }
  566. };
  567. // Parse a newline. If it was preceded by two spaces, return a hard
  568. // line break; otherwise a soft line break.
  569. var parseNewline = function(inlines) {
  570. var m = this.match(/^ *\n/);
  571. if (m) {
  572. if (m.length > 2) {
  573. inlines.push({ t: 'Hardbreak' });
  574. } else if (m.length > 0) {
  575. inlines.push({ t: 'Softbreak' });
  576. }
  577. return true;
  578. }
  579. return false;
  580. };
  581. // Attempt to parse an image. If the opening '!' is not followed
  582. // by a link, return a literal '!'.
  583. var parseImage = function(inlines) {
  584. if (this.match(/^!/)) {
  585. var link = this.parseLink(inlines);
  586. if (link) {
  587. inlines[inlines.length - 1].t = 'Image';
  588. return true;
  589. } else {
  590. inlines.push({ t: 'Str', c: '!' });
  591. return true;
  592. }
  593. } else {
  594. return false;
  595. }
  596. };
  597. // Attempt to parse a link reference, modifying refmap.
  598. var parseReference = function(s, refmap) {
  599. this.subject = s;
  600. this.pos = 0;
  601. this.label_nest_level = 0;
  602. var rawlabel;
  603. var dest;
  604. var title;
  605. var matchChars;
  606. var startpos = this.pos;
  607. var match;
  608. // label:
  609. matchChars = this.parseLinkLabel();
  610. if (matchChars === 0) {
  611. return 0;
  612. } else {
  613. rawlabel = this.subject.substr(0, matchChars);
  614. }
  615. // colon:
  616. if (this.peek() === C_COLON) {
  617. this.pos++;
  618. } else {
  619. this.pos = startpos;
  620. return 0;
  621. }
  622. // link url
  623. this.spnl();
  624. dest = this.parseLinkDestination();
  625. if (dest === null || dest.length === 0) {
  626. this.pos = startpos;
  627. return 0;
  628. }
  629. var beforetitle = this.pos;
  630. this.spnl();
  631. title = this.parseLinkTitle();
  632. if (title === null) {
  633. title = '';
  634. // rewind before spaces
  635. this.pos = beforetitle;
  636. }
  637. // make sure we're at line end:
  638. if (this.match(/^ *(?:\n|$)/) === null) {
  639. this.pos = startpos;
  640. return 0;
  641. }
  642. var normlabel = normalizeReference(rawlabel);
  643. if (!refmap[normlabel]) {
  644. refmap[normlabel] = { destination: dest, title: title };
  645. }
  646. return this.pos - startpos;
  647. };
  648. // Parse the next inline element in subject, advancing subject position.
  649. // On success, add the result to the inlines list, and return true.
  650. // On failure, return false.
  651. var parseInline = function(inlines) {
  652. var startpos = this.pos;
  653. var origlen = inlines.length;
  654. var c = this.peek();
  655. if (c === -1) {
  656. return false;
  657. }
  658. var res;
  659. switch(c) {
  660. case C_NEWLINE:
  661. case C_SPACE:
  662. res = this.parseNewline(inlines);
  663. break;
  664. case C_BACKSLASH:
  665. res = this.parseBackslash(inlines);
  666. break;
  667. case C_BACKTICK:
  668. res = this.parseBackticks(inlines);
  669. break;
  670. case C_ASTERISK:
  671. case C_UNDERSCORE:
  672. res = this.parseEmphasis(c, inlines);
  673. break;
  674. case C_OPEN_BRACKET:
  675. res = this.parseOpenBracket(inlines);
  676. break;
  677. case C_BANG:
  678. res = this.parseBang(inlines);
  679. break;
  680. case C_CLOSE_BRACKET:
  681. res = this.parseCloseBracket(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. parseOpenBracket: parseOpenBracket,
  733. parseCloseBracket: parseCloseBracket,
  734. parseBang: parseBang,
  735. parseEntity: parseEntity,
  736. parseString: parseString,
  737. parseNewline: parseNewline,
  738. parseReference: parseReference,
  739. parseInline: parseInline,
  740. processEmphasis: processEmphasis,
  741. removeDelimiter: removeDelimiter,
  742. parse: parseInlines
  743. };
  744. }
  745. module.exports = InlineParser;