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