fence.mjs 2.4 KB

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