| |
| |
| |
| |
| |
|
|
| import { spawnSync } from 'node:child_process'; |
| import fs from 'node:fs'; |
| import os from 'node:os'; |
| import pathMod from 'node:path'; |
| import { useState, useCallback, useEffect, useMemo, useReducer } from 'react'; |
| import stringWidth from 'string-width'; |
| import { unescapePath } from '@google/gemini-cli-core'; |
| import { |
| toCodePoints, |
| cpLen, |
| cpSlice, |
| stripUnsafeCharacters, |
| } from '../../utils/textUtils.js'; |
| import type { VimAction } from './vim-buffer-actions.js'; |
| import { handleVimAction } from './vim-buffer-actions.js'; |
|
|
| export type Direction = |
| | 'left' |
| | 'right' |
| | 'up' |
| | 'down' |
| | 'wordLeft' |
| | 'wordRight' |
| | 'home' |
| | 'end'; |
|
|
| |
| function isWordChar(ch: string | undefined): boolean { |
| if (ch === undefined) { |
| return false; |
| } |
| return !/[\s,.;!?]/.test(ch); |
| } |
|
|
| |
| export const isWordCharStrict = (char: string): boolean => |
| /[\w\p{L}\p{N}]/u.test(char); |
|
|
| export const isWhitespace = (char: string): boolean => /\s/.test(char); |
|
|
| |
| export const isCombiningMark = (char: string): boolean => /\p{M}/u.test(char); |
|
|
| |
| export const isWordCharWithCombining = (char: string): boolean => |
| isWordCharStrict(char) || isCombiningMark(char); |
|
|
| |
| export const getCharScript = (char: string): string => { |
| if (/[\p{Script=Latin}]/u.test(char)) return 'latin'; |
| if (/[\p{Script=Han}]/u.test(char)) return 'han'; |
| if (/[\p{Script=Arabic}]/u.test(char)) return 'arabic'; |
| if (/[\p{Script=Hiragana}]/u.test(char)) return 'hiragana'; |
| if (/[\p{Script=Katakana}]/u.test(char)) return 'katakana'; |
| if (/[\p{Script=Cyrillic}]/u.test(char)) return 'cyrillic'; |
| return 'other'; |
| }; |
|
|
| |
| export const isDifferentScript = (char1: string, char2: string): boolean => { |
| if (!isWordCharStrict(char1) || !isWordCharStrict(char2)) return false; |
| return getCharScript(char1) !== getCharScript(char2); |
| }; |
|
|
| |
| export const findNextWordStartInLine = ( |
| line: string, |
| col: number, |
| ): number | null => { |
| const chars = toCodePoints(line); |
| let i = col; |
|
|
| if (i >= chars.length) return null; |
|
|
| const currentChar = chars[i]; |
|
|
| |
| if (isWordCharStrict(currentChar)) { |
| while (i < chars.length && isWordCharWithCombining(chars[i])) { |
| |
| if ( |
| i + 1 < chars.length && |
| isWordCharStrict(chars[i + 1]) && |
| isDifferentScript(chars[i], chars[i + 1]) |
| ) { |
| i++; |
| break; |
| } |
| i++; |
| } |
| } else if (!isWhitespace(currentChar)) { |
| while ( |
| i < chars.length && |
| !isWordCharStrict(chars[i]) && |
| !isWhitespace(chars[i]) |
| ) { |
| i++; |
| } |
| } |
|
|
| |
| while (i < chars.length && isWhitespace(chars[i])) { |
| i++; |
| } |
|
|
| return i < chars.length ? i : null; |
| }; |
|
|
| |
| export const findPrevWordStartInLine = ( |
| line: string, |
| col: number, |
| ): number | null => { |
| const chars = toCodePoints(line); |
| let i = col; |
|
|
| if (i <= 0) return null; |
|
|
| i--; |
|
|
| |
| while (i >= 0 && isWhitespace(chars[i])) { |
| i--; |
| } |
|
|
| if (i < 0) return null; |
|
|
| if (isWordCharStrict(chars[i])) { |
| |
| while (i >= 0 && isWordCharStrict(chars[i])) { |
| |
| if ( |
| i - 1 >= 0 && |
| isWordCharStrict(chars[i - 1]) && |
| isDifferentScript(chars[i], chars[i - 1]) |
| ) { |
| return i; |
| } |
| i--; |
| } |
| return i + 1; |
| } else { |
| |
| while (i >= 0 && !isWordCharStrict(chars[i]) && !isWhitespace(chars[i])) { |
| i--; |
| } |
| return i + 1; |
| } |
| }; |
|
|
| |
| export const findWordEndInLine = (line: string, col: number): number | null => { |
| const chars = toCodePoints(line); |
| let i = col; |
|
|
| |
| |
| const atEndOfWordChar = |
| i < chars.length && |
| isWordCharWithCombining(chars[i]) && |
| (i + 1 >= chars.length || |
| !isWordCharWithCombining(chars[i + 1]) || |
| (isWordCharStrict(chars[i]) && |
| i + 1 < chars.length && |
| isWordCharStrict(chars[i + 1]) && |
| isDifferentScript(chars[i], chars[i + 1]))); |
|
|
| const atEndOfPunctuation = |
| i < chars.length && |
| !isWordCharWithCombining(chars[i]) && |
| !isWhitespace(chars[i]) && |
| (i + 1 >= chars.length || |
| isWhitespace(chars[i + 1]) || |
| isWordCharWithCombining(chars[i + 1])); |
|
|
| if (atEndOfWordChar || atEndOfPunctuation) { |
| |
| i++; |
| |
| while (i < chars.length && isWhitespace(chars[i])) { |
| i++; |
| } |
| } |
|
|
| |
| if (i < chars.length && !isWordCharWithCombining(chars[i])) { |
| |
| while (i < chars.length && isWhitespace(chars[i])) { |
| i++; |
| } |
| } |
|
|
| |
| let foundWord = false; |
| let lastBaseCharPos = -1; |
|
|
| if (i < chars.length && isWordCharWithCombining(chars[i])) { |
| |
| while (i < chars.length && isWordCharWithCombining(chars[i])) { |
| foundWord = true; |
|
|
| |
| if (isWordCharStrict(chars[i])) { |
| lastBaseCharPos = i; |
| } |
|
|
| |
| if ( |
| i + 1 < chars.length && |
| isWordCharStrict(chars[i + 1]) && |
| isDifferentScript(chars[i], chars[i + 1]) |
| ) { |
| i++; |
| if (isWordCharStrict(chars[i - 1])) { |
| lastBaseCharPos = i - 1; |
| } |
| break; |
| } |
|
|
| i++; |
| } |
| } else if (i < chars.length && !isWhitespace(chars[i])) { |
| |
| while ( |
| i < chars.length && |
| !isWordCharStrict(chars[i]) && |
| !isWhitespace(chars[i]) |
| ) { |
| foundWord = true; |
| lastBaseCharPos = i; |
| i++; |
| } |
| } |
|
|
| |
| |
| if (foundWord && lastBaseCharPos >= col) { |
| return lastBaseCharPos; |
| } |
|
|
| return null; |
| }; |
|
|
| |
| export const findNextWordAcrossLines = ( |
| lines: string[], |
| cursorRow: number, |
| cursorCol: number, |
| searchForWordStart: boolean, |
| ): { row: number; col: number } | null => { |
| |
| 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 = toCodePoints(line); |
|
|
| |
| if (chars.length === 0) { |
| |
| let hasWordsInLaterLines = false; |
| for (let laterRow = row + 1; laterRow < lines.length; laterRow++) { |
| const laterLine = lines[laterRow] || ''; |
| const laterChars = toCodePoints(laterLine); |
| let firstNonWhitespace = 0; |
| while ( |
| firstNonWhitespace < laterChars.length && |
| isWhitespace(laterChars[firstNonWhitespace]) |
| ) { |
| firstNonWhitespace++; |
| } |
| if (firstNonWhitespace < laterChars.length) { |
| hasWordsInLaterLines = true; |
| break; |
| } |
| } |
|
|
| |
| if (!hasWordsInLaterLines) { |
| return { row, col: 0 }; |
| } |
| continue; |
| } |
|
|
| |
| let firstNonWhitespace = 0; |
| while ( |
| firstNonWhitespace < chars.length && |
| 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; |
| }; |
|
|
| |
| export const findPrevWordAcrossLines = ( |
| lines: string[], |
| cursorRow: number, |
| cursorCol: number, |
| ): { row: number; col: number } | null => { |
| |
| 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 = toCodePoints(line); |
|
|
| if (chars.length === 0) continue; |
|
|
| |
| let lastWordStart = chars.length; |
| while (lastWordStart > 0 && isWhitespace(chars[lastWordStart - 1])) { |
| lastWordStart--; |
| } |
|
|
| if (lastWordStart > 0) { |
| |
| const wordStart = findPrevWordStartInLine(line, lastWordStart); |
| if (wordStart !== null) { |
| return { row, col: wordStart }; |
| } |
| } |
| } |
|
|
| return null; |
| }; |
|
|
| |
| export const getPositionFromOffsets = ( |
| startOffset: number, |
| endOffset: number, |
| lines: string[], |
| ) => { |
| 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 }; |
| }; |
|
|
| export const getLineRangeOffsets = ( |
| startRow: number, |
| lineCount: number, |
| lines: string[], |
| ) => { |
| 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 }; |
| }; |
|
|
| export const replaceRangeInternal = ( |
| state: TextBufferState, |
| startRow: number, |
| startCol: number, |
| endRow: number, |
| endCol: number, |
| text: string, |
| ): TextBufferState => { |
| const currentLine = (row: number) => state.lines[row] || ''; |
| const currentLineLen = (row: number) => cpLen(currentLine(row)); |
| const clamp = (value: number, min: number, max: number) => |
| 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 = clamp(startCol, 0, currentLineLen(startRow)); |
| const eCol = clamp(endCol, 0, currentLineLen(endRow)); |
|
|
| const prefix = cpSlice(currentLine(startRow), 0, sCol); |
| const suffix = 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) + |
| 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, cpLen(newLines[finalCursorRow] || '')), |
| ), |
| preferredCol: null, |
| }; |
| }; |
|
|
| export interface Viewport { |
| height: number; |
| width: number; |
| } |
|
|
| function clamp(v: number, min: number, max: number): number { |
| return v < min ? min : v > max ? max : v; |
| } |
|
|
| |
|
|
| interface UseTextBufferProps { |
| initialText?: string; |
| initialCursorOffset?: number; |
| viewport: Viewport; |
| stdin?: NodeJS.ReadStream | null; |
| setRawMode?: (mode: boolean) => void; |
| onChange?: (text: string) => void; |
| isValidPath: (path: string) => boolean; |
| shellModeActive?: boolean; |
| } |
|
|
| interface UndoHistoryEntry { |
| lines: string[]; |
| cursorRow: number; |
| cursorCol: number; |
| } |
|
|
| function calculateInitialCursorPosition( |
| initialLines: string[], |
| offset: number, |
| ): [number, number] { |
| let remainingChars = offset; |
| let row = 0; |
| while (row < initialLines.length) { |
| const lineLength = 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, cpLen(initialLines[lastRow])]; |
| } |
| return [0, 0]; |
| } |
|
|
| export function offsetToLogicalPos( |
| text: string, |
| offset: number, |
| ): [number, number] { |
| 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 = 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 = cpLen(lines[row]); |
| } else { |
| row = 0; |
| col = 0; |
| } |
| return [row, col]; |
| } |
|
|
| |
| |
| |
| |
| export function logicalPosToOffset( |
| lines: string[], |
| row: number, |
| col: number, |
| ): number { |
| let offset = 0; |
|
|
| |
| const actualRow = Math.min(row, lines.length - 1); |
|
|
| |
| for (let i = 0; i < actualRow; i++) { |
| offset += cpLen(lines[i]) + 1; |
| } |
|
|
| |
| if (actualRow >= 0 && actualRow < lines.length) { |
| offset += Math.min(col, cpLen(lines[actualRow])); |
| } |
|
|
| return offset; |
| } |
|
|
| |
| function calculateVisualLayout( |
| logicalLines: string[], |
| logicalCursor: [number, number], |
| viewportWidth: number, |
| ): { |
| visualLines: string[]; |
| visualCursor: [number, number]; |
| logicalToVisualMap: Array<Array<[number, number]>>; |
| visualToLogicalMap: Array<[number, number]>; |
| } { |
| const visualLines: string[] = []; |
| const logicalToVisualMap: Array<Array<[number, number]>> = []; |
| const visualToLogicalMap: Array<[number, number]> = []; |
| let currentVisualCursor: [number, number] = [0, 0]; |
|
|
| logicalLines.forEach((logLine, logIndex) => { |
| logicalToVisualMap[logIndex] = []; |
| if (logLine.length === 0) { |
| |
| logicalToVisualMap[logIndex].push([visualLines.length, 0]); |
| visualToLogicalMap.push([logIndex, 0]); |
| visualLines.push(''); |
| if (logIndex === logicalCursor[0] && logicalCursor[1] === 0) { |
| currentVisualCursor = [visualLines.length - 1, 0]; |
| } |
| } else { |
| |
| let currentPosInLogLine = 0; |
| const codePointsInLogLine = 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 = stringWidth(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); |
|
|
| |
| |
| if (logIndex === logicalCursor[0]) { |
| const cursorLogCol = logicalCursor[1]; |
| if ( |
| cursorLogCol >= currentPosInLogLine && |
| cursorLogCol < currentPosInLogLine + numCodePointsInChunk |
| ) { |
| currentVisualCursor = [ |
| visualLines.length - 1, |
| cursorLogCol - currentPosInLogLine, |
| ]; |
| } else if ( |
| cursorLogCol === currentPosInLogLine + numCodePointsInChunk && |
| numCodePointsInChunk > 0 |
| ) { |
| |
| currentVisualCursor = [ |
| visualLines.length - 1, |
| numCodePointsInChunk, |
| ]; |
| } |
| } |
|
|
| const logicalStartOfThisChunk = currentPosInLogLine; |
| currentPosInLogLine += numCodePointsInChunk; |
|
|
| |
| |
| |
| if ( |
| logicalStartOfThisChunk + numCodePointsInChunk < |
| codePointsInLogLine.length && |
| currentPosInLogLine < codePointsInLogLine.length && |
| codePointsInLogLine[currentPosInLogLine] === ' ' |
| ) { |
| currentPosInLogLine++; |
| } |
| } |
| |
| |
| if ( |
| logIndex === logicalCursor[0] && |
| logicalCursor[1] === codePointsInLogLine.length |
| ) { |
| const lastVisualLineIdx = visualLines.length - 1; |
| if ( |
| lastVisualLineIdx >= 0 && |
| visualLines[lastVisualLineIdx] !== undefined |
| ) { |
| currentVisualCursor = [ |
| lastVisualLineIdx, |
| cpLen(visualLines[lastVisualLineIdx]), |
| ]; |
| } |
| } |
| } |
| }); |
|
|
| |
| 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]); |
| } |
| currentVisualCursor = [0, 0]; |
| } |
| |
| |
| else if ( |
| logicalCursor[0] === logicalLines.length - 1 && |
| logicalCursor[1] === cpLen(logicalLines[logicalLines.length - 1]) && |
| visualLines.length > 0 |
| ) { |
| const lastVisLineIdx = visualLines.length - 1; |
| currentVisualCursor = [lastVisLineIdx, cpLen(visualLines[lastVisLineIdx])]; |
| } |
|
|
| return { |
| visualLines, |
| visualCursor: currentVisualCursor, |
| logicalToVisualMap, |
| visualToLogicalMap, |
| }; |
| } |
|
|
| |
|
|
| export interface TextBufferState { |
| lines: string[]; |
| cursorRow: number; |
| cursorCol: number; |
| preferredCol: number | null; |
| undoStack: UndoHistoryEntry[]; |
| redoStack: UndoHistoryEntry[]; |
| clipboard: string | null; |
| selectionAnchor: [number, number] | null; |
| viewportWidth: number; |
| } |
|
|
| const historyLimit = 100; |
|
|
| export const pushUndo = (currentState: TextBufferState): TextBufferState => { |
| 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: [] }; |
| }; |
|
|
| export type TextBufferAction = |
| | { type: 'set_text'; payload: string; pushToUndo?: boolean } |
| | { type: 'insert'; payload: string } |
| | { type: 'backspace' } |
| | { |
| type: 'move'; |
| payload: { |
| dir: Direction; |
| }; |
| } |
| | { type: 'delete' } |
| | { type: 'delete_word_left' } |
| | { type: 'delete_word_right' } |
| | { type: 'kill_line_right' } |
| | { type: 'kill_line_left' } |
| | { type: 'undo' } |
| | { type: 'redo' } |
| | { |
| type: 'replace_range'; |
| payload: { |
| startRow: number; |
| startCol: number; |
| endRow: number; |
| endCol: number; |
| text: string; |
| }; |
| } |
| | { type: 'move_to_offset'; payload: { offset: number } } |
| | { type: 'create_undo_snapshot' } |
| | { type: 'set_viewport_width'; payload: number } |
| | { type: 'vim_delete_word_forward'; payload: { count: number } } |
| | { type: 'vim_delete_word_backward'; payload: { count: number } } |
| | { type: 'vim_delete_word_end'; payload: { count: number } } |
| | { type: 'vim_change_word_forward'; payload: { count: number } } |
| | { type: 'vim_change_word_backward'; payload: { count: number } } |
| | { type: 'vim_change_word_end'; payload: { count: number } } |
| | { type: 'vim_delete_line'; payload: { count: number } } |
| | { type: 'vim_change_line'; payload: { count: number } } |
| | { type: 'vim_delete_to_end_of_line' } |
| | { type: 'vim_change_to_end_of_line' } |
| | { |
| type: 'vim_change_movement'; |
| payload: { movement: 'h' | 'j' | 'k' | 'l'; count: number }; |
| } |
| |
| | { type: 'vim_move_left'; payload: { count: number } } |
| | { type: 'vim_move_right'; payload: { count: number } } |
| | { type: 'vim_move_up'; payload: { count: number } } |
| | { type: 'vim_move_down'; payload: { count: number } } |
| | { type: 'vim_move_word_forward'; payload: { count: number } } |
| | { type: 'vim_move_word_backward'; payload: { count: number } } |
| | { type: 'vim_move_word_end'; payload: { count: number } } |
| | { type: 'vim_delete_char'; payload: { count: number } } |
| | { type: 'vim_insert_at_cursor' } |
| | { type: 'vim_append_at_cursor' } |
| | { type: 'vim_open_line_below' } |
| | { type: 'vim_open_line_above' } |
| | { type: 'vim_append_at_line_end' } |
| | { type: 'vim_insert_at_line_start' } |
| | { type: 'vim_move_to_line_start' } |
| | { type: 'vim_move_to_line_end' } |
| | { type: 'vim_move_to_first_nonwhitespace' } |
| | { type: 'vim_move_to_first_line' } |
| | { type: 'vim_move_to_last_line' } |
| | { type: 'vim_move_to_line'; payload: { lineNumber: number } } |
| | { type: 'vim_escape_insert_mode' }; |
|
|
| export function textBufferReducer( |
| state: TextBufferState, |
| action: TextBufferAction, |
| ): TextBufferState { |
| const pushUndoLocal = pushUndo; |
|
|
| const currentLine = (r: number): string => state.lines[r] ?? ''; |
| const currentLineLen = (r: number): number => 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: cpLen(lines[lastNewLineIndex] ?? ''), |
| preferredCol: null, |
| }; |
| } |
|
|
| case 'insert': { |
| const nextState = pushUndoLocal(state); |
| const newLines = [...nextState.lines]; |
| let newCursorRow = nextState.cursorRow; |
| let newCursorCol = nextState.cursorCol; |
|
|
| const currentLine = (r: number) => newLines[r] ?? ''; |
|
|
| const str = stripUnsafeCharacters( |
| action.payload.replace(/\r\n/g, '\n').replace(/\r/g, '\n'), |
| ); |
| const parts = str.split('\n'); |
| const lineContent = currentLine(newCursorRow); |
| const before = cpSlice(lineContent, 0, newCursorCol); |
| const after = 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 = cpLen(lastPartOriginal); |
| } else { |
| newLines[newCursorRow] = before + parts[0] + after; |
| newCursorCol = cpLen(before) + cpLen(parts[0]); |
| } |
|
|
| return { |
| ...nextState, |
| lines: newLines, |
| cursorRow: newCursorRow, |
| cursorCol: newCursorCol, |
| preferredCol: null, |
| }; |
| } |
|
|
| case 'backspace': { |
| const nextState = pushUndoLocal(state); |
| const newLines = [...nextState.lines]; |
| let newCursorRow = nextState.cursorRow; |
| let newCursorCol = nextState.cursorCol; |
|
|
| const currentLine = (r: number) => newLines[r] ?? ''; |
|
|
| if (newCursorCol === 0 && newCursorRow === 0) return state; |
|
|
| if (newCursorCol > 0) { |
| const lineContent = currentLine(newCursorRow); |
| newLines[newCursorRow] = |
| cpSlice(lineContent, 0, newCursorCol - 1) + |
| cpSlice(lineContent, newCursorCol); |
| newCursorCol--; |
| } else if (newCursorRow > 0) { |
| const prevLineContent = currentLine(newCursorRow - 1); |
| const currentLineContentVal = currentLine(newCursorRow); |
| const newCol = 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_width': { |
| if (action.payload === state.viewportWidth) { |
| return state; |
| } |
| return { ...state, viewportWidth: action.payload }; |
| } |
|
|
| case 'move': { |
| const { dir } = action.payload; |
| const { lines, cursorRow, cursorCol, viewportWidth } = state; |
| const visualLayout = calculateVisualLayout( |
| lines, |
| [cursorRow, cursorCol], |
| viewportWidth, |
| ); |
| const { visualLines, visualCursor, visualToLogicalMap } = visualLayout; |
|
|
| let newVisualRow = visualCursor[0]; |
| let newVisualCol = visualCursor[1]; |
| let newPreferredCol = state.preferredCol; |
|
|
| const currentVisLineLen = cpLen(visualLines[newVisualRow] ?? ''); |
|
|
| switch (dir) { |
| case 'left': |
| newPreferredCol = null; |
| if (newVisualCol > 0) { |
| newVisualCol--; |
| } else if (newVisualRow > 0) { |
| newVisualRow--; |
| newVisualCol = 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, |
| cpLen(visualLines[newVisualRow] ?? ''), |
| ); |
| } |
| break; |
| case 'down': |
| if (newVisualRow < visualLines.length - 1) { |
| if (newPreferredCol === null) newPreferredCol = newVisualCol; |
| newVisualRow++; |
| newVisualCol = clamp( |
| newPreferredCol, |
| 0, |
| cpLen(visualLines[newVisualRow] ?? ''), |
| ); |
| } |
| break; |
| case 'home': |
| newPreferredCol = null; |
| newVisualCol = 0; |
| break; |
| case 'end': |
| newPreferredCol = null; |
| newVisualCol = currentVisLineLen; |
| break; |
| case 'wordLeft': { |
| const { cursorRow, cursorCol, lines } = state; |
| if (cursorCol === 0 && cursorRow === 0) return state; |
|
|
| let newCursorRow = cursorRow; |
| let newCursorCol = cursorCol; |
|
|
| if (cursorCol === 0) { |
| newCursorRow--; |
| newCursorCol = cpLen(lines[newCursorRow] ?? ''); |
| } else { |
| const lineContent = lines[cursorRow]; |
| const arr = toCodePoints(lineContent); |
| let start = cursorCol; |
| let onlySpaces = true; |
| for (let i = 0; i < start; i++) { |
| if (isWordChar(arr[i])) { |
| onlySpaces = false; |
| break; |
| } |
| } |
| if (onlySpaces && start > 0) { |
| start--; |
| } else { |
| while (start > 0 && !isWordChar(arr[start - 1])) start--; |
| while (start > 0 && isWordChar(arr[start - 1])) start--; |
| } |
| newCursorCol = start; |
| } |
| return { |
| ...state, |
| cursorRow: newCursorRow, |
| cursorCol: newCursorCol, |
| preferredCol: null, |
| }; |
| } |
| case 'wordRight': { |
| const { cursorRow, cursorCol, lines } = state; |
| if ( |
| cursorRow === lines.length - 1 && |
| cursorCol === cpLen(lines[cursorRow] ?? '') |
| ) { |
| return state; |
| } |
|
|
| let newCursorRow = cursorRow; |
| let newCursorCol = cursorCol; |
| const lineContent = lines[cursorRow] ?? ''; |
| const arr = toCodePoints(lineContent); |
|
|
| if (cursorCol >= arr.length) { |
| newCursorRow++; |
| newCursorCol = 0; |
| } else { |
| let end = cursorCol; |
| while (end < arr.length && !isWordChar(arr[end])) end++; |
| while (end < arr.length && isWordChar(arr[end])) end++; |
| newCursorCol = end; |
| } |
| return { |
| ...state, |
| cursorRow: newCursorRow, |
| cursorCol: newCursorCol, |
| preferredCol: null, |
| }; |
| } |
| default: |
| break; |
| } |
|
|
| if (visualToLogicalMap[newVisualRow]) { |
| const [logRow, logStartCol] = visualToLogicalMap[newVisualRow]; |
| return { |
| ...state, |
| cursorRow: logRow, |
| cursorCol: clamp( |
| logStartCol + newVisualCol, |
| 0, |
| cpLen(state.lines[logRow] ?? ''), |
| ), |
| preferredCol: newPreferredCol, |
| }; |
| } |
| return state; |
| } |
|
|
| 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] = |
| cpSlice(lineContent, 0, cursorCol) + |
| 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; |
| if (cursorCol === 0) { |
| |
| const nextState = pushUndoLocal(state); |
| const prevLineContent = currentLine(cursorRow - 1); |
| const currentLineContentVal = currentLine(cursorRow); |
| const newCol = cpLen(prevLineContent); |
| const newLines = [...nextState.lines]; |
| newLines[cursorRow - 1] = prevLineContent + currentLineContentVal; |
| newLines.splice(cursorRow, 1); |
| return { |
| ...nextState, |
| lines: newLines, |
| cursorRow: cursorRow - 1, |
| cursorCol: newCol, |
| preferredCol: null, |
| }; |
| } |
| const nextState = pushUndoLocal(state); |
| const lineContent = currentLine(cursorRow); |
| const arr = toCodePoints(lineContent); |
| let start = cursorCol; |
| let onlySpaces = true; |
| for (let i = 0; i < start; i++) { |
| if (isWordChar(arr[i])) { |
| onlySpaces = false; |
| break; |
| } |
| } |
| if (onlySpaces && start > 0) { |
| start--; |
| } else { |
| while (start > 0 && !isWordChar(arr[start - 1])) start--; |
| while (start > 0 && isWordChar(arr[start - 1])) start--; |
| } |
| const newLines = [...nextState.lines]; |
| newLines[cursorRow] = |
| cpSlice(lineContent, 0, start) + cpSlice(lineContent, cursorCol); |
| return { |
| ...nextState, |
| lines: newLines, |
| cursorCol: start, |
| preferredCol: null, |
| }; |
| } |
|
|
| case 'delete_word_right': { |
| const { cursorRow, cursorCol, lines } = state; |
| const lineContent = currentLine(cursorRow); |
| const arr = toCodePoints(lineContent); |
| if (cursorCol >= arr.length && cursorRow === lines.length - 1) |
| return state; |
| if (cursorCol >= arr.length) { |
| |
| 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 }; |
| } |
| const nextState = pushUndoLocal(state); |
| let end = cursorCol; |
| while (end < arr.length && !isWordChar(arr[end])) end++; |
| while (end < arr.length && isWordChar(arr[end])) end++; |
| const newLines = [...nextState.lines]; |
| newLines[cursorRow] = |
| cpSlice(lineContent, 0, cursorCol) + 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] = 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] = 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); |
| } |
|
|
| |
| case 'vim_delete_word_forward': |
| case 'vim_delete_word_backward': |
| case 'vim_delete_word_end': |
| case 'vim_change_word_forward': |
| case 'vim_change_word_backward': |
| case 'vim_change_word_end': |
| case 'vim_delete_line': |
| case 'vim_change_line': |
| case 'vim_delete_to_end_of_line': |
| case 'vim_change_to_end_of_line': |
| case 'vim_change_movement': |
| case 'vim_move_left': |
| case 'vim_move_right': |
| case 'vim_move_up': |
| case 'vim_move_down': |
| case 'vim_move_word_forward': |
| case 'vim_move_word_backward': |
| case 'vim_move_word_end': |
| case 'vim_delete_char': |
| case 'vim_insert_at_cursor': |
| case 'vim_append_at_cursor': |
| case 'vim_open_line_below': |
| case 'vim_open_line_above': |
| case 'vim_append_at_line_end': |
| case 'vim_insert_at_line_start': |
| case 'vim_move_to_line_start': |
| case 'vim_move_to_line_end': |
| case 'vim_move_to_first_nonwhitespace': |
| case 'vim_move_to_first_line': |
| case 'vim_move_to_last_line': |
| case 'vim_move_to_line': |
| case 'vim_escape_insert_mode': |
| return handleVimAction(state, action as VimAction); |
|
|
| default: { |
| const exhaustiveCheck: never = action; |
| console.error(`Unknown action encountered: ${exhaustiveCheck}`); |
| return state; |
| } |
| } |
| } |
|
|
| |
|
|
| export function useTextBuffer({ |
| initialText = '', |
| initialCursorOffset = 0, |
| viewport, |
| stdin, |
| setRawMode, |
| onChange, |
| isValidPath, |
| shellModeActive = false, |
| }: UseTextBufferProps): TextBuffer { |
| const initialState = useMemo((): TextBufferState => { |
| const lines = initialText.split('\n'); |
| const [initialCursorRow, initialCursorCol] = calculateInitialCursorPosition( |
| lines.length === 0 ? [''] : lines, |
| initialCursorOffset, |
| ); |
| return { |
| lines: lines.length === 0 ? [''] : lines, |
| cursorRow: initialCursorRow, |
| cursorCol: initialCursorCol, |
| preferredCol: null, |
| undoStack: [], |
| redoStack: [], |
| clipboard: null, |
| selectionAnchor: null, |
| viewportWidth: viewport.width, |
| }; |
| }, [initialText, initialCursorOffset, viewport.width]); |
|
|
| const [state, dispatch] = useReducer(textBufferReducer, initialState); |
| const { lines, cursorRow, cursorCol, preferredCol, selectionAnchor } = state; |
|
|
| const text = useMemo(() => lines.join('\n'), [lines]); |
|
|
| const visualLayout = useMemo( |
| () => |
| calculateVisualLayout(lines, [cursorRow, cursorCol], state.viewportWidth), |
| [lines, cursorRow, cursorCol, state.viewportWidth], |
| ); |
|
|
| const { visualLines, visualCursor } = visualLayout; |
|
|
| const [visualScrollRow, setVisualScrollRow] = useState<number>(0); |
|
|
| useEffect(() => { |
| if (onChange) { |
| onChange(text); |
| } |
| }, [text, onChange]); |
|
|
| useEffect(() => { |
| dispatch({ type: 'set_viewport_width', payload: viewport.width }); |
| }, [viewport.width]); |
|
|
| |
| useEffect(() => { |
| const { height } = viewport; |
| let newVisualScrollRow = visualScrollRow; |
|
|
| if (visualCursor[0] < visualScrollRow) { |
| newVisualScrollRow = visualCursor[0]; |
| } else if (visualCursor[0] >= visualScrollRow + height) { |
| newVisualScrollRow = visualCursor[0] - height + 1; |
| } |
| if (newVisualScrollRow !== visualScrollRow) { |
| setVisualScrollRow(newVisualScrollRow); |
| } |
| }, [visualCursor, visualScrollRow, viewport]); |
|
|
| const insert = useCallback( |
| (ch: string, { paste = false }: { paste?: boolean } = {}): void => { |
| if (/[\n\r]/.test(ch)) { |
| dispatch({ type: 'insert', payload: ch }); |
| return; |
| } |
|
|
| const minLengthToInferAsDragDrop = 3; |
| if ( |
| ch.length >= minLengthToInferAsDragDrop && |
| !shellModeActive && |
| paste |
| ) { |
| let potentialPath = ch.trim(); |
| const quoteMatch = potentialPath.match(/^'(.*)'$/); |
| if (quoteMatch) { |
| potentialPath = quoteMatch[1]; |
| } |
|
|
| potentialPath = potentialPath.trim(); |
| if (isValidPath(unescapePath(potentialPath))) { |
| ch = `@${potentialPath} `; |
| } |
| } |
|
|
| let currentText = ''; |
| for (const char of 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 }); |
| } |
| }, |
| [isValidPath, shellModeActive], |
| ); |
|
|
| const newline = useCallback((): void => { |
| dispatch({ type: 'insert', payload: '\n' }); |
| }, []); |
|
|
| const backspace = useCallback((): void => { |
| dispatch({ type: 'backspace' }); |
| }, []); |
|
|
| const del = useCallback((): void => { |
| dispatch({ type: 'delete' }); |
| }, []); |
|
|
| const move = useCallback((dir: Direction): void => { |
| dispatch({ type: 'move', payload: { dir } }); |
| }, []); |
|
|
| const undo = useCallback((): void => { |
| dispatch({ type: 'undo' }); |
| }, []); |
|
|
| const redo = useCallback((): void => { |
| dispatch({ type: 'redo' }); |
| }, []); |
|
|
| const setText = useCallback((newText: string): void => { |
| dispatch({ type: 'set_text', payload: newText }); |
| }, []); |
|
|
| const deleteWordLeft = useCallback((): void => { |
| dispatch({ type: 'delete_word_left' }); |
| }, []); |
|
|
| const deleteWordRight = useCallback((): void => { |
| dispatch({ type: 'delete_word_right' }); |
| }, []); |
|
|
| const killLineRight = useCallback((): void => { |
| dispatch({ type: 'kill_line_right' }); |
| }, []); |
|
|
| const killLineLeft = useCallback((): void => { |
| dispatch({ type: 'kill_line_left' }); |
| }, []); |
|
|
| |
| const vimDeleteWordForward = useCallback((count: number): void => { |
| dispatch({ type: 'vim_delete_word_forward', payload: { count } }); |
| }, []); |
|
|
| const vimDeleteWordBackward = useCallback((count: number): void => { |
| dispatch({ type: 'vim_delete_word_backward', payload: { count } }); |
| }, []); |
|
|
| const vimDeleteWordEnd = useCallback((count: number): void => { |
| dispatch({ type: 'vim_delete_word_end', payload: { count } }); |
| }, []); |
|
|
| const vimChangeWordForward = useCallback((count: number): void => { |
| dispatch({ type: 'vim_change_word_forward', payload: { count } }); |
| }, []); |
|
|
| const vimChangeWordBackward = useCallback((count: number): void => { |
| dispatch({ type: 'vim_change_word_backward', payload: { count } }); |
| }, []); |
|
|
| const vimChangeWordEnd = useCallback((count: number): void => { |
| dispatch({ type: 'vim_change_word_end', payload: { count } }); |
| }, []); |
|
|
| const vimDeleteLine = useCallback((count: number): void => { |
| dispatch({ type: 'vim_delete_line', payload: { count } }); |
| }, []); |
|
|
| const vimChangeLine = useCallback((count: number): void => { |
| dispatch({ type: 'vim_change_line', payload: { count } }); |
| }, []); |
|
|
| const vimDeleteToEndOfLine = useCallback((): void => { |
| dispatch({ type: 'vim_delete_to_end_of_line' }); |
| }, []); |
|
|
| const vimChangeToEndOfLine = useCallback((): void => { |
| dispatch({ type: 'vim_change_to_end_of_line' }); |
| }, []); |
|
|
| const vimChangeMovement = useCallback( |
| (movement: 'h' | 'j' | 'k' | 'l', count: number): void => { |
| dispatch({ type: 'vim_change_movement', payload: { movement, count } }); |
| }, |
| [], |
| ); |
|
|
| |
| const vimMoveLeft = useCallback((count: number): void => { |
| dispatch({ type: 'vim_move_left', payload: { count } }); |
| }, []); |
|
|
| const vimMoveRight = useCallback((count: number): void => { |
| dispatch({ type: 'vim_move_right', payload: { count } }); |
| }, []); |
|
|
| const vimMoveUp = useCallback((count: number): void => { |
| dispatch({ type: 'vim_move_up', payload: { count } }); |
| }, []); |
|
|
| const vimMoveDown = useCallback((count: number): void => { |
| dispatch({ type: 'vim_move_down', payload: { count } }); |
| }, []); |
|
|
| const vimMoveWordForward = useCallback((count: number): void => { |
| dispatch({ type: 'vim_move_word_forward', payload: { count } }); |
| }, []); |
|
|
| const vimMoveWordBackward = useCallback((count: number): void => { |
| dispatch({ type: 'vim_move_word_backward', payload: { count } }); |
| }, []); |
|
|
| const vimMoveWordEnd = useCallback((count: number): void => { |
| dispatch({ type: 'vim_move_word_end', payload: { count } }); |
| }, []); |
|
|
| const vimDeleteChar = useCallback((count: number): void => { |
| dispatch({ type: 'vim_delete_char', payload: { count } }); |
| }, []); |
|
|
| const vimInsertAtCursor = useCallback((): void => { |
| dispatch({ type: 'vim_insert_at_cursor' }); |
| }, []); |
|
|
| const vimAppendAtCursor = useCallback((): void => { |
| dispatch({ type: 'vim_append_at_cursor' }); |
| }, []); |
|
|
| const vimOpenLineBelow = useCallback((): void => { |
| dispatch({ type: 'vim_open_line_below' }); |
| }, []); |
|
|
| const vimOpenLineAbove = useCallback((): void => { |
| dispatch({ type: 'vim_open_line_above' }); |
| }, []); |
|
|
| const vimAppendAtLineEnd = useCallback((): void => { |
| dispatch({ type: 'vim_append_at_line_end' }); |
| }, []); |
|
|
| const vimInsertAtLineStart = useCallback((): void => { |
| dispatch({ type: 'vim_insert_at_line_start' }); |
| }, []); |
|
|
| const vimMoveToLineStart = useCallback((): void => { |
| dispatch({ type: 'vim_move_to_line_start' }); |
| }, []); |
|
|
| const vimMoveToLineEnd = useCallback((): void => { |
| dispatch({ type: 'vim_move_to_line_end' }); |
| }, []); |
|
|
| const vimMoveToFirstNonWhitespace = useCallback((): void => { |
| dispatch({ type: 'vim_move_to_first_nonwhitespace' }); |
| }, []); |
|
|
| const vimMoveToFirstLine = useCallback((): void => { |
| dispatch({ type: 'vim_move_to_first_line' }); |
| }, []); |
|
|
| const vimMoveToLastLine = useCallback((): void => { |
| dispatch({ type: 'vim_move_to_last_line' }); |
| }, []); |
|
|
| const vimMoveToLine = useCallback((lineNumber: number): void => { |
| dispatch({ type: 'vim_move_to_line', payload: { lineNumber } }); |
| }, []); |
|
|
| const vimEscapeInsertMode = useCallback((): void => { |
| dispatch({ type: 'vim_escape_insert_mode' }); |
| }, []); |
|
|
| const openInExternalEditor = useCallback( |
| async (opts: { editor?: string } = {}): Promise<void> => { |
| const editor = |
| opts.editor ?? |
| process.env['VISUAL'] ?? |
| process.env['EDITOR'] ?? |
| (process.platform === 'win32' ? 'notepad' : 'vi'); |
| const tmpDir = fs.mkdtempSync(pathMod.join(os.tmpdir(), 'gemini-edit-')); |
| const filePath = pathMod.join(tmpDir, 'buffer.txt'); |
| fs.writeFileSync(filePath, text, 'utf8'); |
|
|
| dispatch({ type: 'create_undo_snapshot' }); |
|
|
| const wasRaw = stdin?.isRaw ?? false; |
| try { |
| setRawMode?.(false); |
| const { status, error } = spawnSync(editor, [filePath], { |
| stdio: 'inherit', |
| }); |
| if (error) throw error; |
| if (typeof status === 'number' && status !== 0) |
| throw new Error(`External editor exited with status ${status}`); |
|
|
| let newText = fs.readFileSync(filePath, 'utf8'); |
| newText = newText.replace(/\r\n?/g, '\n'); |
| dispatch({ type: 'set_text', payload: newText, pushToUndo: false }); |
| } catch (err) { |
| console.error('[useTextBuffer] external editor error', err); |
| } finally { |
| if (wasRaw) setRawMode?.(true); |
| try { |
| fs.unlinkSync(filePath); |
| } catch { |
| |
| } |
| try { |
| fs.rmdirSync(tmpDir); |
| } catch { |
| |
| } |
| } |
| }, |
| [text, stdin, setRawMode], |
| ); |
|
|
| const handleInput = useCallback( |
| (key: { |
| name: string; |
| ctrl: boolean; |
| meta: boolean; |
| shift: boolean; |
| paste: boolean; |
| sequence: string; |
| }): void => { |
| const { sequence: input } = key; |
|
|
| if (key.paste) { |
| |
| |
| insert(input, { paste: key.paste }); |
| return; |
| } |
|
|
| if ( |
| 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 (input && !key.ctrl && !key.meta) { |
| insert(input, { paste: key.paste }); |
| } |
| }, |
| [newline, move, deleteWordLeft, deleteWordRight, backspace, del, insert], |
| ); |
|
|
| const renderedVisualLines = useMemo( |
| () => visualLines.slice(visualScrollRow, visualScrollRow + viewport.height), |
| [visualLines, visualScrollRow, viewport.height], |
| ); |
|
|
| const replaceRange = useCallback( |
| ( |
| startRow: number, |
| startCol: number, |
| endRow: number, |
| endCol: number, |
| text: string, |
| ): void => { |
| dispatch({ |
| type: 'replace_range', |
| payload: { startRow, startCol, endRow, endCol, text }, |
| }); |
| }, |
| [], |
| ); |
|
|
| const replaceRangeByOffset = useCallback( |
| (startOffset: number, endOffset: number, replacementText: string): void => { |
| const [startRow, startCol] = offsetToLogicalPos(text, startOffset); |
| const [endRow, endCol] = offsetToLogicalPos(text, endOffset); |
| replaceRange(startRow, startCol, endRow, endCol, replacementText); |
| }, |
| [text, replaceRange], |
| ); |
|
|
| const moveToOffset = useCallback((offset: number): void => { |
| dispatch({ type: 'move_to_offset', payload: { offset } }); |
| }, []); |
|
|
| const returnValue: TextBuffer = { |
| lines, |
| text, |
| cursor: [cursorRow, cursorCol], |
| preferredCol, |
| selectionAnchor, |
|
|
| allVisualLines: visualLines, |
| viewportVisualLines: renderedVisualLines, |
| visualCursor, |
| visualScrollRow, |
|
|
| setText, |
| insert, |
| newline, |
| backspace, |
| del, |
| move, |
| undo, |
| redo, |
| replaceRange, |
| replaceRangeByOffset, |
| moveToOffset, |
| deleteWordLeft, |
| deleteWordRight, |
| killLineRight, |
| killLineLeft, |
| handleInput, |
| openInExternalEditor, |
| |
| vimDeleteWordForward, |
| vimDeleteWordBackward, |
| vimDeleteWordEnd, |
| vimChangeWordForward, |
| vimChangeWordBackward, |
| vimChangeWordEnd, |
| vimDeleteLine, |
| vimChangeLine, |
| vimDeleteToEndOfLine, |
| vimChangeToEndOfLine, |
| vimChangeMovement, |
| vimMoveLeft, |
| vimMoveRight, |
| vimMoveUp, |
| vimMoveDown, |
| vimMoveWordForward, |
| vimMoveWordBackward, |
| vimMoveWordEnd, |
| vimDeleteChar, |
| vimInsertAtCursor, |
| vimAppendAtCursor, |
| vimOpenLineBelow, |
| vimOpenLineAbove, |
| vimAppendAtLineEnd, |
| vimInsertAtLineStart, |
| vimMoveToLineStart, |
| vimMoveToLineEnd, |
| vimMoveToFirstNonWhitespace, |
| vimMoveToFirstLine, |
| vimMoveToLastLine, |
| vimMoveToLine, |
| vimEscapeInsertMode, |
| }; |
| return returnValue; |
| } |
|
|
| export interface TextBuffer { |
| |
| lines: string[]; |
| text: string; |
| cursor: [number, number]; |
| |
| |
| |
| |
| |
| |
| preferredCol: number | null; |
| selectionAnchor: [number, number] | null; |
|
|
| |
| allVisualLines: string[]; |
| viewportVisualLines: string[]; |
| visualCursor: [number, number]; |
| visualScrollRow: number; |
|
|
| |
|
|
| |
| |
| |
| |
| setText: (text: string) => void; |
| |
| |
| |
| insert: (ch: string, opts?: { paste?: boolean }) => void; |
| newline: () => void; |
| backspace: () => void; |
| del: () => void; |
| move: (dir: Direction) => void; |
| undo: () => void; |
| redo: () => void; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| replaceRange: ( |
| startRow: number, |
| startCol: number, |
| endRow: number, |
| endCol: number, |
| text: string, |
| ) => void; |
| |
| |
| |
| |
| |
| |
| deleteWordLeft: () => void; |
| |
| |
| |
| |
| |
| deleteWordRight: () => void; |
| |
| |
| |
| killLineRight: () => void; |
| |
| |
| |
| killLineLeft: () => void; |
| |
| |
| |
| handleInput: (key: { |
| name: string; |
| ctrl: boolean; |
| meta: boolean; |
| shift: boolean; |
| paste: boolean; |
| sequence: string; |
| }) => void; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| openInExternalEditor: (opts?: { editor?: string }) => Promise<void>; |
|
|
| replaceRangeByOffset: ( |
| startOffset: number, |
| endOffset: number, |
| replacementText: string, |
| ) => void; |
| moveToOffset(offset: number): void; |
|
|
| |
| |
| |
| |
| vimDeleteWordForward: (count: number) => void; |
| |
| |
| |
| vimDeleteWordBackward: (count: number) => void; |
| |
| |
| |
| vimDeleteWordEnd: (count: number) => void; |
| |
| |
| |
| vimChangeWordForward: (count: number) => void; |
| |
| |
| |
| vimChangeWordBackward: (count: number) => void; |
| |
| |
| |
| vimChangeWordEnd: (count: number) => void; |
| |
| |
| |
| vimDeleteLine: (count: number) => void; |
| |
| |
| |
| vimChangeLine: (count: number) => void; |
| |
| |
| |
| vimDeleteToEndOfLine: () => void; |
| |
| |
| |
| vimChangeToEndOfLine: () => void; |
| |
| |
| |
| vimChangeMovement: (movement: 'h' | 'j' | 'k' | 'l', count: number) => void; |
| |
| |
| |
| vimMoveLeft: (count: number) => void; |
| |
| |
| |
| vimMoveRight: (count: number) => void; |
| |
| |
| |
| vimMoveUp: (count: number) => void; |
| |
| |
| |
| vimMoveDown: (count: number) => void; |
| |
| |
| |
| vimMoveWordForward: (count: number) => void; |
| |
| |
| |
| vimMoveWordBackward: (count: number) => void; |
| |
| |
| |
| vimMoveWordEnd: (count: number) => void; |
| |
| |
| |
| vimDeleteChar: (count: number) => void; |
| |
| |
| |
| vimInsertAtCursor: () => void; |
| |
| |
| |
| vimAppendAtCursor: () => void; |
| |
| |
| |
| vimOpenLineBelow: () => void; |
| |
| |
| |
| vimOpenLineAbove: () => void; |
| |
| |
| |
| vimAppendAtLineEnd: () => void; |
| |
| |
| |
| vimInsertAtLineStart: () => void; |
| |
| |
| |
| vimMoveToLineStart: () => void; |
| |
| |
| |
| vimMoveToLineEnd: () => void; |
| |
| |
| |
| vimMoveToFirstNonWhitespace: () => void; |
| |
| |
| |
| vimMoveToFirstLine: () => void; |
| |
| |
| |
| vimMoveToLastLine: () => void; |
| |
| |
| |
| vimMoveToLine: (lineNumber: number) => void; |
| |
| |
| |
| vimEscapeInsertMode: () => void; |
| } |
|
|