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