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