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