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