* Returns the character ranges [start, end) of fenced code blocks in markdown content. * Fenced code blocks are delimited by lines starting with 3+ backticks or 3+ tildes. * The returned ranges span from the first character of the opening fence line through * the last character of the closing fen
(s)
| 410 | * @returns {Array<[number, number]>} Array of [start, end) character positions |
| 411 | */ |
| 412 | function getFencedCodeRanges(s) { |
| 413 | /** @type {Array<[number, number]>} */ |
| 414 | const ranges = []; |
| 415 | const lines = s.split("\n"); |
| 416 | let pos = 0; |
| 417 | let inBlock = false; |
| 418 | let blockStart = -1; |
| 419 | let fenceChar = ""; |
| 420 | let fenceLen = 0; |
| 421 | |
| 422 | for (let i = 0; i < lines.length; i++) { |
| 423 | const line = lines[i]; |
| 424 | const trimmed = line.trim(); |
| 425 | // Character position of the end of this line's content (not including the newline separator) |
| 426 | const lineContentEnd = pos + line.length; |
| 427 | // Character position after the newline separator (or same as lineContentEnd for the last line) |
| 428 | const lineEnd = i < lines.length - 1 ? lineContentEnd + 1 : lineContentEnd; |
| 429 | |
| 430 | if (!inBlock) { |
| 431 | const m = trimmed.match(/^(`{3,}|~{3,})/); |
| 432 | if (m) { |
| 433 | inBlock = true; |
| 434 | blockStart = pos; |
| 435 | fenceChar = m[1][0]; |
| 436 | fenceLen = m[1].length; |
| 437 | } |
| 438 | } else { |
| 439 | // A closing fence: same character, at least as long, only whitespace after |
| 440 | const fc = fenceChar === "`" ? "\\`" : "~"; |
| 441 | const closingRegex = new RegExp(`^[${fc}]{${fenceLen},}\\s*$`); |
| 442 | if (closingRegex.test(trimmed)) { |
| 443 | ranges.push([blockStart, lineEnd]); |
| 444 | inBlock = false; |
| 445 | blockStart = -1; |
| 446 | fenceChar = ""; |
| 447 | fenceLen = 0; |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | pos = lineEnd; |
| 452 | } |
| 453 | |
| 454 | // Unclosed fence – treat the rest as code (safer fallback) |
| 455 | if (inBlock && blockStart !== -1) { |
| 456 | ranges.push([blockStart, s.length]); |
| 457 | } |
| 458 | |
| 459 | return ranges; |
| 460 | } |
| 461 | |
| 462 | /** |
| 463 | * Applies a transformation function to a text segment while skipping inline code spans |
no outgoing calls
no test coverage detected