Files
Netcatty/components/terminal/hooks/useTerminalContextActions.ts
T
陈大猫andClaude Opus 4.5 932bb5032d fix: wrap terminal paste in bracketed paste escape sequences (#191)
All three paste paths (hotkey, context menu, middle-click) were sending
raw clipboard text directly to the session backend via writeToSession(),
bypassing xterm's built-in term.paste() which handles bracketed paste
wrapping. When a remote application like vim enables bracketed paste
mode (CSI ?2004h), pasted text must be wrapped in \e[200~ / \e[201~
so the application can distinguish paste from typed input.

Without these markers, vim's autoindent treats each pasted newline as
a manual Enter keypress, causing indentation to accumulate
progressively with each line (the "staircase effect").

Now checks term.modes.bracketedPasteMode before sending and wraps
the text accordingly on all paste paths.

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-07 14:33:51 +08:00

68 lines
2.0 KiB
TypeScript

import type { Terminal as XTerm } from "@xterm/xterm";
import { useCallback } from "react";
import type { RefObject } from "react";
import { logger } from "../../../lib/logger";
import { normalizeLineEndings, wrapBracketedPaste } from "../../../lib/utils";
type TerminalBackendWriteApi = {
writeToSession: (sessionId: string, data: string) => void;
};
export const useTerminalContextActions = ({
termRef,
sessionRef,
terminalBackend,
onHasSelectionChange,
}: {
termRef: RefObject<XTerm | null>;
sessionRef: RefObject<string | null>;
terminalBackend: TerminalBackendWriteApi;
onHasSelectionChange?: (hasSelection: boolean) => void;
}) => {
const onCopy = useCallback(() => {
const term = termRef.current;
if (!term) return;
const selection = term.getSelection();
if (selection) {
navigator.clipboard.writeText(selection);
}
}, [termRef]);
const onPaste = useCallback(async () => {
const term = termRef.current;
if (!term) return;
try {
const text = await navigator.clipboard.readText();
if (text && sessionRef.current) {
let data = normalizeLineEndings(text);
if (term.modes.bracketedPasteMode) data = wrapBracketedPaste(data);
terminalBackend.writeToSession(sessionRef.current, data);
}
} catch (err) {
logger.warn("Failed to paste from clipboard", err);
}
}, [sessionRef, termRef, terminalBackend]);
const onSelectAll = useCallback(() => {
const term = termRef.current;
if (!term) return;
term.selectAll();
onHasSelectionChange?.(true);
}, [onHasSelectionChange, termRef]);
const onClear = useCallback(() => {
const term = termRef.current;
if (!term) return;
term.clear();
}, [termRef]);
const onSelectWord = useCallback(() => {
const term = termRef.current;
if (!term) return;
term.selectAll();
onHasSelectionChange?.(true);
}, [onHasSelectionChange, termRef]);
return { onCopy, onPaste, onSelectAll, onClear, onSelectWord };
};