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