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