fence.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // fences (``` lang, ~~~ lang)
  2. 'use strict';
  3. module.exports = function fence(state, startLine, endLine, silent) {
  4. var marker, len, params, nextLine, mem, token, markup,
  5. haveEndMarker = false,
  6. pos = state.bMarks[startLine] + state.tShift[startLine],
  7. max = state.eMarks[startLine];
  8. // if it's indented more than 3 spaces, it should be a code block
  9. if (state.sCount[startLine] - state.blkIndent >= 4) { return false; }
  10. if (pos + 3 > max) { return false; }
  11. marker = state.src.charCodeAt(pos);
  12. if (marker !== 0x7E/* ~ */ && marker !== 0x60 /* ` */) {
  13. return false;
  14. }
  15. // scan marker length
  16. mem = pos;
  17. pos = state.skipChars(pos, marker);
  18. len = pos - mem;
  19. if (len < 3) { return false; }
  20. markup = state.src.slice(mem, pos);
  21. params = state.src.slice(pos, max);
  22. if (params.indexOf(String.fromCharCode(marker)) >= 0) { return false; }
  23. // Since start is found, we can report success here in validation mode
  24. if (silent) { return true; }
  25. // search end of block
  26. nextLine = startLine;
  27. for (;;) {
  28. nextLine++;
  29. if (nextLine >= endLine) {
  30. // unclosed block should be autoclosed by end of document.
  31. // also block seems to be autoclosed by end of parent
  32. break;
  33. }
  34. pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
  35. max = state.eMarks[nextLine];
  36. if (pos < max && state.sCount[nextLine] < state.blkIndent) {
  37. // non-empty line with negative indent should stop the list:
  38. // - ```
  39. // test
  40. break;
  41. }
  42. if (state.src.charCodeAt(pos) !== marker) { continue; }
  43. if (state.sCount[nextLine] - state.blkIndent >= 4) {
  44. // closing fence should be indented less than 4 spaces
  45. continue;
  46. }
  47. pos = state.skipChars(pos, marker);
  48. // closing code fence must be at least as long as the opening one
  49. if (pos - mem < len) { continue; }
  50. // make sure tail has spaces only
  51. pos = state.skipSpaces(pos);
  52. if (pos < max) { continue; }
  53. haveEndMarker = true;
  54. // found!
  55. break;
  56. }
  57. // If a fence has heading spaces, they should be removed from its inner block
  58. len = state.sCount[startLine];
  59. state.line = nextLine + (haveEndMarker ? 1 : 0);
  60. token = state.push('fence', 'code', 0);
  61. token.info = params;
  62. token.content = state.getLines(startLine + 1, nextLine, len, true);
  63. token.markup = markup;
  64. token.map = [ startLine, state.line ];
  65. return true;
  66. };