Why does Emacs insert ^m at the end of every line in my Linux environment?
Q: Why does emacs show ^M in a buffer?
A: The “^M” is ASCII caret notation for unprintable Carriage return char (ASCII 13). If emacs shows that, it's probably because you have mixed characters of ^M and ^J and emacs cannot interpret them consistently as newlines.
To fix it, call “set-buffer-file-coding-system”, then give one of: “mac”, “dos”, “unix”. Then, save the file. If that does not fix it, you can use find and replace to remove it manually.
I know that this question has been resolved, but I wanted to mention that Dos2Unix is a handy part of a toolkit for file operation between UNIX/DOS/Mac machines. It is an easy command-based approach for adding/removing OS-preferred line endings.
I know it´s an old question, but for the record, there are other reasons why ^M appears at the end of files. I just had the same problem. Here is what happened:
- Every day I use the same text file on Emacs and never saw ^M. I use this file to take personal notes.
- Last time I used the file I copied and pasted the contents of an e-mail I got on MS Outlook.
- Today I opened the same old file and every single line had a ^M at the end, and all non-ASCII characters were replaced by strange codes like ???.
How to fix it:
Open the same file on VI (yes, I know, the archenemy) and search for characters that appear in a highlight color. On my terminal it is blue. Remove those characters and everything will work fine again on Emacs.
The problem was caused by some strange quotation mark characters that came from Outlook. The funny thing is that Emacs does not show this problem until you reopen the file, making it hard for you to identify that your file has a problem right away.
If you are using Emacs in a primarily DOS/Windows environment, Emacs should correctly recognize the line-ending system and deal with it transparently.
You might see ^M suddenly appear in a file because it has been edited, perhaps with a script, that added lines with UNIX line-endings, and now lline endings are mixed.
You can fix these lines by adding ^M back onto them, save the file, kill the buffer, and re-open it. Now it should look normal, and say (DOS) as the encoding marking on the status line.
The regexp to look for is \([^^M]\)$ and replace with \1^M. Remember to use Ctrl-Q to 'quote' the Ctrl-M characters.