* Applies a transformation function to a text segment while skipping inline code spans * (backtick-delimited sequences). The transformation is applied to each run of * non-code text; inline code spans are preserved verbatim. * * @param {string} text - The text to process (should not contain fen
(text, fn)
| 469 | * @returns {string} The processed text |
| 470 | */ |
| 471 | function applyFnOutsideInlineCode(text, fn) { |
| 472 | if (!text) return fn(text || ""); |
| 473 | |
| 474 | const parts = []; |
| 475 | let i = 0; |
| 476 | let textStart = 0; |
| 477 | |
| 478 | while (i < text.length) { |
| 479 | if (text[i] !== "`") { |
| 480 | i++; |
| 481 | continue; |
| 482 | } |
| 483 | |
| 484 | // Count consecutive backticks at the current position |
| 485 | const btStart = i; |
| 486 | let btCount = 0; |
| 487 | while (i < text.length && text[i] === "`") { |
| 488 | btCount++; |
| 489 | i++; |
| 490 | } |
| 491 | // i is now past the opening backtick sequence |
| 492 | |
| 493 | // Look for the matching closing sequence of exactly btCount backticks |
| 494 | let closeIdx = -1; |
| 495 | let j = i; |
| 496 | while (j < text.length) { |
| 497 | if (text[j] === "`") { |
| 498 | let closeCount = 0; |
| 499 | const jStart = j; |
| 500 | while (j < text.length && text[j] === "`") { |
| 501 | closeCount++; |
| 502 | j++; |
| 503 | } |
| 504 | if (closeCount === btCount) { |
| 505 | closeIdx = jStart; |
| 506 | break; |
| 507 | } |
| 508 | // Different length – keep scanning (j already advanced past these backticks) |
| 509 | } else { |
| 510 | j++; |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | if (closeIdx !== -1) { |
| 515 | // Valid inline code span found: apply fn to the text before it, then keep the code span |
| 516 | if (textStart < btStart) { |
| 517 | parts.push(fn(text.slice(textStart, btStart))); |
| 518 | } |
| 519 | parts.push(text.slice(btStart, closeIdx + btCount)); |
| 520 | textStart = closeIdx + btCount; |
| 521 | i = textStart; |
| 522 | } |
| 523 | // If no matching close was found, the backticks are treated as regular text (i already advanced) |
| 524 | } |
| 525 | |
| 526 | // Apply fn to any remaining non-code text |
| 527 | if (textStart < text.length) { |
| 528 | parts.push(fn(text.slice(textStart))); |
no test coverage detected