Emacs: Newline Convention

By Xah Lee. Date: . Last updated: .

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
Operating SystemNewline Convention
Unix, Linux, Mac OS XLF
WindowsCRLF (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.

Control Characters for Newline
NameAbbrevDecimal
Codepoint
Escape
Notation
Caret
Notation
Emacs Input method
Line FeedLF10\n^JCtrl+q Ctrl+j
Carriage ReturnCR13\r^MCtrl+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

  1. 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.
  2. 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.

  • t means do this only when the file is about to be saved.
  • 'visit means do this right after the file is visited.
  • 'visit-save means do it at both of those times.
  • Any other true value means ask user whether to add a newline, when saving.
  • nil means 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