Emacs: Newline Convention
Newline Character in Emacs Buffer
in emacs buffer, newline character is always
Line Feed (ASCII 10, "\n"),
on any Windows, Mac, Linux.
to insert it literally, see Emacs: Insert Tab or Newline
File Newline Convention in Windows, Mac, Linux
Different operating systems use different characters for newline (aka end-of-line char, eol char), and or use a combination of them to represent a single newline.
Newline is indicated by 1 or 2 control characters.
| Operating System | Newline Convention |
|---|---|
| Unix, Linux, Mac OS X | LF |
| Windows | CR LF (2 characters) |
| Mac OS Classic (dated before 2002) | CR |
Note:
Mac OS X prefers LF, but accept the Mac OS Classic's CR too.
ASCII Characters for Newline
The following characters are used for newline.
| Name | Abbrev | Decimal Codepoint | Escape Notation | Caret Notation | Emacs Input method |
|---|---|---|---|---|---|
| Line Feed | LF | 10 | \n | ^J | Ctrl+q Ctrl+j |
| Carriage Return | CR | 13 | \r | ^M | Ctrl+q Ctrl+m |
Why is emacs showing ^M
If emacs displays many ^M (CR, codepoint 13) that probably means there's inconsistent line ending in the file.
Find out what char is ^M ^J ^L
How to delete ^M
- Goto beginning of the file, then Alt+x
query-replace, then insert the Carriage Return char by Ctrl+q Ctrl+m for the find string. For replacement string just press Enter for empty string. - Alt+x
set-buffer-file-coding-system, then type one of: {mac, dos, unix}. Then, save the file.
Automatically Add Newline at End of File
- require-final-newline
-
Variable.
Whether to add a newline automatically at the end of the file.
tmeans do this only when the file is about to be saved.'visitmeans do this right after the file is visited.'visit-savemeans do it at both of those times.- Any other true value means ask user whether to add a newline, when saving.
nilmeans don't add newlines.
- mode-require-final-newline
-
Variable.
same as require-final-newline, but used by some Major Mode
💡 TIP: some system tool or protocols expect a newline at the end of file.
🛑 WARNING: Do not manually do find replace to change newline character in a buffer, because after you save the file, a unexpected newline character may be quietly added because of require-final-newline.
Thanks to Stefan Monnier 〔http://www.iro.umontreal.ca/~monnier/〕 for a major tip on this newline issue in emacs.
Emacs Line Ending
ASCII Character Set Problems
- ASCII Characters
- Unicode: ASCII Control Characters ␀
- Why You Need to Understand ASCII (2024)
- Programing Language: ASCII Char Jam vs Unicode (2011)
- Emacs Lisp Doc String Curly Quote Controversy (2015)
- Linux: Terminal Control Sequence Keys
- Stack Overflow offline page 2011-08-06
- Emacs: Newline Convention
- Emacs Key Notations Explained (/r, ^M, C-m, RET, <return>, M-, meta)