Recently I’ve been noticing some of my C# files have inconsistent line endings.
The Problem
The line endings in the following file are not consistent. Do you want to normalize the line endings?
This probably means some of the developers have been editing our source code using a text-editor (instead of Visual Studio) and they had their line endings set to “Unix” or “Mac” instead of “Dos/Windows”. This isn’t a big deal, though it is annoying.
Vim: Convert All Files to Dos/Windows Line Endings
Since I don’t know which files have this problem, I decided to just normalize all the line endings. There are various ways to do this, but I chose to use vim since the documentation on this topic is excellent.
To convert from any mixture of CRLF endings and LF-only endings, to CRLF endings:
:set ffs=dos :args **\*.cs :argdo w
We’re basically asking vim to assume Dos/Windows line endings, having it open all *.cs files (C# code files), then having it write the line-ending changes.
Downsides
This does change every single file that was found, regardless of the original line endings. It’s best to do this as one commit in source control to avoid any confusion.
Alternatives
You can also use unix2dos to do this conversion or any scripting language (python, perl, powershell).
Some people also let their source control handle their line endings. Git can enforce these line endings by updating them for you if you prefer. However, at my office, we choose not to let our source control alter our code in any way; we prefer to do that ourselves.
Now get back to coding!