67

Is there a way to tell GNU Emacs to convert DOS/Windows newline characters in a file to Unix format?

Charo
  • 865
  • 1
  • 9
  • 11

2 Answers2

84

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` – CodyChan Jul 03 '18 at 10:36
  • @CodyChan `C-x RET f` is the default binding for `set-buffer-file-coding-system`. – Gilles 'SO- stop being evil' Jul 03 '18 at 10:40
  • I bound a function to `C-x C-m`, and currently I'm using Emacs in terminal remotely, when I execute `C-x RET` in Emacs, it says it is bound to the function I bound to `C-x C-m`, I think `M-x ` suits to everyone. – CodyChan Jul 04 '18 at 03: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 that `RET` is the same thing as `C-m`, which is what the Return key sends on a terminal — a binding that only applied to the Return key in a GUI would use `return`. – Gilles 'SO- stop being evil' Jul 04 '18 at 06:38
  • 1
    If 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'. – Digicrat Mar 08 '20 at 20:04
6

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.

Nsukami _
  • 6,341
  • 2
  • 22
  • 35