"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var text_buffer_exports = {};
__export(text_buffer_exports, {
  findNextWordAcrossLines: () => findNextWordAcrossLines,
  findNextWordStartInLine: () => findNextWordStartInLine,
  findPrevWordAcrossLines: () => findPrevWordAcrossLines,
  findPrevWordStartInLine: () => findPrevWordStartInLine,
  findWordEndInLine: () => findWordEndInLine,
  getLineRangeOffsets: () => getLineRangeOffsets,
  getPositionFromOffsets: () => getPositionFromOffsets,
  logicalPosToOffset: () => logicalPosToOffset,
  offsetToLogicalPos: () => offsetToLogicalPos,
  pushUndo: () => pushUndo,
  replaceRangeInternal: () => replaceRangeInternal,
  textBufferReducer: () => textBufferReducer,
  useTextBuffer: () => useTextBuffer
});
module.exports = __toCommonJS(text_buffer_exports);
var import_react = require("react");
var import_textUtils = require("../../utils/textUtils.js");
const findNextWordStartInLine = (line, col) => {
  const chars = (0, import_textUtils.toCodePoints)(line);
  let i = col;
  if (i >= chars.length) return null;
  const currentChar = chars[i];
  if ((0, import_textUtils.isWordCharStrict)(currentChar)) {
    while (i < chars.length && (0, import_textUtils.isWordCharWithCombining)(chars[i])) {
      if (i + 1 < chars.length && (0, import_textUtils.isWordCharStrict)(chars[i + 1]) && (0, import_textUtils.isDifferentScript)(chars[i], chars[i + 1])) {
        i++;
        break;
      }
      i++;
    }
  } else if (!(0, import_textUtils.isWhitespace)(currentChar)) {
    while (i < chars.length && !(0, import_textUtils.isWordCharStrict)(chars[i]) && !(0, import_textUtils.isWhitespace)(chars[i])) {
      i++;
    }
  }
  while (i < chars.length && (0, import_textUtils.isWhitespace)(chars[i])) {
    i++;
  }
  return i < chars.length ? i : null;
};
const findPrevWordStartInLine = (line, col) => {
  const chars = (0, import_textUtils.toCodePoints)(line);
  let i = col;
  if (i <= 0) return null;
  i--;
  while (i >= 0 && (0, import_textUtils.isWhitespace)(chars[i])) {
    i--;
  }
  if (i < 0) return null;
  if ((0, import_textUtils.isWordCharStrict)(chars[i])) {
    while (i >= 0 && (0, import_textUtils.isWordCharStrict)(chars[i])) {
      if (i - 1 >= 0 && (0, import_textUtils.isWordCharStrict)(chars[i - 1]) && (0, import_textUtils.isDifferentScript)(chars[i], chars[i - 1])) {
        return i;
      }
      i--;
    }
    return i + 1;
  } else {
    while (i >= 0 && !(0, import_textUtils.isWordCharStrict)(chars[i]) && !(0, import_textUtils.isWhitespace)(chars[i])) {
      i--;
    }
    return i + 1;
  }
};
const findWordEndInLine = (line, col) => {
  const chars = (0, import_textUtils.toCodePoints)(line);
  let i = col;
  const atEndOfWordChar = i < chars.length && (0, import_textUtils.isWordCharWithCombining)(chars[i]) && (i + 1 >= chars.length || !(0, import_textUtils.isWordCharWithCombining)(chars[i + 1]) || (0, import_textUtils.isWordCharStrict)(chars[i]) && i + 1 < chars.length && (0, import_textUtils.isWordCharStrict)(chars[i + 1]) && (0, import_textUtils.isDifferentScript)(chars[i], chars[i + 1]));
  const atEndOfPunctuation = i < chars.length && !(0, import_textUtils.isWordCharWithCombining)(chars[i]) && !(0, import_textUtils.isWhitespace)(chars[i]) && (i + 1 >= chars.length || (0, import_textUtils.isWhitespace)(chars[i + 1]) || (0, import_textUtils.isWordCharWithCombining)(chars[i + 1]));
  if (atEndOfWordChar || atEndOfPunctuation) {
    i++;
    while (i < chars.length && (0, import_textUtils.isWhitespace)(chars[i])) {
      i++;
    }
  }
  if (i < chars.length && !(0, import_textUtils.isWordCharWithCombining)(chars[i])) {
    while (i < chars.length && (0, import_textUtils.isWhitespace)(chars[i])) {
      i++;
    }
  }
  let foundWord = false;
  let lastBaseCharPos = -1;
  if (i < chars.length && (0, import_textUtils.isWordCharWithCombining)(chars[i])) {
    while (i < chars.length && (0, import_textUtils.isWordCharWithCombining)(chars[i])) {
      foundWord = true;
      if ((0, import_textUtils.isWordCharStrict)(chars[i])) {
        lastBaseCharPos = i;
      }
      if (i + 1 < chars.length && (0, import_textUtils.isWordCharStrict)(chars[i + 1]) && (0, import_textUtils.isDifferentScript)(chars[i], chars[i + 1])) {
        i++;
        if ((0, import_textUtils.isWordCharStrict)(chars[i - 1])) {
          lastBaseCharPos = i - 1;
        }
        break;
      }
      i++;
    }
  } else if (i < chars.length && !(0, import_textUtils.isWhitespace)(chars[i])) {
    while (i < chars.length && !(0, import_textUtils.isWordCharStrict)(chars[i]) && !(0, import_textUtils.isWhitespace)(chars[i])) {
      foundWord = true;
      lastBaseCharPos = i;
      i++;
    }
  }
  if (foundWord && lastBaseCharPos >= col) {
    return lastBaseCharPos;
  }
  return null;
};
const segmenter = new Intl.Segmenter(void 0, { granularity: "word" });
function findPrevWordBoundary(line, cursorCol) {
  const codePoints = (0, import_textUtils.toCodePoints)(line);
  const prefix = codePoints.slice(0, cursorCol).join("");
  const cursorIdx = prefix.length;
  let targetIdx = 0;
  for (const seg of segmenter.segment(line)) {
    if (seg.index >= cursorIdx) break;
    if (seg.isWordLike) {
      targetIdx = seg.index;
    }
  }
  return (0, import_textUtils.toCodePoints)(line.slice(0, targetIdx)).length;
}
function findNextWordBoundary(line, cursorCol) {
  const codePoints = (0, import_textUtils.toCodePoints)(line);
  const prefix = codePoints.slice(0, cursorCol).join("");
  const cursorIdx = prefix.length;
  let targetIdx = line.length;
  for (const seg of segmenter.segment(line)) {
    const segEnd = seg.index + seg.segment.length;
    if (segEnd > cursorIdx) {
      if (seg.isWordLike) {
        targetIdx = segEnd;
        break;
      }
    }
  }
  return (0, import_textUtils.toCodePoints)(line.slice(0, targetIdx)).length;
}
const findNextWordAcrossLines = (lines, cursorRow, cursorCol, searchForWordStart) => {
  const currentLine = lines[cursorRow] || "";
  const colInCurrentLine = searchForWordStart ? findNextWordStartInLine(currentLine, cursorCol) : findWordEndInLine(currentLine, cursorCol);
  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }
  for (let row = cursorRow + 1; row < lines.length; row++) {
    const line = lines[row] || "";
    const chars = (0, import_textUtils.toCodePoints)(line);
    if (chars.length === 0) {
      let hasWordsInLaterLines = false;
      for (let laterRow = row + 1; laterRow < lines.length; laterRow++) {
        const laterLine = lines[laterRow] || "";
        const laterChars = (0, import_textUtils.toCodePoints)(laterLine);
        let firstNonWhitespace2 = 0;
        while (firstNonWhitespace2 < laterChars.length && (0, import_textUtils.isWhitespace)(laterChars[firstNonWhitespace2])) {
          firstNonWhitespace2++;
        }
        if (firstNonWhitespace2 < laterChars.length) {
          hasWordsInLaterLines = true;
          break;
        }
      }
      if (!hasWordsInLaterLines) {
        return { row, col: 0 };
      }
      continue;
    }
    let firstNonWhitespace = 0;
    while (firstNonWhitespace < chars.length && (0, import_textUtils.isWhitespace)(chars[firstNonWhitespace])) {
      firstNonWhitespace++;
    }
    if (firstNonWhitespace < chars.length) {
      if (searchForWordStart) {
        return { row, col: firstNonWhitespace };
      } else {
        const endCol = findWordEndInLine(line, firstNonWhitespace);
        if (endCol !== null) {
          return { row, col: endCol };
        }
      }
    }
  }
  return null;
};
const findPrevWordAcrossLines = (lines, cursorRow, cursorCol) => {
  const currentLine = lines[cursorRow] || "";
  const colInCurrentLine = findPrevWordStartInLine(currentLine, cursorCol);
  if (colInCurrentLine !== null) {
    return { row: cursorRow, col: colInCurrentLine };
  }
  for (let row = cursorRow - 1; row >= 0; row--) {
    const line = lines[row] || "";
    const chars = (0, import_textUtils.toCodePoints)(line);
    if (chars.length === 0) continue;
    let lastWordStart = chars.length;
    while (lastWordStart > 0 && (0, import_textUtils.isWhitespace)(chars[lastWordStart - 1])) {
      lastWordStart--;
    }
    if (lastWordStart > 0) {
      const wordStart = findPrevWordStartInLine(line, lastWordStart);
      if (wordStart !== null) {
        return { row, col: wordStart };
      }
    }
  }
  return null;
};
const getPositionFromOffsets = (startOffset, endOffset, lines) => {
  let offset = 0;
  let startRow = 0;
  let startCol = 0;
  let endRow = 0;
  let endCol = 0;
  for (let i = 0; i < lines.length; i++) {
    const lineLength = lines[i].length + 1;
    if (offset + lineLength > startOffset) {
      startRow = i;
      startCol = startOffset - offset;
      break;
    }
    offset += lineLength;
  }
  offset = 0;
  for (let i = 0; i < lines.length; i++) {
    const lineLength = lines[i].length + (i < lines.length - 1 ? 1 : 0);
    if (offset + lineLength >= endOffset) {
      endRow = i;
      endCol = endOffset - offset;
      break;
    }
    offset += lineLength;
  }
  return { startRow, startCol, endRow, endCol };
};
const getLineRangeOffsets = (startRow, lineCount, lines) => {
  let startOffset = 0;
  for (let i = 0; i < startRow; i++) {
    startOffset += lines[i].length + 1;
  }
  let endOffset = startOffset;
  for (let i = 0; i < lineCount; i++) {
    const lineIndex = startRow + i;
    if (lineIndex < lines.length) {
      endOffset += lines[lineIndex].length;
      if (lineIndex < lines.length - 1) {
        endOffset += 1;
      }
    }
  }
  return { startOffset, endOffset };
};
const replaceRangeInternal = (state, startRow, startCol, endRow, endCol, text) => {
  const currentLine = (row) => state.lines[row] || "";
  const currentLineLen = (row) => (0, import_textUtils.cpLen)(currentLine(row));
  const clamp2 = (value, min, max) => Math.min(Math.max(value, min), max);
  if (startRow > endRow || startRow === endRow && startCol > endCol || startRow < 0 || startCol < 0 || endRow >= state.lines.length || endRow < state.lines.length && endCol > currentLineLen(endRow)) {
    return state;
  }
  const newLines = [...state.lines];
  const sCol = clamp2(startCol, 0, currentLineLen(startRow));
  const eCol = clamp2(endCol, 0, currentLineLen(endRow));
  const prefix = (0, import_textUtils.cpSlice)(currentLine(startRow), 0, sCol);
  const suffix = (0, import_textUtils.cpSlice)(currentLine(endRow), eCol);
  const normalisedReplacement = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
  const replacementParts = normalisedReplacement.split("\n");
  const firstLine = prefix + replacementParts[0];
  if (replacementParts.length === 1) {
    newLines.splice(startRow, endRow - startRow + 1, firstLine + suffix);
  } else {
    const lastLine = replacementParts[replacementParts.length - 1] + suffix;
    const middleLines = replacementParts.slice(1, -1);
    newLines.splice(startRow, endRow - startRow + 1, firstLine, ...middleLines, lastLine);
  }
  const finalCursorRow = startRow + replacementParts.length - 1;
  const finalCursorCol = (replacementParts.length > 1 ? 0 : sCol) + (0, import_textUtils.cpLen)(replacementParts[replacementParts.length - 1]);
  return {
    ...state,
    lines: newLines,
    cursorRow: Math.min(Math.max(finalCursorRow, 0), newLines.length - 1),
    cursorCol: Math.max(0, Math.min(finalCursorCol, (0, import_textUtils.cpLen)(newLines[finalCursorRow] || ""))),
    preferredCol: null
  };
};
function clamp(v, min, max) {
  return v < min ? min : v > max ? max : v;
}
function calculateInitialCursorPosition(initialLines, offset) {
  let remainingChars = offset;
  let row = 0;
  while (row < initialLines.length) {
    const lineLength = (0, import_textUtils.cpLen)(initialLines[row]);
    const totalCharsInLineAndNewline = lineLength + (row < initialLines.length - 1 ? 1 : 0);
    if (remainingChars <= lineLength) {
      return [row, remainingChars];
    }
    remainingChars -= totalCharsInLineAndNewline;
    row++;
  }
  if (initialLines.length > 0) {
    const lastRow = initialLines.length - 1;
    return [lastRow, (0, import_textUtils.cpLen)(initialLines[lastRow])];
  }
  return [0, 0];
}
function offsetToLogicalPos(text, offset) {
  let row = 0;
  let col = 0;
  let currentOffset = 0;
  if (offset === 0) return [0, 0];
  const lines = text.split("\n");
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const lineLength = (0, import_textUtils.cpLen)(line);
    const lineLengthWithNewline = lineLength + (i < lines.length - 1 ? 1 : 0);
    if (offset <= currentOffset + lineLength) {
      row = i;
      col = offset - currentOffset;
      return [row, col];
    } else if (offset <= currentOffset + lineLengthWithNewline) {
      row = i;
      col = lineLength;
      if (offset === currentOffset + lineLengthWithNewline && i < lines.length - 1) {
        return [i + 1, 0];
      }
      return [row, col];
    }
    currentOffset += lineLengthWithNewline;
  }
  if (lines.length > 0) {
    row = lines.length - 1;
    col = (0, import_textUtils.cpLen)(lines[row]);
  } else {
    row = 0;
    col = 0;
  }
  return [row, col];
}
function logicalPosToOffset(lines, row, col) {
  let offset = 0;
  const actualRow = Math.min(row, lines.length - 1);
  for (let i = 0; i < actualRow; i++) {
    offset += (0, import_textUtils.cpLen)(lines[i]) + 1;
  }
  if (actualRow >= 0 && actualRow < lines.length) {
    offset += Math.min(col, (0, import_textUtils.cpLen)(lines[actualRow]));
  }
  return offset;
}
function calculateLayout(logicalLines, viewportWidth) {
  const visualLines = [];
  const logicalToVisualMap = [];
  const visualToLogicalMap = [];
  logicalLines.forEach((logLine, logIndex) => {
    logicalToVisualMap[logIndex] = [];
    if (logLine.length === 0) {
      logicalToVisualMap[logIndex].push([visualLines.length, 0]);
      visualToLogicalMap.push([logIndex, 0]);
      visualLines.push("");
    } else {
      let currentPosInLogLine = 0;
      const codePointsInLogLine = (0, import_textUtils.toCodePoints)(logLine);
      while (currentPosInLogLine < codePointsInLogLine.length) {
        let currentChunk = "";
        let currentChunkVisualWidth = 0;
        let numCodePointsInChunk = 0;
        let lastWordBreakPoint = -1;
        let numCodePointsAtLastWordBreak = 0;
        for (let i = currentPosInLogLine; i < codePointsInLogLine.length; i++) {
          const char = codePointsInLogLine[i];
          const charVisualWidth = (0, import_textUtils.getCachedStringWidth)(char);
          if (currentChunkVisualWidth + charVisualWidth > viewportWidth) {
            if (lastWordBreakPoint !== -1 && numCodePointsAtLastWordBreak > 0 && currentPosInLogLine + numCodePointsAtLastWordBreak < i) {
              currentChunk = codePointsInLogLine.slice(
                currentPosInLogLine,
                currentPosInLogLine + numCodePointsAtLastWordBreak
              ).join("");
              numCodePointsInChunk = numCodePointsAtLastWordBreak;
            } else {
              if (numCodePointsInChunk === 0 && charVisualWidth > viewportWidth) {
                currentChunk = char;
                numCodePointsInChunk = 1;
              } else if (numCodePointsInChunk === 0 && charVisualWidth <= viewportWidth) {
              }
            }
            break;
          }
          currentChunk += char;
          currentChunkVisualWidth += charVisualWidth;
          numCodePointsInChunk++;
          if (char === " ") {
            lastWordBreakPoint = i;
            numCodePointsAtLastWordBreak = numCodePointsInChunk - 1;
          }
        }
        if (numCodePointsInChunk === 0 && currentPosInLogLine < codePointsInLogLine.length) {
          const firstChar = codePointsInLogLine[currentPosInLogLine];
          currentChunk = firstChar;
          numCodePointsInChunk = 1;
        }
        if (numCodePointsInChunk === 0 && currentPosInLogLine < codePointsInLogLine.length) {
          currentChunk = codePointsInLogLine[currentPosInLogLine];
          numCodePointsInChunk = 1;
        }
        logicalToVisualMap[logIndex].push([visualLines.length, currentPosInLogLine]);
        visualToLogicalMap.push([logIndex, currentPosInLogLine]);
        visualLines.push(currentChunk);
        const logicalStartOfThisChunk = currentPosInLogLine;
        currentPosInLogLine += numCodePointsInChunk;
        if (logicalStartOfThisChunk + numCodePointsInChunk < codePointsInLogLine.length && currentPosInLogLine < codePointsInLogLine.length && // Redundant if previous is true, but safe
        codePointsInLogLine[currentPosInLogLine] === " ") {
          currentPosInLogLine++;
        }
      }
    }
  });
  if (logicalLines.length === 0 || logicalLines.length === 1 && logicalLines[0] === "") {
    if (visualLines.length === 0) {
      visualLines.push("");
      if (!logicalToVisualMap[0]) logicalToVisualMap[0] = [];
      logicalToVisualMap[0].push([0, 0]);
      visualToLogicalMap.push([0, 0]);
    }
  }
  return {
    visualLines,
    logicalToVisualMap,
    visualToLogicalMap
  };
}
function calculateVisualCursorFromLayout(layout, logicalCursor) {
  const { logicalToVisualMap, visualLines } = layout;
  const [logicalRow, logicalCol] = logicalCursor;
  const segmentsForLogicalLine = logicalToVisualMap[logicalRow];
  if (!segmentsForLogicalLine || segmentsForLogicalLine.length === 0) {
    return [0, 0];
  }
  let targetSegmentIndex = segmentsForLogicalLine.findIndex(([, startColInLogical2], index) => {
    const nextStartColInLogical = index + 1 < segmentsForLogicalLine.length ? segmentsForLogicalLine[index + 1][1] : Infinity;
    return logicalCol >= startColInLogical2 && logicalCol < nextStartColInLogical;
  });
  if (targetSegmentIndex === -1) {
    if (logicalCol === 0) {
      targetSegmentIndex = 0;
    } else {
      targetSegmentIndex = segmentsForLogicalLine.length - 1;
    }
  }
  const [visualRow, startColInLogical] = segmentsForLogicalLine[targetSegmentIndex];
  const visualCol = logicalCol - startColInLogical;
  const clampedVisualCol = Math.min(visualCol, (0, import_textUtils.cpLen)(visualLines[visualRow] ?? ""));
  return [visualRow, clampedVisualCol];
}
const historyLimit = 100;
const pushUndo = (currentState) => {
  const snapshot = {
    lines: [...currentState.lines],
    cursorRow: currentState.cursorRow,
    cursorCol: currentState.cursorCol
  };
  const newStack = [...currentState.undoStack, snapshot];
  if (newStack.length > historyLimit) {
    newStack.shift();
  }
  return { ...currentState, undoStack: newStack, redoStack: [] };
};
function textBufferReducerLogic(state, action, options = {}) {
  const pushUndoLocal = pushUndo;
  const currentLine = (r) => state.lines[r] ?? "";
  const currentLineLen = (r) => (0, import_textUtils.cpLen)(currentLine(r));
  switch (action.type) {
    case "set_text": {
      let nextState = state;
      if (action.pushToUndo !== false) {
        nextState = pushUndoLocal(state);
      }
      const newContentLines = action.payload.replace(/\r\n?/g, "\n").split("\n");
      const lines = newContentLines.length === 0 ? [""] : newContentLines;
      const lastNewLineIndex = lines.length - 1;
      return {
        ...nextState,
        lines,
        cursorRow: lastNewLineIndex,
        cursorCol: (0, import_textUtils.cpLen)(lines[lastNewLineIndex] ?? ""),
        preferredCol: null
      };
    }
    case "insert": {
      let payload = action.payload;
      if (options.singleLine) {
        payload = payload.replace(/[\r\n]/g, "");
      }
      if (options.inputFilter) {
        payload = options.inputFilter(payload);
      }
      if (payload.length === 0) {
        return state;
      }
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;
      const currentLine2 = (r) => newLines[r] ?? "";
      const str = (0, import_textUtils.stripUnsafeCharacters)(payload.replace(/\r\n/g, "\n").replace(/\r/g, "\n"));
      const parts = str.split("\n");
      const lineContent = currentLine2(newCursorRow);
      const before = (0, import_textUtils.cpSlice)(lineContent, 0, newCursorCol);
      const after = (0, import_textUtils.cpSlice)(lineContent, newCursorCol);
      if (parts.length > 1) {
        newLines[newCursorRow] = before + parts[0];
        const remainingParts = parts.slice(1);
        const lastPartOriginal = remainingParts.pop() ?? "";
        newLines.splice(newCursorRow + 1, 0, ...remainingParts);
        newLines.splice(newCursorRow + parts.length - 1, 0, lastPartOriginal + after);
        newCursorRow = newCursorRow + parts.length - 1;
        newCursorCol = (0, import_textUtils.cpLen)(lastPartOriginal);
      } else {
        newLines[newCursorRow] = before + parts[0] + after;
        newCursorCol = (0, import_textUtils.cpLen)(before) + (0, import_textUtils.cpLen)(parts[0]);
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "backspace": {
      if (state.cursorCol === 0 && state.cursorRow === 0) return state;
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = nextState.cursorRow;
      let newCursorCol = nextState.cursorCol;
      const currentLine2 = (r) => newLines[r] ?? "";
      if (newCursorCol > 0) {
        const lineContent = currentLine2(newCursorRow);
        newLines[newCursorRow] = (0, import_textUtils.cpSlice)(lineContent, 0, newCursorCol - 1) + (0, import_textUtils.cpSlice)(lineContent, newCursorCol);
        newCursorCol--;
      } else if (newCursorRow > 0) {
        const prevLineContent = currentLine2(newCursorRow - 1);
        const currentLineContentVal = currentLine2(newCursorRow);
        const newCol = (0, import_textUtils.cpLen)(prevLineContent);
        newLines[newCursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(newCursorRow, 1);
        newCursorRow--;
        newCursorCol = newCol;
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "set_viewport": {
      const { width, height } = action.payload;
      if (width === state.viewportWidth && height === state.viewportHeight) {
        return state;
      }
      return {
        ...state,
        viewportWidth: width,
        viewportHeight: height
      };
    }
    case "move": {
      const { dir } = action.payload;
      const { cursorRow, cursorCol, lines, visualLayout, preferredCol } = state;
      if (dir === "left" || dir === "right" || dir === "up" || dir === "down" || dir === "home" || dir === "end") {
        const visualCursor = calculateVisualCursorFromLayout(visualLayout, [
          cursorRow,
          cursorCol
        ]);
        const { visualLines, visualToLogicalMap } = visualLayout;
        let newVisualRow = visualCursor[0];
        let newVisualCol = visualCursor[1];
        let newPreferredCol = preferredCol;
        const currentVisLineLen = (0, import_textUtils.cpLen)(visualLines[newVisualRow] ?? "");
        switch (dir) {
          case "left":
            newPreferredCol = null;
            if (newVisualCol > 0) {
              newVisualCol--;
            } else if (newVisualRow > 0) {
              newVisualRow--;
              newVisualCol = (0, import_textUtils.cpLen)(visualLines[newVisualRow] ?? "");
            }
            break;
          case "right":
            newPreferredCol = null;
            if (newVisualCol < currentVisLineLen) {
              newVisualCol++;
            } else if (newVisualRow < visualLines.length - 1) {
              newVisualRow++;
              newVisualCol = 0;
            }
            break;
          case "up":
            if (newVisualRow > 0) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow--;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                (0, import_textUtils.cpLen)(visualLines[newVisualRow] ?? "")
              );
            }
            break;
          case "down":
            if (newVisualRow < visualLines.length - 1) {
              if (newPreferredCol === null) newPreferredCol = newVisualCol;
              newVisualRow++;
              newVisualCol = clamp(
                newPreferredCol,
                0,
                (0, import_textUtils.cpLen)(visualLines[newVisualRow] ?? "")
              );
            }
            break;
          case "home":
            newPreferredCol = null;
            newVisualCol = 0;
            break;
          case "end":
            newPreferredCol = null;
            newVisualCol = currentVisLineLen;
            break;
          default:
            return state;
        }
        if (visualToLogicalMap[newVisualRow]) {
          const [logRow, logStartCol] = visualToLogicalMap[newVisualRow];
          return {
            ...state,
            cursorRow: logRow,
            cursorCol: clamp(logStartCol + newVisualCol, 0, (0, import_textUtils.cpLen)(lines[logRow] ?? "")),
            preferredCol: newPreferredCol
          };
        }
        return state;
      }
      switch (dir) {
        case "wordLeft": {
          if (cursorCol === 0 && cursorRow === 0) return state;
          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;
          if (cursorCol === 0) {
            newCursorRow--;
            newCursorCol = (0, import_textUtils.cpLen)(lines[newCursorRow] ?? "");
          } else {
            const lineContent = lines[cursorRow] ?? "";
            newCursorCol = findPrevWordBoundary(lineContent, cursorCol);
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null
          };
        }
        case "wordRight": {
          const lineContent = lines[cursorRow] ?? "";
          if (cursorRow === lines.length - 1 && cursorCol === (0, import_textUtils.cpLen)(lineContent)) {
            return state;
          }
          let newCursorRow = cursorRow;
          let newCursorCol = cursorCol;
          const lineLen = (0, import_textUtils.cpLen)(lineContent);
          if (cursorCol >= lineLen) {
            newCursorRow++;
            newCursorCol = 0;
          } else {
            newCursorCol = findNextWordBoundary(lineContent, cursorCol);
          }
          return {
            ...state,
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: null
          };
        }
        default:
          return state;
      }
    }
    case "set_cursor": {
      return {
        ...state,
        ...action.payload
      };
    }
    case "delete": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      if (cursorCol < currentLineLen(cursorRow)) {
        const nextState = pushUndoLocal(state);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = (0, import_textUtils.cpSlice)(lineContent, 0, cursorCol) + (0, import_textUtils.cpSlice)(lineContent, cursorCol + 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      } else if (cursorRow < lines.length - 1) {
        const nextState = pushUndoLocal(state);
        const nextLineContent = currentLine(cursorRow + 1);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      }
      return state;
    }
    case "delete_word_left": {
      const { cursorRow, cursorCol } = state;
      if (cursorCol === 0 && cursorRow === 0) return state;
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      let newCursorRow = cursorRow;
      let newCursorCol = cursorCol;
      if (newCursorCol > 0) {
        const lineContent = currentLine(newCursorRow);
        const prevWordStart = findPrevWordStartInLine(lineContent, newCursorCol);
        const start = prevWordStart === null ? 0 : prevWordStart;
        newLines[newCursorRow] = (0, import_textUtils.cpSlice)(lineContent, 0, start) + (0, import_textUtils.cpSlice)(lineContent, newCursorCol);
        newCursorCol = start;
      } else {
        const prevLineContent = currentLine(cursorRow - 1);
        const currentLineContentVal = currentLine(cursorRow);
        const newCol = (0, import_textUtils.cpLen)(prevLineContent);
        newLines[cursorRow - 1] = prevLineContent + currentLineContentVal;
        newLines.splice(cursorRow, 1);
        newCursorRow--;
        newCursorCol = newCol;
      }
      return {
        ...nextState,
        lines: newLines,
        cursorRow: newCursorRow,
        cursorCol: newCursorCol,
        preferredCol: null
      };
    }
    case "delete_word_right": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      const lineLen = (0, import_textUtils.cpLen)(lineContent);
      if (cursorCol >= lineLen && cursorRow === lines.length - 1) {
        return state;
      }
      const nextState = pushUndoLocal(state);
      const newLines = [...nextState.lines];
      if (cursorCol >= lineLen) {
        const nextLineContent = currentLine(cursorRow + 1);
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
      } else {
        const nextWordStart = findNextWordStartInLine(lineContent, cursorCol);
        const end = nextWordStart === null ? lineLen : nextWordStart;
        newLines[cursorRow] = (0, import_textUtils.cpSlice)(lineContent, 0, cursorCol) + (0, import_textUtils.cpSlice)(lineContent, end);
      }
      return {
        ...nextState,
        lines: newLines,
        preferredCol: null
      };
    }
    case "kill_line_right": {
      const { cursorRow, cursorCol, lines } = state;
      const lineContent = currentLine(cursorRow);
      if (cursorCol < currentLineLen(cursorRow)) {
        const nextState = pushUndoLocal(state);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = (0, import_textUtils.cpSlice)(lineContent, 0, cursorCol);
        return {
          ...nextState,
          lines: newLines
        };
      } else if (cursorRow < lines.length - 1) {
        const nextState = pushUndoLocal(state);
        const nextLineContent = currentLine(cursorRow + 1);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = lineContent + nextLineContent;
        newLines.splice(cursorRow + 1, 1);
        return {
          ...nextState,
          lines: newLines,
          preferredCol: null
        };
      }
      return state;
    }
    case "kill_line_left": {
      const { cursorRow, cursorCol } = state;
      if (cursorCol > 0) {
        const nextState = pushUndoLocal(state);
        const lineContent = currentLine(cursorRow);
        const newLines = [...nextState.lines];
        newLines[cursorRow] = (0, import_textUtils.cpSlice)(lineContent, cursorCol);
        return {
          ...nextState,
          lines: newLines,
          cursorCol: 0,
          preferredCol: null
        };
      }
      return state;
    }
    case "undo": {
      const stateToRestore = state.undoStack[state.undoStack.length - 1];
      if (!stateToRestore) return state;
      const currentSnapshot = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol
      };
      return {
        ...state,
        ...stateToRestore,
        undoStack: state.undoStack.slice(0, -1),
        redoStack: [...state.redoStack, currentSnapshot]
      };
    }
    case "redo": {
      const stateToRestore = state.redoStack[state.redoStack.length - 1];
      if (!stateToRestore) return state;
      const currentSnapshot = {
        lines: [...state.lines],
        cursorRow: state.cursorRow,
        cursorCol: state.cursorCol
      };
      return {
        ...state,
        ...stateToRestore,
        redoStack: state.redoStack.slice(0, -1),
        undoStack: [...state.undoStack, currentSnapshot]
      };
    }
    case "replace_range": {
      const { startRow, startCol, endRow, endCol, text } = action.payload;
      const nextState = pushUndoLocal(state);
      return replaceRangeInternal(nextState, startRow, startCol, endRow, endCol, text);
    }
    case "move_to_offset": {
      const { offset } = action.payload;
      const [newRow, newCol] = offsetToLogicalPos(state.lines.join("\n"), offset);
      return {
        ...state,
        cursorRow: newRow,
        cursorCol: newCol,
        preferredCol: null
      };
    }
    case "create_undo_snapshot": {
      return pushUndoLocal(state);
    }
    default:
      return state;
  }
}
function textBufferReducer(state, action, options = {}) {
  const newState = textBufferReducerLogic(state, action, options);
  if (newState.lines !== state.lines || newState.viewportWidth !== state.viewportWidth) {
    return {
      ...newState,
      visualLayout: calculateLayout(newState.lines, newState.viewportWidth)
    };
  }
  return newState;
}
function useTextBuffer({
  initialText = "",
  initialCursorOffset = 0,
  viewport,
  onChange,
  inputFilter,
  singleLine = false
}) {
  const initialState = (0, import_react.useMemo)(() => {
    const lines2 = initialText.split("\n");
    const [initialCursorRow, initialCursorCol] = calculateInitialCursorPosition(
      lines2.length === 0 ? [""] : lines2,
      initialCursorOffset
    );
    const visualLayout2 = calculateLayout(lines2.length === 0 ? [""] : lines2, viewport.width);
    return {
      lines: lines2.length === 0 ? [""] : lines2,
      cursorRow: initialCursorRow,
      cursorCol: initialCursorCol,
      preferredCol: null,
      undoStack: [],
      redoStack: [],
      viewportWidth: viewport.width,
      viewportHeight: viewport.height,
      visualLayout: visualLayout2
    };
  }, [initialText, initialCursorOffset, viewport.width, viewport.height]);
  const [state, dispatch] = (0, import_react.useReducer)(
    (s, a) => textBufferReducer(s, a, { inputFilter, singleLine }),
    initialState
  );
  const { lines, cursorRow, cursorCol, preferredCol, visualLayout } = state;
  const text = (0, import_react.useMemo)(() => lines.join("\n"), [lines]);
  const visualCursor = (0, import_react.useMemo)(
    () => calculateVisualCursorFromLayout(visualLayout, [cursorRow, cursorCol]),
    [visualLayout, cursorRow, cursorCol]
  );
  const { visualLines, visualToLogicalMap } = visualLayout;
  const [visualScrollRow, setVisualScrollRow] = (0, import_react.useState)(0);
  (0, import_react.useEffect)(() => {
    if (onChange) {
      onChange(text);
    }
  }, [text, onChange]);
  (0, import_react.useEffect)(() => {
    dispatch({
      type: "set_viewport",
      payload: { width: viewport.width, height: viewport.height }
    });
  }, [viewport.width, viewport.height]);
  (0, import_react.useEffect)(() => {
    const { height } = viewport;
    const totalVisualLines = visualLines.length;
    const maxScrollStart = Math.max(0, totalVisualLines - height);
    let newVisualScrollRow = visualScrollRow;
    if (visualCursor[0] < visualScrollRow) {
      newVisualScrollRow = visualCursor[0];
    } else if (visualCursor[0] >= visualScrollRow + height) {
      newVisualScrollRow = visualCursor[0] - height + 1;
    }
    newVisualScrollRow = clamp(newVisualScrollRow, 0, maxScrollStart);
    if (newVisualScrollRow !== visualScrollRow) {
      setVisualScrollRow(newVisualScrollRow);
    }
  }, [visualCursor, visualScrollRow, viewport, visualLines.length]);
  const insert = (0, import_react.useCallback)(
    (ch, { paste: _paste = false } = {}) => {
      if (!singleLine && /[\n\r]/.test(ch)) {
        dispatch({ type: "insert", payload: ch });
        return;
      }
      let currentText = "";
      for (const char of (0, import_textUtils.toCodePoints)(ch)) {
        if (char.codePointAt(0) === 127) {
          if (currentText.length > 0) {
            dispatch({ type: "insert", payload: currentText });
            currentText = "";
          }
          dispatch({ type: "backspace" });
        } else {
          currentText += char;
        }
      }
      if (currentText.length > 0) {
        dispatch({ type: "insert", payload: currentText });
      }
    },
    [singleLine]
  );
  const newline = (0, import_react.useCallback)(() => {
    if (singleLine) {
      return;
    }
    dispatch({ type: "insert", payload: "\n" });
  }, [singleLine]);
  const backspace = (0, import_react.useCallback)(() => {
    dispatch({ type: "backspace" });
  }, []);
  const del = (0, import_react.useCallback)(() => {
    dispatch({ type: "delete" });
  }, []);
  const move = (0, import_react.useCallback)(
    (dir) => {
      dispatch({ type: "move", payload: { dir } });
    },
    [dispatch]
  );
  const undo = (0, import_react.useCallback)(() => {
    dispatch({ type: "undo" });
  }, []);
  const redo = (0, import_react.useCallback)(() => {
    dispatch({ type: "redo" });
  }, []);
  const setText = (0, import_react.useCallback)((newText) => {
    dispatch({ type: "set_text", payload: newText });
  }, []);
  const deleteWordLeft = (0, import_react.useCallback)(() => {
    dispatch({ type: "delete_word_left" });
  }, []);
  const deleteWordRight = (0, import_react.useCallback)(() => {
    dispatch({ type: "delete_word_right" });
  }, []);
  const killLineRight = (0, import_react.useCallback)(() => {
    dispatch({ type: "kill_line_right" });
  }, []);
  const killLineLeft = (0, import_react.useCallback)(() => {
    dispatch({ type: "kill_line_left" });
  }, []);
  const setViewport = (0, import_react.useCallback)((width, height) => {
    dispatch({ type: "set_viewport", payload: { width, height } });
  }, []);
  const handleInput = (0, import_react.useCallback)(
    (key) => {
      const { sequence: input } = key;
      if (key.paste) {
        insert(input, { paste: key.paste });
        return;
      }
      if (!singleLine && (key.name === "return" || input === "\r" || input === "\n" || input === "\\r"))
        newline();
      else if (key.name === "left" && !key.meta && !key.ctrl) move("left");
      else if (key.ctrl && key.name === "b") move("left");
      else if (key.name === "right" && !key.meta && !key.ctrl) move("right");
      else if (key.ctrl && key.name === "f") move("right");
      else if (key.name === "up") move("up");
      else if (key.name === "down") move("down");
      else if ((key.ctrl || key.meta) && key.name === "left") move("wordLeft");
      else if (key.meta && key.name === "b") move("wordLeft");
      else if ((key.ctrl || key.meta) && key.name === "right") move("wordRight");
      else if (key.meta && key.name === "f") move("wordRight");
      else if (key.name === "home") move("home");
      else if (key.ctrl && key.name === "a") move("home");
      else if (key.name === "end") move("end");
      else if (key.ctrl && key.name === "e") move("end");
      else if (key.ctrl && key.name === "w") deleteWordLeft();
      else if ((key.meta || key.ctrl) && (key.name === "backspace" || input === "\x7F"))
        deleteWordLeft();
      else if ((key.meta || key.ctrl) && key.name === "delete") deleteWordRight();
      else if (key.name === "backspace" || input === "\x7F" || key.ctrl && key.name === "h")
        backspace();
      else if (key.name === "delete" || key.ctrl && key.name === "d") del();
      else if (key.ctrl && !key.shift && key.name === "z") undo();
      else if (key.ctrl && key.shift && key.name === "z") redo();
      else if (key.insertable) {
        insert(input, { paste: key.paste });
      }
    },
    [
      newline,
      move,
      deleteWordLeft,
      deleteWordRight,
      backspace,
      del,
      insert,
      undo,
      redo,
      singleLine
    ]
  );
  const renderedVisualLines = (0, import_react.useMemo)(
    () => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height),
    [visualLines, visualScrollRow, viewport.height]
  );
  const replaceRange = (0, import_react.useCallback)(
    (startRow, startCol, endRow, endCol, text2) => {
      dispatch({
        type: "replace_range",
        payload: { startRow, startCol, endRow, endCol, text: text2 }
      });
    },
    []
  );
  const replaceRangeByOffset = (0, import_react.useCallback)(
    (startOffset, endOffset, replacementText) => {
      const [startRow, startCol] = offsetToLogicalPos(text, startOffset);
      const [endRow, endCol] = offsetToLogicalPos(text, endOffset);
      replaceRange(startRow, startCol, endRow, endCol, replacementText);
    },
    [text, replaceRange]
  );
  const moveToOffset = (0, import_react.useCallback)((offset) => {
    dispatch({ type: "move_to_offset", payload: { offset } });
  }, []);
  const moveToVisualPosition = (0, import_react.useCallback)(
    (visRow, visCol) => {
      const { visualLines: visualLines2, visualToLogicalMap: visualToLogicalMap2 } = visualLayout;
      const clampedVisRow = Math.max(0, Math.min(visRow, visualLines2.length - 1));
      const visualLine = visualLines2[clampedVisRow] || "";
      if (visualToLogicalMap2[clampedVisRow]) {
        const [logRow, logStartCol] = visualToLogicalMap2[clampedVisRow];
        const codePoints = (0, import_textUtils.toCodePoints)(visualLine);
        let currentVisX = 0;
        let charOffset = 0;
        for (const char of codePoints) {
          const charWidth = (0, import_textUtils.getCachedStringWidth)(char);
          if (visCol < currentVisX + charWidth) {
            if (charWidth > 1 && visCol >= currentVisX + charWidth / 2) {
              charOffset++;
            }
            break;
          }
          currentVisX += charWidth;
          charOffset++;
        }
        charOffset = Math.min(charOffset, codePoints.length);
        const newCursorRow = logRow;
        const newCursorCol = logStartCol + charOffset;
        dispatch({
          type: "set_cursor",
          payload: {
            cursorRow: newCursorRow,
            cursorCol: newCursorCol,
            preferredCol: charOffset
          }
        });
      }
    },
    [visualLayout]
  );
  const getOffset = (0, import_react.useCallback)(
    () => logicalPosToOffset(lines, cursorRow, cursorCol),
    [lines, cursorRow, cursorCol]
  );
  const returnValue = (0, import_react.useMemo)(
    () => ({
      lines,
      text,
      cursor: [cursorRow, cursorCol],
      preferredCol,
      allVisualLines: visualLines,
      viewportVisualLines: renderedVisualLines,
      visualCursor,
      visualScrollRow,
      visualToLogicalMap,
      setText,
      insert,
      newline,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      getOffset,
      moveToVisualPosition,
      deleteWordLeft,
      deleteWordRight,
      killLineRight,
      killLineLeft,
      handleInput,
      setViewport
    }),
    [
      lines,
      text,
      cursorRow,
      cursorCol,
      preferredCol,
      visualLines,
      renderedVisualLines,
      visualCursor,
      visualScrollRow,
      visualToLogicalMap,
      setText,
      insert,
      newline,
      backspace,
      del,
      move,
      undo,
      redo,
      replaceRange,
      replaceRangeByOffset,
      moveToOffset,
      getOffset,
      moveToVisualPosition,
      deleteWordLeft,
      deleteWordRight,
      killLineRight,
      killLineLeft,
      handleInput,
      setViewport
    ]
  );
  return returnValue;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  findNextWordAcrossLines,
  findNextWordStartInLine,
  findPrevWordAcrossLines,
  findPrevWordStartInLine,
  findWordEndInLine,
  getLineRangeOffsets,
  getPositionFromOffsets,
  logicalPosToOffset,
  offsetToLogicalPos,
  pushUndo,
  replaceRangeInternal,
  textBufferReducer,
  useTextBuffer
});
