aboutsummaryrefslogtreecommitdiff
path: root/js/lib/inlines.js
blob: 994cc1e180a2d5bb74ff18ec1ab94ab5c2b15195 (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 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 match;
  113. while (!foundCode && (match = this.match(/`+/m))) {
  114. if (match === 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. 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. "use strict";
  275. var opener, closer;
  276. var opener_inl, closer_inl;
  277. var nextstack, tempstack;
  278. var use_delims;
  279. var contents;
  280. var emph;
  281. var i;
  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 m = this.match(/^\[(?:[^\\\[\]]|\\[\[\]]){0,1000}\]/);
  382. return m === null ? 0 : m.length;
  383. };
  384. // Add open bracket to delimiter stack and add a Str to inlines.
  385. var parseOpenBracket = function(inlines) {
  386. var startpos = this.pos;
  387. this.pos += 1;
  388. inlines.push(Str("["));
  389. // Add entry to stack for this opener
  390. this.delimiters = { cc: C_OPEN_BRACKET,
  391. numdelims: 1,
  392. pos: inlines.length - 1,
  393. previous: this.delimiters,
  394. next: null,
  395. can_open: true,
  396. can_close: false,
  397. index: startpos };
  398. if (this.delimiters.previous !== null) {
  399. this.delimiters.previous.next = this.delimiters;
  400. }
  401. return true;
  402. };
  403. // IF next character is [, and ! delimiter to delimiter stack and
  404. // add a Str to inlines. Otherwise just add a Str.
  405. var parseBang = function(inlines) {
  406. var startpos = this.pos;
  407. this.pos += 1;
  408. if (this.peek() === C_OPEN_BRACKET) {
  409. this.pos += 1;
  410. inlines.push(Str("!["));
  411. // Add entry to stack for this opener
  412. this.delimiters = { cc: C_BANG,
  413. numdelims: 1,
  414. pos: inlines.length - 1,
  415. previous: this.delimiters,
  416. next: null,
  417. can_open: true,
  418. can_close: false,
  419. index: startpos + 1 };
  420. if (this.delimiters.previous !== null) {
  421. this.delimiters.previous.next = this.delimiters;
  422. }
  423. } else {
  424. inlines.push(Str("!"));
  425. }
  426. return true;
  427. };
  428. // Try to match close bracket against an opening in the delimiter
  429. // stack. Add either a link or image, or a plain [ character,
  430. // to the inlines stack. If there is a matching delimiter,
  431. // remove it from the delimiter stack.
  432. var parseCloseBracket = function(inlines) {
  433. var startpos;
  434. var is_image;
  435. var dest;
  436. var title;
  437. var matched = false;
  438. var link_text;
  439. var i;
  440. var reflabel;
  441. var opener, closer_above;
  442. this.pos += 1;
  443. startpos = this.pos;
  444. // look through stack of delimiters for a [ or !
  445. opener = this.delimiters;
  446. while (opener !== null) {
  447. if (opener.cc === C_OPEN_BRACKET || opener.cc === C_BANG) {
  448. break;
  449. }
  450. opener = opener.previous;
  451. }
  452. if (opener === null) {
  453. // no matched opener, just return a literal
  454. inlines.push(Str("]"));
  455. return true;
  456. }
  457. // If we got here, open is a potential opener
  458. is_image = opener.cc === C_BANG;
  459. // instead of copying a slice, we null out the
  460. // parts of inlines that don't correspond to link_text;
  461. // later, we'll collapse them. This is awkward, and could
  462. // be simplified if we made inlines a linked list rather than
  463. // an array:
  464. link_text = inlines.slice(0);
  465. for (i = 0; i < opener.pos + 1; i++) {
  466. link_text[i] = null;
  467. }
  468. // Check to see if we have a link/image
  469. // Inline link?
  470. if (this.peek() === C_OPEN_PAREN) {
  471. this.pos++;
  472. if (this.spnl() &&
  473. ((dest = this.parseLinkDestination()) !== null) &&
  474. this.spnl() &&
  475. // make sure there's a space before the title:
  476. (/^\s/.test(this.subject.charAt(this.pos - 1)) &&
  477. (title = this.parseLinkTitle() || '') || true) &&
  478. this.spnl() &&
  479. this.match(/^\)/)) {
  480. matched = true;
  481. }
  482. } else {
  483. // Next, see if there's a link label
  484. var savepos = this.pos;
  485. this.spnl();
  486. var beforelabel = this.pos;
  487. var n = this.parseLinkLabel();
  488. if (n === 0 || n === 2) {
  489. // empty or missing second label
  490. reflabel = this.subject.slice(opener.index, startpos);
  491. } else {
  492. reflabel = this.subject.slice(beforelabel, beforelabel + n);
  493. }
  494. if (n === 0) {
  495. // If shortcut reference link, rewind before spaces we skipped.
  496. this.pos = savepos;
  497. }
  498. // lookup rawlabel in refmap
  499. var link = this.refmap[normalizeReference(reflabel)];
  500. if (link) {
  501. dest = link.destination;
  502. title = link.title;
  503. matched = true;
  504. }
  505. }
  506. if (matched) {
  507. this.processEmphasis(link_text, opener.previous);
  508. // remove the part of inlines that became link_text.
  509. // see note above on why we need to do this instead of splice:
  510. for (i = opener.pos; i < inlines.length; i++) {
  511. inlines[i] = null;
  512. }
  513. // processEmphasis will remove this and later delimiters.
  514. // Now, for a link, we also remove earlier link openers.
  515. // (no links in links)
  516. if (!is_image) {
  517. opener = this.delimiters;
  518. closer_above = null;
  519. while (opener !== null) {
  520. if (opener.cc === C_OPEN_BRACKET) {
  521. this.removeDelimiter(opener); // remove this opener from stack
  522. }
  523. opener = opener.previous;
  524. }
  525. }
  526. inlines.push({t: is_image ? 'Image' : 'Link',
  527. destination: dest,
  528. title: title,
  529. label: link_text});
  530. return true;
  531. } else { // no match
  532. this.removeDelimiter(opener); // remove this opener from stack
  533. this.pos = startpos;
  534. inlines.push(Str("]"));
  535. return true;
  536. }
  537. };
  538. // Attempt to parse an entity, return Entity object if successful.
  539. var parseEntity = function(inlines) {
  540. var m;
  541. if ((m = this.match(reEntityHere))) {
  542. inlines.push({ t: 'Text', c: entityToChar(m) });
  543. return true;
  544. } else {
  545. return false;
  546. }
  547. };
  548. // Parse a run of ordinary characters, or a single character with
  549. // a special meaning in markdown, as a plain string, adding to inlines.
  550. var parseString = function(inlines) {
  551. var m;
  552. if ((m = this.match(reMain))) {
  553. inlines.push({ t: 'Text', c: m });
  554. return true;
  555. } else {
  556. return false;
  557. }
  558. };
  559. // Parse a newline. If it was preceded by two spaces, return a hard
  560. // line break; otherwise a soft line break.
  561. var parseNewline = function(inlines) {
  562. var m = this.match(/^ *\n/);
  563. if (m) {
  564. if (m.length > 2) {
  565. inlines.push({ t: 'Hardbreak' });
  566. } else if (m.length > 0) {
  567. inlines.push({ t: 'Softbreak' });
  568. }
  569. return true;
  570. }
  571. return false;
  572. };
  573. // Attempt to parse a link reference, modifying refmap.
  574. var parseReference = function(s, refmap) {
  575. this.subject = s;
  576. this.pos = 0;
  577. this.label_nest_level = 0;
  578. var rawlabel;
  579. var dest;
  580. var title;
  581. var matchChars;
  582. var startpos = this.pos;
  583. // label:
  584. matchChars = this.parseLinkLabel();
  585. if (matchChars === 0) {
  586. return 0;
  587. } else {
  588. rawlabel = this.subject.substr(0, matchChars);
  589. }
  590. // colon:
  591. if (this.peek() === C_COLON) {
  592. this.pos++;
  593. } else {
  594. this.pos = startpos;
  595. return 0;
  596. }
  597. // link url
  598. this.spnl();
  599. dest = this.parseLinkDestination();
  600. if (dest === null || dest.length === 0) {
  601. this.pos = startpos;
  602. return 0;
  603. }
  604. var beforetitle = this.pos;
  605. this.spnl();
  606. title = this.parseLinkTitle();
  607. if (title === null) {
  608. title = '';
  609. // rewind before spaces
  610. this.pos = beforetitle;
  611. }
  612. // make sure we're at line end:
  613. if (this.match(/^ *(?:\n|$)/) === null) {
  614. this.pos = startpos;
  615. return 0;
  616. }
  617. var normlabel = normalizeReference(rawlabel);
  618. if (!refmap[normlabel]) {
  619. refmap[normlabel] = { destination: dest, title: title };
  620. }
  621. return this.pos - startpos;
  622. };
  623. // Parse the next inline element in subject, advancing subject position.
  624. // On success, add the result to the inlines list, and return true.
  625. // On failure, return false.
  626. var parseInline = function(inlines) {
  627. "use strict";
  628. var c = this.peek();
  629. if (c === -1) {
  630. return false;
  631. }
  632. var res;
  633. switch(c) {
  634. case C_NEWLINE:
  635. case C_SPACE:
  636. res = this.parseNewline(inlines);
  637. break;
  638. case C_BACKSLASH:
  639. res = this.parseBackslash(inlines);
  640. break;
  641. case C_BACKTICK:
  642. res = this.parseBackticks(inlines);
  643. break;
  644. case C_ASTERISK:
  645. case C_UNDERSCORE:
  646. res = this.parseEmphasis(c, inlines);
  647. break;
  648. case C_OPEN_BRACKET:
  649. res = this.parseOpenBracket(inlines);
  650. break;
  651. case C_BANG:
  652. res = this.parseBang(inlines);
  653. break;
  654. case C_CLOSE_BRACKET:
  655. res = this.parseCloseBracket(inlines);
  656. break;
  657. case C_LESSTHAN:
  658. res = this.parseAutolink(inlines) || this.parseHtmlTag(inlines);
  659. break;
  660. case C_AMPERSAND:
  661. res = this.parseEntity(inlines);
  662. break;
  663. default:
  664. res = this.parseString(inlines);
  665. break;
  666. }
  667. if (!res) {
  668. this.pos += 1;
  669. inlines.push({t: 'Text', c: fromCodePoint(c)});
  670. }
  671. return true;
  672. };
  673. // Parse s as a list of inlines, using refmap to resolve references.
  674. var parseInlines = function(s, refmap) {
  675. this.subject = s;
  676. this.pos = 0;
  677. this.refmap = refmap || {};
  678. this.delimiters = null;
  679. var inlines = [];
  680. while (this.parseInline(inlines)) {
  681. }
  682. this.processEmphasis(inlines, null);
  683. return inlines;
  684. };
  685. // The InlineParser object.
  686. function InlineParser(){
  687. "use strict";
  688. return {
  689. subject: '',
  690. label_nest_level: 0, // used by parseLinkLabel method
  691. delimiters: null, // used by parseEmphasis method
  692. pos: 0,
  693. refmap: {},
  694. match: match,
  695. peek: peek,
  696. spnl: spnl,
  697. unescapeString: unescapeString,
  698. parseBackticks: parseBackticks,
  699. parseBackslash: parseBackslash,
  700. parseAutolink: parseAutolink,
  701. parseHtmlTag: parseHtmlTag,
  702. scanDelims: scanDelims,
  703. parseEmphasis: parseEmphasis,
  704. parseLinkTitle: parseLinkTitle,
  705. parseLinkDestination: parseLinkDestination,
  706. parseLinkLabel: parseLinkLabel,
  707. parseOpenBracket: parseOpenBracket,
  708. parseCloseBracket: parseCloseBracket,
  709. parseBang: parseBang,
  710. parseEntity: parseEntity,
  711. parseString: parseString,
  712. parseNewline: parseNewline,
  713. parseReference: parseReference,
  714. parseInline: parseInline,
  715. processEmphasis: processEmphasis,
  716. removeDelimiter: removeDelimiter,
  717. parse: parseInlines
  718. };
  719. }
  720. module.exports = InlineParser;