Show HN:10 行 Python 代码修复 Claude Code 复制粘贴错误

1作者: collectedparts5 个月前
Claude Code 使用 Ink (用于 CLI 的 React) 通过光标移动来定位文本。当你从它的终端输出中复制文本时,每一行都会用尾随空格填充以填满终端宽度,并且每一行都会从 UI 界面获得一致的起始缩进。结果是文本在终端中看起来没问题,但粘贴出来就像垃圾一样。 我原以为这是一个难题——复制操作会破坏行边界,并将填充与缩进合并成一个模糊的空格团。错。一个十六进制转储 (`pbpaste | xxd`) 显示了每个行边界处真正的 `0a` 换行符,以及一致的起始空白。整个修复方法是:去除尾随空白,去缩进。 ```python #! /usr/bin/env python3 import re, sys def clean(text): text = re.sub(r'\x1b\[[0-9;]*[a-zA-Z]', '', text) # 去除 ANSI 转义序列 text = re.sub(r'\x1b\][^\x07]*\x07', '', text) # 去除 OSC 序列 text = re.sub(r'[ \t]+$', '', text, flags=re.MULTILINE) # 去除尾随空白 lines = text.split('\n') while lines and not lines[0].strip(): lines.pop(0) # 删除前导空行 while lines and not lines[-1].strip(): lines.pop() # 删除尾随空行 indent = min((len(l) - len(l.lstrip()) for l in lines if l.strip()), default=0) return '\n'.join(l[indent:] for l in lines) + '\n' print(clean(sys.stdin.read()), end='') ``` 用法: ``` pbpaste | ./unfuck-paste pbpaste | ./unfuck-paste | pbcopy # 在剪贴板上原地修复 ``` 是的,我知道 Clean Clode 存在——但它是一个 Web 应用程序。如果我已经在终端中从终端复制内容,打开浏览器来修复终端输出感觉不对劲(并且不适用于任何敏感内容)。
查看原文
Claude Code uses Ink (React for CLIs) which positions text via cursor moves. When you copy text from its terminal output, each line gets padded with trailing spaces to fill the terminal width, and every line gets a consistent leading indent from the UI chrome. The result is text that looks right in the terminal but pastes like garbage.<p>I assumed this was a hard problem — that the copy operation was destroying line boundaries and merging padding with indentation into an ambiguous space blob. Nope. A hex dump (`pbpaste | xxd`) showed real `0a` newlines at every line boundary, and consistent leading whitespace. The entire fix is: strip trailing whitespace, dedent.<p><pre><code> #!&#x2F;usr&#x2F;bin&#x2F;env python3 import re, sys def clean(text): text = re.sub(r&#x27;\x1b\[[0-9;]*[a-zA-Z]&#x27;, &#x27;&#x27;, text) # strip ANSI escapes text = re.sub(r&#x27;\x1b\][^\x07]*\x07&#x27;, &#x27;&#x27;, text) # strip OSC sequences text = re.sub(r&#x27;[ \t]+$&#x27;, &#x27;&#x27;, text, flags=re.MULTILINE) # strip trailing whitespace lines = text.split(&#x27;\n&#x27;) while lines and not lines[0].strip(): lines.pop(0) # drop leading blank lines while lines and not lines[-1].strip(): lines.pop() # drop trailing blank lines indent = min((len(l) - len(l.lstrip()) for l in lines if l.strip()), default=0) return &#x27;\n&#x27;.join(l[indent:] for l in lines) + &#x27;\n&#x27; print(clean(sys.stdin.read()), end=&#x27;&#x27;) </code></pre> Usage:<p><pre><code> pbpaste | .&#x2F;unfuck-paste pbpaste | .&#x2F;unfuck-paste | pbcopy # fix in-place on clipboard </code></pre> Yes I know Clean Clode exists — but it&#x27;s a web app. If I&#x27;m already in a terminal copying from a terminal, opening a browser to fix terminal output feels wrong (and not appropriate for anything sensitive).