fence.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 (marker === 0x60 /* ` */) {
  23. if (params.indexOf(String.fromCharCode(marker)) >= 0) {
  24. return false;
  25. }
  26. }
  27. // Since start is found, we can report success here in validation mode
  28. if (silent) { return true; }
  29. // search end of block
  30. nextLine = startLine;
  31. for (;;) {
  32. nextLine++;
  33. if (nextLine >= endLine) {
  34. // unclosed block should be autoclosed by end of document.
  35. // also block seems to be autoclosed by end of parent
  36. break;
  37. }
  38. pos = mem = state.bMarks[nextLine] + state.tShift[nextLine];
  39. max = state.eMarks[nextLine];
  40. if (pos < max && state.sCount[nextLine] < state.blkIndent) {
  41. // non-empty line with negative indent should stop the list:
  42. // - ```
  43. // test
  44. break;
  45. }
  46. if (state.src.charCodeAt(pos) !== marker) { continue; }
  47. if (state.sCount[nextLine] - state.blkIndent >= 4) {
  48. // closing fence should be indented less than 4 spaces
  49. continue;
  50. }
  51. pos = state.skipChars(pos, marker);
  52. // closing code fence must be at least as long as the opening one
  53. if (pos - mem < len) { continue; }
  54. // make sure tail has spaces only
  55. pos = state.skipSpaces(pos);
  56. if (pos < max) { continue; }
  57. haveEndMarker = true;
  58. // found!
  59. break;
  60. }
  61. // If a fence has heading spaces, they should be removed from its inner block
  62. len = state.sCount[startLine];
  63. state.line = nextLine + (haveEndMarker ? 1 : 0);
  64. token = state.push('fence', 'code', 0);
  65. token.info = params;
  66. token.content = state.getLines(startLine + 1, nextLine, len, true);
  67. token.markup = markup;
  68. token.map = [ startLine, state.line ];
  69. return true;
  70. };