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