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