MCPcopy Create free account
hub / github.com/anus-dev/ANUS / replaceRangeInternal

Function replaceRangeInternal

packages/cli/src/ui/components/shared/text-buffer.ts:425–496  ·  view source on GitHub ↗
(
  state: TextBufferState,
  startRow: number,
  startCol: number,
  endRow: number,
  endCol: number,
  text: string,
)

Source from the content-addressed store, hash-verified

423};
424
425export const replaceRangeInternal = (
426 state: TextBufferState,
427 startRow: number,
428 startCol: number,
429 endRow: number,
430 endCol: number,
431 text: string,
432): TextBufferState => {
433 const currentLine = (row: number) => state.lines[row] || '';
434 const currentLineLen = (row: number) => cpLen(currentLine(row));
435 const clamp = (value: number, min: number, max: number) =>
436 Math.min(Math.max(value, min), max);
437
438 if (
439 startRow > endRow ||
440 (startRow === endRow && startCol > endCol) ||
441 startRow < 0 ||
442 startCol < 0 ||
443 endRow >= state.lines.length ||
444 (endRow < state.lines.length && endCol > currentLineLen(endRow))
445 ) {
446 return state; // Invalid range
447 }
448
449 const newLines = [...state.lines];
450
451 const sCol = clamp(startCol, 0, currentLineLen(startRow));
452 const eCol = clamp(endCol, 0, currentLineLen(endRow));
453
454 const prefix = cpSlice(currentLine(startRow), 0, sCol);
455 const suffix = cpSlice(currentLine(endRow), eCol);
456
457 const normalisedReplacement = text
458 .replace(/\r\n/g, '\n')
459 .replace(/\r/g, '\n');
460 const replacementParts = normalisedReplacement.split('\n');
461
462 // The combined first line of the new text
463 const firstLine = prefix + replacementParts[0];
464
465 if (replacementParts.length === 1) {
466 // No newlines in replacement: combine prefix, replacement, and suffix on one line.
467 newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
468 } else {
469 // Newlines in replacement: create new lines.
470 const lastLine = replacementParts[replacementParts.length - 1] + suffix;
471 const middleLines = replacementParts.slice(1, -1);
472 newLines.splice(
473 startRow,
474 endRow - startRow + 1,
475 firstLine,
476 ...middleLines,
477 lastLine,
478 );
479 }
480
481 const finalCursorRow = startRow + replacementParts.length - 1;
482 const finalCursorCol =

Callers 2

textBufferReducerFunction · 0.85
handleVimActionFunction · 0.85

Calls 5

currentLineLenFunction · 0.85
clampFunction · 0.85
cpSliceFunction · 0.85
currentLineFunction · 0.85
cpLenFunction · 0.85

Tested by

no test coverage detected