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