aboutsummaryrefslogtreecommitdiff
path: root/js/lib/inlines.js
blob: 0b40dfddee70358e44e6754a95fcfb8843503b2e (plain)
  1. var Node = require('./node');
  2. var fromCodePoint = require('./from-code-point.js');
  3. var entityToChar = require('./html5-entities.js').entityToChar;
  4. // Constants for character codes:
  5. var C_NEWLINE = 10;
  6. var C_ASTERISK = 42;
  7. var C_UNDERSCORE = 95;
  8. var C_BACKTICK = 96;
  9. var C_OPEN_BRACKET = 91;
  10. var C_CLOSE_BRACKET = 93;
  11. var C_LESSTHAN = 60;
  12. var C_BANG = 33;
  13. var C_BACKSLASH = 92;
  14. var C_AMPERSAND = 38;
  15. var C_OPEN_PAREN = 40;
  16. var C_COLON = 58;
  17. // Some regexps used in inline parser:
  18. var ESCAPABLE = '[!"#$%&\'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]';
  19. var ESCAPED_CHAR = '\\\\' + ESCAPABLE;
  20. var REG_CHAR = '[^\\\\()\\x00-\\x20]';
  21. var IN_PARENS_NOSP = '\\((' + REG_CHAR + '|' + ESCAPED_CHAR + ')*\\)';
  22. var TAGNAME = '[A-Za-z][A-Za-z0-9]*';
  23. var ATTRIBUTENAME = '[a-zA-Z_:][a-zA-Z0-9:._-]*';
  24. var UNQUOTEDVALUE = "[^\"'=<>`\\x00-\\x20]+";
  25. var SINGLEQUOTEDVALUE = "'[^']*'";
  26. var DOUBLEQUOTEDVALUE = '"[^"]*"';
  27. var ATTRIBUTEVALUE = "(?:" + UNQUOTEDVALUE + "|" + SINGLEQUOTEDVALUE + "|" + DOUBLEQUOTEDVALUE + ")";
  28. var ATTRIBUTEVALUESPEC = "(?:" + "\\s*=" + "\\s*" + ATTRIBUTEVALUE + ")";
  29. var ATTRIBUTE = "(?:" + "\\s+" + ATTRIBUTENAME + ATTRIBUTEVALUESPEC + "?)";
  30. var OPENTAG = "<" + TAGNAME + ATTRIBUTE + "*" + "\\s*/?>";
  31. var CLOSETAG = "</" + TAGNAME + "\\s*[>]";
  32. var HTMLCOMMENT = "<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->";
  33. var PROCESSINGINSTRUCTION = "[<][?].*?[?][>]";
  34. var DECLARATION = "<![A-Z]+" + "\\s+[^>]*>";
  35. var CDATA = "<!\\[CDATA\\[[\\s\\S]*?\]\\]>";
  36. var HTMLTAG = "(?:" + OPENTAG + "|" + CLOSETAG + "|" + HTMLCOMMENT + "|" +
  37. PROCESSINGINSTRUCTION + "|" + DECLARATION + "|" + CDATA + ")";
  38. var ENTITY = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});";
  39. var rePunctuation = new RegExp(/^[\u2000-\u206F\u2E00-\u2E7F\\'!"#\$%&\(\)\*\+,\-\.\/:;<=>\?@\[\]\^_`\{\|\}~]/);
  40. var reHtmlTag = new RegExp('^' + HTMLTAG, 'i');
  41. var reLinkTitle = new RegExp(
  42. '^(?:"(' + ESCAPED_CHAR + '|[^"\\x00])*"' +
  43. '|' +
  44. '\'(' + ESCAPED_CHAR + '|[^\'\\x00])*\'' +
  45. '|' +
  46. '\\((' + ESCAPED_CHAR + '|[^)\\x00])*\\))');
  47. var reLinkDestinationBraces = new RegExp(
  48. '^(?:[<](?:[^<>\\n\\\\\\x00]' + '|' + ESCAPED_CHAR + '|' + '\\\\)*[>])');
  49. var reLinkDestination = new RegExp(
  50. '^(?:' + REG_CHAR + '+|' + ESCAPED_CHAR + '|' + IN_PARENS_NOSP + ')*');
  51. var reEscapable = new RegExp(ESCAPABLE);
  52. var reEntityHere = new RegExp('^' + ENTITY, 'i');
  53. var reEntityOrEscapedChar = new RegExp('\\\\' + ESCAPABLE + '|' + ENTITY, 'gi');
  54. // Matches a string of non-special characters.
  55. var reMain = /^[^\n`\[\]\\!<&*_]+/m;
  56. var unescapeChar = function(s) {
  57. "use strict";
  58. if (s[0] === '\\') {
  59. return s[1];
  60. } else {
  61. return entityToChar(s);
  62. }
  63. };
  64. // Replace entities and backslash escapes with literal characters.
  65. var unescapeString = function(s) {
  66. "use strict";
  67. return s.replace(reEntityOrEscapedChar, unescapeChar);
  68. };
  69. // Normalize reference label: collapse internal whitespace
  70. // to single space, remove leading/trailing whitespace, case fold.
  71. var normalizeReference = function(s) {
  72. "use strict";
  73. return s.trim()
  74. .replace(/\s+/, ' ')
  75. .toUpperCase();
  76. };
  77. var text = function(s) {
  78. "use strict";
  79. var node = new Node('Text');
  80. node.literal = s;
  81. return node;
  82. };
  83. // INLINE PARSER
  84. // These are methods of an InlineParser object, defined below.
  85. // An InlineParser keeps track of a subject (a string to be
  86. // parsed) and a position in that subject.
  87. // If re matches at current position in the subject, advance
  88. // position in subject and return the match; otherwise return null.
  89. var match = function(re) {
  90. "use strict";
  91. var m = re.exec(this.subject.slice(this.pos));
  92. if (m) {
  93. this.pos += m.index + m[0].length;
  94. return m[0];
  95. } else {
  96. return null;
  97. }
  98. };
  99. // Returns the code for the character at the current subject position, or -1
  100. // there are no more characters.
  101. var peek = function() {
  102. "use strict";
  103. if (this.pos < this.subject.length) {
  104. return this.subject.charCodeAt(this.pos);
  105. } else {
  106. return -1;
  107. }
  108. };
  109. // Parse zero or more space characters, including at most one newline
  110. var spnl = function() {
  111. "use strict";
  112. this.match(/^ *(?:\n *)?/);
  113. return 1;
  114. };
  115. // All of the parsers below try to match something at the current position
  116. // in the subject. If they succeed in matching anything, they
  117. // return the inline matched, advancing the subject.
  118. // Attempt to parse backticks, adding either a backtick code span or a
  119. // literal sequence of backticks.
  120. var parseBackticks = function(block) {
  121. "use strict";
  122. var ticks = this.match(/^`+/);
  123. if (!ticks) {
  124. return 0;
  125. }
  126. var afterOpenTicks = this.pos;
  127. var foundCode = false;
  128. var matched;
  129. var node;
  130. while (!foundCode && (matched = this.match(/`+/m))) {
  131. if (matched === ticks) {
  132. node = new Node('Code');
  133. node.literal = this.subject.slice(afterOpenTicks,
  134. this.pos - ticks.length)
  135. .replace(/[ \n]+/g, ' ')
  136. .trim();
  137. block.appendChild(node);
  138. return true;
  139. }
  140. }
  141. // If we got here, we didn't match a closing backtick sequence.
  142. this.pos = afterOpenTicks;
  143. block.appendChild(text(ticks));
  144. return true;
  145. };
  146. // Parse a backslash-escaped special character, adding either the escaped
  147. // character, a hard line break (if the backslash is followed by a newline),
  148. // or a literal backslash to the block's children.
  149. var parseBackslash = function(block) {
  150. "use strict";
  151. var subj = this.subject,
  152. pos = this.pos;
  153. var node;
  154. if (subj.charCodeAt(pos) === C_BACKSLASH) {
  155. if (subj.charAt(pos + 1) === '\n') {
  156. this.pos = this.pos + 2;
  157. node = new Node('Hardbreak');
  158. block.appendChild(node);
  159. } else if (reEscapable.test(subj.charAt(pos + 1))) {
  160. this.pos = this.pos + 2;
  161. block.appendChild(text(subj.charAt(pos + 1)));
  162. } else {
  163. this.pos++;
  164. block.appendChild(text('\\'));
  165. }
  166. return true;
  167. } else {
  168. return false;
  169. }
  170. };
  171. // Attempt to parse an autolink (URL or email in pointy brackets).
  172. var parseAutolink = function(block) {
  173. "use strict";
  174. var m;
  175. var dest;
  176. var node;
  177. if ((m = this.match(/^<([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)>/))) { // email autolink
  178. dest = m.slice(1, -1);
  179. node = new Node('Link');
  180. node.destination = 'mailto:' + encodeURI(unescape(dest));
  181. node.appendChild(text(dest));
  182. block.appendChild(node);
  183. return true;
  184. } else if ((m = this.match(/^<(?:coap|doi|javascript|aaa|aaas|about|acap|cap|cid|crid|data|dav|dict|dns|file|ftp|geo|go|gopher|h323|http|https|iax|icap|im|imap|info|ipp|iris|iris.beep|iris.xpc|iris.xpcs|iris.lwz|ldap|mailto|mid|msrp|msrps|mtqp|mupdate|news|nfs|ni|nih|nntp|opaquelocktoken|pop|pres|rtsp|service|session|shttp|sieve|sip|sips|sms|snmp|soap.beep|soap.beeps|tag|tel|telnet|tftp|thismessage|tn3270|tip|tv|urn|vemmi|ws|wss|xcon|xcon-userid|xmlrpc.beep|xmlrpc.beeps|xmpp|z39.50r|z39.50s|adiumxtra|afp|afs|aim|apt|attachment|aw|beshare|bitcoin|bolo|callto|chrome|chrome-extension|com-eventbrite-attendee|content|cvs|dlna-playsingle|dlna-playcontainer|dtn|dvb|ed2k|facetime|feed|finger|fish|gg|git|gizmoproject|gtalk|hcp|icon|ipn|irc|irc6|ircs|itms|jar|jms|keyparc|lastfm|ldaps|magnet|maps|market|message|mms|ms-help|msnim|mumble|mvn|notes|oid|palm|paparazzi|platform|proxy|psyc|query|res|resource|rmi|rsync|rtmp|secondlife|sftp|sgn|skype|smb|soldat|spotify|ssh|steam|svn|teamspeak|things|udp|unreal|ut2004|ventrilo|view-source|webcal|wtai|wyciwyg|xfire|xri|ymsgr):[^<>\x00-\x20]*>/i))) {
  185. dest = m.slice(1, -1);
  186. node = new Node('Link');
  187. node.destination = encodeURI(unescape(dest));
  188. node.appendChild(text(dest));
  189. block.appendChild(node);
  190. return true;
  191. } else {
  192. return false;
  193. }
  194. };
  195. // Attempt to parse a raw HTML tag.
  196. var parseHtmlTag = function(block) {
  197. "use strict";
  198. var m = this.match(reHtmlTag);
  199. var node;
  200. if (m) {
  201. node = new Node('Html');
  202. node.literal = m;
  203. block.appendChild(node);
  204. return true;
  205. } else {
  206. return false;
  207. }
  208. };
  209. // Scan a sequence of characters with code cc, and return information about
  210. // the number of delimiters and whether they are positioned such that
  211. // they can open and/or close emphasis or strong emphasis. A utility
  212. // function for strong/emph parsing.
  213. var scanDelims = function(cc) {
  214. "use strict";
  215. var numdelims = 0;
  216. var char_before, char_after, cc_after;
  217. var startpos = this.pos;
  218. char_before = this.pos === 0 ? '\n' :
  219. this.subject.charAt(this.pos - 1);
  220. while (this.peek() === cc) {
  221. numdelims++;
  222. this.pos++;
  223. }
  224. cc_after = this.peek();
  225. if (cc_after === -1) {
  226. char_after = '\n';
  227. } else {
  228. char_after = fromCodePoint(cc_after);
  229. }
  230. var can_open = numdelims > 0 && !(/\s/.test(char_after)) &&
  231. !(rePunctuation.test(char_after) &&
  232. !(/\s/.test(char_before)) &&
  233. !(rePunctuation.test(char_before)));
  234. var can_close = numdelims > 0 && !(/\s/.test(char_before)) &&
  235. !(rePunctuation.test(char_before) &&
  236. !(/\s/.test(char_after)) &&
  237. !(rePunctuation.test(char_after)));
  238. if (cc === C_UNDERSCORE) {
  239. can_open = can_open && !((/[a-z0-9]/i).test(char_before));
  240. can_close = can_close && !((/[a-z0-9]/i).test(char_after));
  241. }
  242. this.pos = startpos;
  243. return { numdelims: numdelims,
  244. can_open: can_open,
  245. can_close: can_close };
  246. };
  247. // Attempt to parse emphasis or strong emphasis.
  248. var parseEmphasis = function(cc, block) {
  249. "use strict";
  250. var res = this.scanDelims(cc);
  251. var numdelims = res.numdelims;
  252. var startpos = this.pos;
  253. if (numdelims === 0) {
  254. return false;
  255. }
  256. this.pos += numdelims;
  257. var node = text(this.subject.slice(startpos, this.pos));
  258. block.appendChild(node);
  259. // Add entry to stack for this opener
  260. this.delimiters = { cc: cc,
  261. numdelims: numdelims,
  262. node: node,
  263. previous: this.delimiters,
  264. next: null,
  265. can_open: res.can_open,
  266. can_close: res.can_close,
  267. active: true };
  268. if (this.delimiters.previous !== null) {
  269. this.delimiters.previous.next = this.delimiters;
  270. }
  271. return true;
  272. };
  273. var removeDelimiter = function(delim) {
  274. "use strict";
  275. if (delim.previous !== null) {
  276. delim.previous.next = delim.next;
  277. }
  278. if (delim.next === null) {
  279. // top of stack
  280. this.delimiters = delim.previous;
  281. } else {
  282. delim.next.previous = delim.previous;
  283. }
  284. };
  285. var processEmphasis = function(block, stack_bottom) {
  286. "use strict";
  287. var opener, closer;
  288. var opener_inl, closer_inl;
  289. var nextstack, tempstack;
  290. var use_delims;
  291. var tmp, next;
  292. // find first closer above stack_bottom:
  293. closer = this.delimiters;
  294. while (closer !== null && closer.previous !== stack_bottom) {
  295. closer = closer.previous;
  296. }
  297. // move forward, looking for closers, and handling each
  298. while (closer !== null) {
  299. if (closer.can_close && (closer.cc === C_UNDERSCORE || closer.cc === C_ASTERISK)) {
  300. // found emphasis closer. now look back for first matching opener:
  301. opener = closer.previous;
  302. while (opener !== null && opener !== stack_bottom) {
  303. if (opener.cc === closer.cc && opener.can_open) {
  304. break;
  305. }
  306. opener = opener.previous;
  307. }
  308. if (opener !== null && opener !== stack_bottom) {
  309. // calculate actual number of delimiters used from this closer
  310. if (closer.numdelims < 3 || opener.numdelims < 3) {
  311. use_delims = closer.numdelims <= opener.numdelims ?
  312. closer.numdelims : opener.numdelims;
  313. } else {
  314. use_delims = closer.numdelims % 2 === 0 ? 2 : 1;
  315. }
  316. opener_inl = opener.node;
  317. closer_inl = closer.node;
  318. // remove used delimiters from stack elts and inlines
  319. opener.numdelims -= use_delims;
  320. closer.numdelims -= use_delims;
  321. opener_inl.literal =
  322. opener_inl.literal.slice(0,
  323. opener_inl.literal.length - use_delims);
  324. closer_inl.literal =
  325. closer_inl.literal.slice(0,
  326. closer_inl.literal.length - use_delims);
  327. // build contents for new emph element
  328. var emph = new Node(use_delims === 1 ? 'Emph' : 'Strong');
  329. tmp = opener_inl.next;
  330. while (tmp && tmp !== closer_inl) {
  331. next = tmp.next;
  332. tmp.unlink();
  333. emph.appendChild(tmp);
  334. tmp = next;
  335. }
  336. opener_inl.insertAfter(emph);
  337. // remove elts btw opener and closer in delimiters stack
  338. tempstack = closer.previous;
  339. while (tempstack !== null && tempstack !== opener) {
  340. nextstack = tempstack.previous;
  341. this.removeDelimiter(tempstack);
  342. tempstack = nextstack;
  343. }
  344. // if opener has 0 delims, remove it and the inline
  345. if (opener.numdelims === 0) {
  346. opener_inl.unlink();
  347. this.removeDelimiter(opener);
  348. }
  349. if (closer.numdelims === 0) {
  350. closer_inl.unlink();
  351. tempstack = closer.next;
  352. this.removeDelimiter(closer);
  353. closer = tempstack;
  354. }
  355. } else {
  356. closer = closer.next;
  357. }
  358. } else {
  359. closer = closer.next;
  360. }
  361. }
  362. // remove all delimiters
  363. while (this.delimiters !== stack_bottom) {
  364. this.removeDelimiter(this.delimiters);
  365. }
  366. };
  367. // Attempt to parse link title (sans quotes), returning the string
  368. // or null if no match.
  369. var parseLinkTitle = function() {
  370. "use strict";
  371. var title = this.match(reLinkTitle);
  372. if (title) {
  373. // chop off quotes from title and unescape:
  374. return unescapeString(title.substr(1, title.length - 2));
  375. } else {
  376. return null;
  377. }
  378. };
  379. // Attempt to parse link destination, returning the string or
  380. // null if no match.
  381. var parseLinkDestination = function() {
  382. "use strict";
  383. var res = this.match(reLinkDestinationBraces);
  384. if (res) { // chop off surrounding <..>:
  385. return encodeURI(unescape(unescapeString(res.substr(1, res.length - 2))));
  386. } else {
  387. res = this.match(reLinkDestination);
  388. if (res !== null) {
  389. return encodeURI(unescape(unescapeString(res)));
  390. } else {
  391. return null;
  392. }
  393. }
  394. };
  395. // Attempt to parse a link label, returning number of characters parsed.
  396. var parseLinkLabel = function() {
  397. "use strict";
  398. var m = this.match(/^\[(?:[^\\\[\]]|\\[\[\]]){0,1000}\]/);
  399. return m === null ? 0 : m.length;
  400. };
  401. // Add open bracket to delimiter stack and add a text node to block's children.
  402. var parseOpenBracket = function(block) {
  403. "use strict";
  404. var startpos = this.pos;
  405. this.pos += 1;
  406. var node = text('[');
  407. block.appendChild(node);
  408. // Add entry to stack for this opener
  409. this.delimiters = { cc: C_OPEN_BRACKET,
  410. numdelims: 1,
  411. node: node,
  412. previous: this.delimiters,
  413. next: null,
  414. can_open: true,
  415. can_close: false,
  416. index: startpos,
  417. active: true };
  418. if (this.delimiters.previous !== null) {
  419. this.delimiters.previous.next = this.delimiters;
  420. }
  421. return true;
  422. };
  423. // IF next character is [, and ! delimiter to delimiter stack and
  424. // add a text node to block's children. Otherwise just add a text node.
  425. var parseBang = function(block) {
  426. "use strict";
  427. var startpos = this.pos;
  428. this.pos += 1;
  429. if (this.peek() === C_OPEN_BRACKET) {
  430. this.pos += 1;
  431. var node = text('![');
  432. block.appendChild(node);
  433. // Add entry to stack for this opener
  434. this.delimiters = { cc: C_BANG,
  435. numdelims: 1,
  436. node: node,
  437. previous: this.delimiters,
  438. next: null,
  439. can_open: true,
  440. can_close: false,
  441. index: startpos + 1,
  442. active: true };
  443. if (this.delimiters.previous !== null) {
  444. this.delimiters.previous.next = this.delimiters;
  445. }
  446. } else {
  447. block.appendChild(text('!'));
  448. }
  449. return true;
  450. };
  451. // Try to match close bracket against an opening in the delimiter
  452. // stack. Add either a link or image, or a plain [ character,
  453. // to block's children. If there is a matching delimiter,
  454. // remove it from the delimiter stack.
  455. var parseCloseBracket = function(block) {
  456. "use strict";
  457. var startpos;
  458. var is_image;
  459. var dest;
  460. var title;
  461. var matched = false;
  462. var reflabel;
  463. var opener;
  464. this.pos += 1;
  465. startpos = this.pos;
  466. // look through stack of delimiters for a [ or ![
  467. opener = this.delimiters;
  468. while (opener !== null) {
  469. if (opener.cc === C_OPEN_BRACKET || opener.cc === C_BANG) {
  470. break;
  471. }
  472. opener = opener.previous;
  473. }
  474. if (opener === null) {
  475. // no matched opener, just return a literal
  476. block.appendChild(text(']'));
  477. return true;
  478. }
  479. if (!opener.active) {
  480. // no matched opener, just return a literal
  481. block.appendChild(text(']'));
  482. // take opener off emphasis stack
  483. this.removeDelimiter(opener);
  484. return true;
  485. }
  486. // If we got here, open is a potential opener
  487. is_image = opener.cc === C_BANG;
  488. // Check to see if we have a link/image
  489. // Inline link?
  490. if (this.peek() === C_OPEN_PAREN) {
  491. this.pos++;
  492. if (this.spnl() &&
  493. ((dest = this.parseLinkDestination()) !== null) &&
  494. this.spnl() &&
  495. // make sure there's a space before the title:
  496. (/^\s/.test(this.subject.charAt(this.pos - 1)) &&
  497. (title = this.parseLinkTitle() || '') || true) &&
  498. this.spnl() &&
  499. this.match(/^\)/)) {
  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 = / *$/.exec(lastc.literal)[0].length;
  593. if (sps > 0) {
  594. lastc.literal = lastc.literal.replace(/ *$/, '');
  595. }
  596. block.appendChild(new Node(sps >= 2 ? 'Hardbreak' : 'Softbreak'));
  597. } else {
  598. block.appendChild(new Node('Softbreak'));
  599. }
  600. this.match(/^ */); // 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 c = this.peek();
  659. if (c === -1) {
  660. return false;
  661. }
  662. var res;
  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. unescapeString: unescapeString,
  728. parseBackticks: parseBackticks,
  729. parseBackslash: parseBackslash,
  730. parseAutolink: parseAutolink,
  731. parseHtmlTag: parseHtmlTag,
  732. scanDelims: scanDelims,
  733. parseEmphasis: parseEmphasis,
  734. parseLinkTitle: parseLinkTitle,
  735. parseLinkDestination: parseLinkDestination,
  736. parseLinkLabel: parseLinkLabel,
  737. parseOpenBracket: parseOpenBracket,
  738. parseCloseBracket: parseCloseBracket,
  739. parseBang: parseBang,
  740. parseEntity: parseEntity,
  741. parseString: parseString,
  742. parseNewline: parseNewline,
  743. parseReference: parseReference,
  744. parseInline: parseInline,
  745. processEmphasis: processEmphasis,
  746. removeDelimiter: removeDelimiter,
  747. parse: parseInlines
  748. };
  749. }
  750. module.exports = InlineParser;