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