Files
Triple-C/app/src/components/terminal/trimSelection.ts
T
shadow-test 7f6655fbcf
Build App / compute-version (push) Successful in 2s
Build App / build-macos (push) Successful in 2m31s
Build App / build-windows (push) Successful in 4m39s
Build App / build-linux (push) Successful in 5m42s
Build App / create-tag (push) Successful in 9s
Build App / sync-to-github (push) Successful in 17s
Trim whitespace on terminal copy by default, keep raw copy on Ctrl+Shift+Alt+C and right-click menu
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 08:58:56 -07:00

43 lines
1.4 KiB
TypeScript

/**
* Cleans up terminal selections for pasting into other tools.
*
* Terminal UI padding (left margin from the xterm container, alignment spaces
* at end of line) ends up in the copied text. This helper removes that cruft
* while preserving the *relative* indentation of the content — so code blocks
* keep their shape but lose the wrapper padding.
*
* Steps:
* 1. Dedent — strip the common leading whitespace count from every line.
* 2. trimEnd — drop trailing whitespace per line.
* 3. Drop fully-blank leading and trailing lines.
*
* Internal newlines and relative indentation are preserved. Pure function.
*/
export function trimSelection(text: string): string {
if (!text) return text;
const lines = text.split("\n");
let minIndent = Infinity;
for (const line of lines) {
if (line.trim() === "") continue;
const match = line.match(/^[ \t]*/);
const indent = match ? match[0].length : 0;
if (indent < minIndent) minIndent = indent;
if (minIndent === 0) break;
}
if (!Number.isFinite(minIndent)) minIndent = 0;
const processed = lines.map((line) => {
const afterDedent = line.length >= minIndent ? line.slice(minIndent) : "";
return afterDedent.trimEnd();
});
let start = 0;
let end = processed.length;
while (start < end && processed[start] === "") start++;
while (end > start && processed[end - 1] === "") end--;
return processed.slice(start, end).join("\n");
}