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