backticks.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Parse backticks
  2. 'use strict';
  3. module.exports = function backtick(state, silent) {
  4. var start, max, marker, token, matchStart, matchEnd, openerLength, closerLength,
  5. pos = state.pos,
  6. ch = state.src.charCodeAt(pos);
  7. if (ch !== 0x60/* ` */) { return false; }
  8. start = pos;
  9. pos++;
  10. max = state.posMax;
  11. // scan marker length
  12. while (pos < max && state.src.charCodeAt(pos) === 0x60/* ` */) { pos++; }
  13. marker = state.src.slice(start, pos);
  14. openerLength = marker.length;
  15. if (state.backticksScanned && (state.backticks[openerLength] || 0) <= start) {
  16. if (!silent) state.pending += marker;
  17. state.pos += openerLength;
  18. return true;
  19. }
  20. matchStart = matchEnd = pos;
  21. // Nothing found in the cache, scan until the end of the line (or until marker is found)
  22. while ((matchStart = state.src.indexOf('`', matchEnd)) !== -1) {
  23. matchEnd = matchStart + 1;
  24. // scan marker length
  25. while (matchEnd < max && state.src.charCodeAt(matchEnd) === 0x60/* ` */) { matchEnd++; }
  26. closerLength = matchEnd - matchStart;
  27. if (closerLength === openerLength) {
  28. // Found matching closer length.
  29. if (!silent) {
  30. token = state.push('code_inline', 'code', 0);
  31. token.markup = marker;
  32. token.content = state.src.slice(pos, matchStart)
  33. .replace(/\n/g, ' ')
  34. .replace(/^ (.+) $/, '$1');
  35. }
  36. state.pos = matchEnd;
  37. return true;
  38. }
  39. // Some different length found, put it in cache as upper limit of where closer can be found
  40. state.backticks[closerLength] = matchStart;
  41. }
  42. // Scanned through the end, didn't find anything
  43. state.backticksScanned = true;
  44. if (!silent) state.pending += marker;
  45. state.pos += openerLength;
  46. return true;
  47. };