Is there a way to tell GNU Emacs to convert DOS/Windows newline characters in a file to Unix format?
2 Answers
If the mode line shows a (DOS)
indicator, click on it twice to cycle to :
meaning Unix newlines and then save the file.
If you can't click on the mode line or prefer a keyboard-based solution, run the command C-x RET f
(set-buffer-file-coding-system
) and type unix
. This will change the encoding of newlines without changing the encoding of other characters. (You can also change the encoding of other characters by typing something like utf-8-unix
.)
-
1
C-x RET f (set-buffer-file-coding-system)
-->M-x set-buffer-file-coding-system RET
– CodyChanJul 3, 2018 at 10:36 -
@CodyChan
C-x RET f
is the default binding forset-buffer-file-coding-system
. Jul 3, 2018 at 10:40 -
I bound a function to
C-x C-m
, and currently I'm using Emacs in terminal remotely, when I executeC-x RET
in Emacs, it says it is bound to the function I bound toC-x C-m
, I thinkM-x
suits to everyone.– CodyChanJul 4, 2018 at 3:17 -
2@CodyChan I give the default bindings (like the Emacs documentation) because it's useful to most readers. Obviously, if you've changed the default bindings, you can't use the default bindings. You can use
M-x
with the function name which is indicated in parentheses, there's no point in repeating it. Do note thatRET
is the same thing asC-m
, which is what the Return key sends on a terminal — a binding that only applied to the Return key in a GUI would usereturn
. Jul 4, 2018 at 6:38 -
1If you're like me and want to use the habitual dos2unix command without remembering a new keyboard shortcut, I defined an alias so I can simply type "M-x dos2unix" as "(defun dos2unix() (interactive) (set-buffer-file-coding-system 'utf-8-unix)". For unix2dos, subsitute the type for 'dos'.– DigicratMar 8, 2020 at 20:04
Save the file, and Emacs will automatically use the correct newline char when writing the buffer to file, according to the value of buffer-file-coding-system
.
To know what is the value of buffer-file-coding-system, call describe-variable
then buffer-file-coding-system
, or run the describe-coding-system
command which you can do by clicking the second character of the mode line or pressing C-h C
. To set its value, call set-buffer-file-coding-system
(C-x RET f
) and tab to choose the one you want.
:
.(DOS)
.