Issues with Line Endings (^M in Git Diff)

Every once in a while, when I run git diff on a file, I see something like the following:

I've made a couple changes to some code that was inherited and all the sudden there are a bunch of ^Ms littered everywhere.

This is a result of confused line endings between operating systems and fortunately, it's a quick fix. Each operating system has a particular way of denoting where a line ends:

  • Unix/Linux/OS X use \n or LF (line feed)
  • Windows uses \r\n or CRLF (carriage return, line feed)
  • Legacy Mac uses \r or CR (carriage return)

For me, the problem usually means that the previous developer was using a Windows machine, so none of the line endings match. Instead of updating the file to match Unix's \n, Vim simply conforms to the existing file format, which causes those ^Ms at the end of every line.

To fix this, convert the file format to unix with:

:set ff=unix

If you're using IntelliJ, follow the steps on the JetBrains website to solve the same problem.