共114行
2026-02-07 02:22:58
你在Windows下使用Emacs的shell(如eshell、shell-mode)时出现了乱码问题,这是Windows系统编码与Emacs编码不兼容导致的,以下是针对性的完整解决方案,从核心配置到分场景优化逐一说明:
在你的 init.el 配置文件中添加以下代码,优先解决编码不匹配的核心问题:
;; 1. 全局UTF-8编码(基础,确保Emacs自身编码统一)
(set-language-environment "UTF-8")
(set-default-coding-systems 'utf-8)
(set-buffer-file-coding-system 'utf-8)
(set-clipboard-coding-system 'utf-8)
(set-file-name-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(set-terminal-coding-system 'utf-8)
(prefer-coding-system 'utf-8)
;; 2. Windows shell 编码适配(核心解决shell乱码)
;; 针对 cmd.exe / PowerShell 的编码映射
(setq process-coding-system-alist
(append '(("cmd" . (utf-8 . gbk))
("powershell" . (utf-8 . gbk))
("pwsh" . (utf-8 . gbk))
(eshell . (utf-8 . utf-8)))
process-coding-system-alist))
;; 3. 强制设置shell输出编码为GBK(Windows默认控制台编码)
(setq default-process-coding-system '(utf-8 . gbk))
Windows的 cmd.exe、PowerShell 默认使用 GBK/GB2312 编码(中文系统),而Emacs默认使用UTF-8编码,两者编码不匹配是乱码的根本原因。上述配置通过 process-coding-system-alist 和 default-process-coding-system 建立了Emacs与Windows shell的编码映射,实现双向兼容。
Eshell是Emacs原生shell,额外添加以下配置确保无乱码:
;; Eshell 专属编码配置
(defun eshell-mode-setup ()
(set-buffer-process-coding-system 'utf-8 'utf-8)
(setq eshell-output-encoding 'utf-8)
(setq eshell-input-encoding 'utf-8))
(add-hook 'eshell-mode-hook 'eshell-mode-setup)
;; 可选:Eshell 中文显示优化
(setq eshell-prefer-lisp-functions nil) ; 避免部分命令输出异常
如果使用 M-x shell 调用外部终端出现乱码,添加以下钩子配置:
;; Shell-Mode 启动时自动配置编码
(defun shell-mode-setup ()
(set-buffer-process-coding-system 'utf-8 'gbk)
(setq comint-output-filter-functions
(remove 'comint-postoutput-scroll-to-bottom
comint-output-filter-functions)))
(add-hook 'shell-mode-hook 'shell-mode-setup)
;; 解决Windows下shell命令输出换行异常(附带优化)
(setq comint-process-echoes t)
(setq comint-scroll-to-bottom-on-output t)
若优先使用PowerShell 7+(pwsh),补充以下配置:
;; 设置默认shell为pwsh(可选,优先使用新版PowerShell)
(setq explicit-shell-file-name "C:/Program Files/PowerShell/7/pwsh.exe")
(setq shell-file-name explicit-shell-file-name)
;; pwsh 编码强制适配
(defun pwsh-mode-setup ()
(set-buffer-process-coding-system 'utf-8 'gbk))
(add-hook 'powershell-mode-hook 'pwsh-mode-setup)
如果上述Emacs配置仍无法解决乱码,可修改Windows系统控制台编码,从根源上统一编码:
以管理员身份打开 cmd.exe
执行以下命令,设置控制台默认编码为UTF-8:
chcp 65001(永久生效)修改注册表(谨慎操作):
Win+R,输入 regedit 打开注册表编辑器HKEY_CURRENT_USER\Console\%SystemRoot%_system32_cmd.exeCodePage,值为 65001init.el 文件(C-x C-s)init.el 缓冲区执行 M-x eval-buffer(无需重启)M-x eshell 或 M-x shell)dir 中文文件夹/)或执行 chcp,查看输出是否正常无乱码process-coding-system-alist 和 default-process-coding-system 建立编码映射;chcp 65001 并修改注册表,可永久统一控制台编码,彻底根治乱码。