Home About Archive RSS

Fix text encoding and line endings in Emacs on Windows

Windows uses different text encodings based on locale while POSIX-compliant OSes like GNU/Linux, MacOS or *BSD use UTF-8. Windows also uses its own line endings (CRLF). By default, Emacs on Windows uses ISO-8859-1 (ISO-Latin) and CRLF (Windows line endings). Since I push and pull files between different machines with git and most of those machines run GNU/Linux, I need files created on Windows to not use its own text encoding and line endings. Below are the settings I have found to force Emacs to use UTF-8 with Unix (LF) line endings.

(prefer-coding-system 'utf-8-unix)
(set-default-coding-systems 'utf-8-unix)
(set-language-environment 'utf-8)
(set-selection-coding-system 'utf-8-unix)
(setq-default coding-system-for-write 'utf-8-unix)
(setq-default buffer-file-coding-system 'utf-8-unix)

In addition to these settings within Emacs, since I use git, I don't want it to convert line endings in files I pull down with it from LF to CRLF on Windows, which it does by default when used on Windows. To change this behaviour I also had to run git config --global core.autocrlf false in PowerShell. I tried the per-system way first with --system, but that did not work, not even after granting myself administrator rights. But the per-user global setting you see above worked.

Even after making these settings to Emacs, when I interact with files through Powershell in Shell mode in Emacs, file names outside the ASCII range are garbled. Even if the settings above sets Emacs to use UTF-8, PowerShell uses the UTF-16 text encoding. Since it is unavoidable for me when I make teaching materials in Norwegian Bokmål to use letters outside the ASCII range, this is rather annoying.

There is a Beta feature in Windows 11 to switch to UTF-8 as the default text encoding system for the whole OS. I did not dare to try this, especially since my machine is managed through my organisation, but I hope Microsoft will improve the lives of Windows users, especially developers, sysopers and (cloud) admins by getting this feature out of Beta in the not too distant future.



Copyright 2010 - 2025 Einar Mostad. All content is shared under the terms of the Creative Commons Attribution-ShareAlike license.