LF VS CRLF

Introduction

A few days ago, I submitted a change list, and to my surprise, the Gerrit code review website showed that every line in a file was different from its base version, even if I had only modified a few lines of code. It turns out that somehow the line endings of the file were changed from LF to CRLF, which is something I have never been aware of before. In this blog post, I will discuss the difference between LF and CRLF and how to handle them in VS Code.

LF VS CRLF

LF stands for Line Feed, which is the Unix-style line ending, while CRLF stands for Carriage Return Line Feed, which is the Windows-style line ending. The difference between LF and CRLF is that LF only moves the cursor to the next line, while CRLF moves the cursor to the beginning of the next line. In other words, LF is a single character \n, while CRLF consists of two characters \r\n.

If a file was changed from LF to CRLF, or vice versa, every line in the file will be different from its base version, even though the content of the file is the same. The Gerrit code review website or git diff will show that every line in the file was changed, and the diff will be very noisy.

For example, suppose we have a file lf.cpp with LF line endings and a file crlf.cpp that has exactly the same content but with CRLF line endings. The diff between the two files will be as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ git diff lf.cpp crlf.cpp
diff --git a/lf.cpp b/crlf.cpp
index 5f42c42..a5b3b68 100644
--- a/lf.cpp
+++ b/crlf.cpp
@@ -1,5 +1,5 @@
-// This is line 1.
-// This is line 2.
-// This is line 3.
-// This is line 4.
+// This is line 1.^M
+// This is line 2.^M
+// This is line 3.^M
+// This is line 4.^M
// This is line 5.
\ No newline at end of file

LF VS CRLF In VS Code

It turns out that the line endings of a file can be changed very easily in VS Code via a few button clicks. To change the line endings of a file in VS Code, click on the “LF” or “CRLF” button at the bottom right corner of the VS Code window, and select the desired line ending.

VS Code LF and CRLF Toggle

Viewing the changes of file from using the LF line endings to CRLF line endings, or vice versa, in the VS Code source control can be very confusing. Despite that every line in the file was changed, VS Code source control will only show the file was modified, but no content was changed at all. If we have committed and pushed the changes to the remote repository, the Gerrit code review website will show that every line in the file was changed. Fixing this, fortunately, is also very easy. We can just click on the “LF” or “CRLF” button at the bottom right corner of the VS Code window, and select the correct line ending.

Author

Lei Mao

Posted on

04-18-2025

Updated on

04-18-2025

Licensed under


Comments