关键词:Codex、中文乱码、VS Code、PowerShell、UTF-8、终端编码、无 BOM
使用 GitHub Copilot(或 Codex)修改包含中文的文件时,保存后打开发现中文变成乱码,比如:
|
1 |
æˆ‘çˆ±ä¸æ–‡ → 实际应为 “我爱中文” |
很多人第一反应是:“是不是 VS Code 编码设置错了?”
但其实——问题不在编辑器,而在终端!
Codex 并不直接在 VS Code 编辑器里写文件,而是通过终端(Terminal)执行命令(如 echo、sed、PowerShell 脚本等)来修改文件内容。
流程如下:
???? 所以,乱码的根本原因是:终端编码 ≠ 编辑器编码。
要彻底解决,必须同时配置:
打开 VS Code 设置(Ctrl + ,),切换到 settings.json,添加:
|
1 2 3 4 |
{ "files.encoding": "utf8", "files.autoGuessEncoding": true } |
? 这一步确保 VS Code 读写一致。
在终端运行:
|
1 |
$PSVersionTable.PSVersion |
???? 强烈建议升级到 ,对 UTF-8 支持更好。
|
1 |
$PROFILE |
常见路径:
?? 注意:不要用 Add-Content -Encoding UTF8,它会写入 带 BOM 的 UTF-8,可能引发其他工具兼容问题。
我们需要的是 UTF-8 无 BOM。
运行以下完整脚本(支持幂等、避免重复、兼容 Win7/10/11):
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Setup-UTF8PowerShellProfile.ps1 $utf8Config = @' # 设置控制台使用 UTF-8 编码(无 BOM) chcp 65001 | Out-Null [Console]::InputEncoding = [System.Text.UTF8Encoding]::new() [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new() $OutputEncoding = [System.Text.UTF8Encoding]::new() # 设置默认文件操作编码为 UTF-8(无 BOM) $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8' $PSDefaultParameterValues['Set-Content:Encoding'] = 'utf8' $PSDefaultParameterValues['Add-Content:Encoding'] = 'utf8' '@ # 创建目录(如果不存在) $profileDir = Split-Path -Parent $PROFILE if (-not (Test-Path $profileDir)) { New-Item -ItemType Directory -Path $profileDir -Force | Out-Null } # 读取现有内容 $existing = if (Test-Path $PROFILE) { Get-Content $PROFILE -Raw } else { "" } # 检查是否已配置(避免重复) $hasConfig = $existing -match 'Console::OutputEncoding' -and $existing -match '\$OutputEncoding' -and $existing -match "PSDefaultParameterValues.*Out-File:Encoding" if (-not $hasConfig) { $newContent = if ($existing) { "$existing`r`n$utf8Config" } else { $utf8Config } $utf8NoBom = New-Object System.Text.UTF8Encoding($false) # $false = 无 BOM [System.IO.File]::WriteAllText($PROFILE, $newContent, $utf8NoBom) Write-Host "? UTF-8 配置已写入 Profile!路径: $PROFILE" -ForegroundColor Green } else { Write-Host "?? UTF-8 已配置,跳过。" -ForegroundColor Cyan } # 立即生效 . $PROFILE |
|
1 2 |
'中文测试' | Set-Content .\test.txt Get-Content .\test.txt |
如果输出 “中文测试” 而非乱码,说明配置成功!
临时切换:
|
1 |
chcp 65001 |
?? 仅对当前窗口有效。不建议长期使用 CMD 处理中文,推荐改用 PowerShell。
编辑 ~/.bashrc,添加:
|
1 2 |
export LANG="zh_CN.UTF-8" export LC_ALL="zh_CN.UTF-8" |
然后执行:
|
1 |
source ~/.bashrc |
| 组件 | 配置项 | 目的 |
|---|---|---|
| VS Code | "files.encoding": "utf8" | 编辑器读写统一为 UTF-8 |
| PowerShell | Profile 中设置 Console + $OutputEncoding + $PSDefaultParameterValues | 终端命令输出 UTF-8 无 BOM |
| CMD | chcp 65001(临时) | 切换代码页为 UTF-8 |
| Git Bash | export LANG=zh_CN.UTF-8 | 环境变量强制 UTF-8 |
? 只要 终端写入 和 编辑器读取 都用 UTF-8(无 BOM),Codex 修改中文文件就再也不会乱码!
???? 小提示:如果你经常在多平台开发,建议将此脚本加入你的 Windows 初始化配置清单,一劳永逸解决编码问题!
作者:一位注重编码规范的 Windows 开发者
环境:Windows 10/11 + PowerShell 5.1/7 + VS Code
目标:让每一行中文都正确显示 ????
如需获取该脚本的 .ps1 文件或一键安装版,欢迎留言!