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