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