How can I make all line endings (EOLs) in all files in Visual Studio Code, Unix-like?
Asked Answered
S

13

142

I use Windows 10 Home and I usually use Visual Studio Code (VS Code) to edit Linux Bash scripts as well as PHP and JavaScript.

I don't develop anything dedicated for Windows and I wouldn't mind that the default EOLs for all files I edit whatsoever would be Unix like (nix).

How could I ensure that all EOLs, in all files whatsoever (from whatever file extension), are nix, in Visual Studio Code?


I ask this question after I've written a few Bash scripts in Windows with Visual Studio Code, uploaded them to GitHub as part of a project, and a senior programmer that reviewed the project told me I have Windows EOLs there and also a BOM problem that I could solve if I'll change the EOLs there to be nix (or that's what I understood, at least).


Because all my development is Linux-oriented, I would prefer that by default, any file I edit would have nix EOLs, even if it's Windows unique.

Safeguard answered 8/2, 2018 at 18:49 Comment(0)
S
88

In your project preferences, add/edit the following configuration option:

"files.eol": "\n"

This was added as of commit 639a3cb, so you would obviously need to be using a version after that commit.

Note: Even if you have a single CRLF in the file, the above setting will be ignored and the whole file will be converted to CRLF. You first need to convert all CRLF into LF before you can open it in Visual Studio Code.

See also: https://github.com/Microsoft/vscode/issues/2957

Snigger answered 8/2, 2018 at 19:5 Comment(3)
this method does not convert ALL FILES but single fileSurfactant
I think there is no vscode-all-files-eol-unix-like-solution.Caustic
Also for me this doesn't work on git projects shared with linux envoronments. What I sometimes use is find . -not -path '*/.*' -type f \( -iname \*Dockerfile* -o -iname \*.sh \) -exec sed -i 's/\r//' {} \; in addition to git config core.eol native and git config core.autocrlf true. More here https://mcmap.net/q/11220/-force-lf-eol-in-git-repo-and-working-copyWarsle
C
170

The accepted answer explains how to do this for all files (use files.eol in settings), but if you ever need to override that setting there's an indicator at the bottom right that you can click on and change for this one file. Took me a while to notice that this was clickable.

See CRLF in the message bar at the bottom right

Clarenceclarenceux answered 8/2, 2018 at 20:36 Comment(4)
This only sets the current file. The question was how to set it for all files.Stonehenge
I upvoted the accepted answer, which does directly answer the question The intent of this answer was to point out that if you have an exception to the default there is an easy mechanism to change the file endings for just one file. It must be helpful to at least some people (probably new to vscode) and they upvote? I guess it would be better as a comment to the accepted answer?Clarenceclarenceux
The image of Ian could be misleading, you have to change it to lf that is line feed.Caustic
Alternatively execute Change End Of Line Sequence command in Show All Commands list (ctrl+shift+p).Yale
P
140

I searched for a simple solution for days and didn't have any success until I found some Git commands that changed all files from CRLF to LF.

As pointed out by Mats, make sure to commit changes before executing the following commands.

In the root folder type the following.

git config core.autocrlf false

git rm --cached -r .         # Don’t forget the dot at the end

git reset --hard
Photostat answered 8/1, 2021 at 12:9 Comment(8)
Make sure to commit any changes before running this! :)Heroine
If only I had seen this comment earlier.Shenyang
You can express that by giving an upvote :DPhotostat
omg @Photostat I have been using git config core.autocrlf false so many times but it didn't work. And after following your 3 steps, my VSCode plays so wellGolem
Our cc-wiki licensing, while intentionally permissive, does require attribution. ~ * ~ Don't violate Stack Overflow's legal terms! ~ * ~ You could for example write : I searched for a simple solution for days and didn't have any success until I found some Git commands that changed all files from CRLF to LF. ~ * ~ The inclusion of that link is all it takes to save you from criticism. (I already did this for you. This comment explains why.)Bibliogony
@Henke what if I found the solution on some other site and just wanted to help whoever is searching for the right answer like me? If there is an answer already available on StackOverflow that doesn't mean I took it from there. I just wrote what helped me there is no need to waste mine and yours timePhotostat
Please read: How to reference material written by others. Your answer was well received. – Be happy about it! :-) But why would you ever want to deliberately violate Stack Overflow's legal terms?? You are allowed to copy-paste a solution from anywhere on the Internet. You are not allowed to do so without attributing to that other source. ~ * ~ I suggest you edit your answer to include the actual source you used.Bibliogony
For anyone (possibly including my future self) who wants a hint on the source of this answer's three suggested commands, and/or understand what they do, here are some links. Git: Dealing with line endings – solution. . What git rm --cached -r . does. . Docs of git rm --cached -r .. . The other (identical) SO-answer.Bibliogony
S
88

In your project preferences, add/edit the following configuration option:

"files.eol": "\n"

This was added as of commit 639a3cb, so you would obviously need to be using a version after that commit.

Note: Even if you have a single CRLF in the file, the above setting will be ignored and the whole file will be converted to CRLF. You first need to convert all CRLF into LF before you can open it in Visual Studio Code.

See also: https://github.com/Microsoft/vscode/issues/2957

Snigger answered 8/2, 2018 at 19:5 Comment(3)
this method does not convert ALL FILES but single fileSurfactant
I think there is no vscode-all-files-eol-unix-like-solution.Caustic
Also for me this doesn't work on git projects shared with linux envoronments. What I sometimes use is find . -not -path '*/.*' -type f \( -iname \*Dockerfile* -o -iname \*.sh \) -exec sed -i 's/\r//' {} \; in addition to git config core.eol native and git config core.autocrlf true. More here https://mcmap.net/q/11220/-force-lf-eol-in-git-repo-and-working-copyWarsle
E
30

To convert the line ending for existing files

WSL

We can use dos2unix in WSL or in your Shell terminal.

Install the tool:

sudo apt install dos2unix

Convert line endings in the current directory:

find -type f -print0 | xargs -0 dos2unix

If there are some folders that you'd want to exclude from the conversion, use:

find -type f \
     -not -path "./<dir_to_exclude>/*" \
     -not -path "./<other_dir_to_exclude>/*" \
     -print0 | xargs -0 dos2unix

Edited in 2023

Directly PowerShell 7+ (faster, multithreaded)

To install PowerShell 7 on Windows, follow the instructions here.

You will need to have Chocolatey installed, and to install dos2unix for Chocolatey.

  1. Install Chocolatey following this instructions if you don't have it already.

  2. Install dos2unix for Chocolatey

    1. Open a PowerShell terminal as Administrator

      pwsh.exe -new_console:a
      
    2. Install dos2unix

      choco install dos2unix
      
    3. Close the Administrator terminal

      exit
      

Now, we can use dos2unix from PowerShell.

# Set the parameters
$path = Get-Location
$numbOfThreads = 50
$exclude_patterns = "^.*(\.git|\.idea|node_modules|\.next|\.(jpeg|jpg|png|gif|mp4|mkv|mp3|wav)$).*$"

# Find files to convert
$files = Get-ChildItem -Path $path -Recurse -Include *.* -File -Force | Where-Object {$_.FullName -notmatch $exclude_patterns}
Write-Host "Found $($files.Count) files"

# Convert the files
$files | ForEach-Object -Parallel {
    dos2unix $_.FullName
} -ThrottleLimit $numbOfThreads

Enyo answered 4/4, 2020 at 15:37 Comment(3)
How does it handle UTF-8 with BOM encoded files?Gawain
If you want to find the modern way, try ` apt install fd-find` on debian.Caustic
Thanks! The only solution that worked on WSL for meTrod
H
29

You can find the option in Visual Studio Code settings. It's under "Text Editor"→"Files"→"Eol". Here you can select whether you want \n or \r\n or auto.

Enter image description here

Holpen answered 22/9, 2020 at 15:59 Comment(4)
One way to get to settings is menu FilePreferencesSettings. Another is Ctrl + ,.Gawain
The auto option might be real crap.Caustic
Not a solution, still the default option is CRLF for all the files even though it is set to \n in settings. What a bug in 2022. Shame on VSCode.Frias
I searched in the setteings for LF, CRLF, line break, linebreak,... and finally it's "Eol" o.OEleni
D
11

Both existing answers are helpful but not what I needed. I wanted to bulk convert all the newline characters in my workspace from CRLF to LF.

I made a simple extension to do it

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.keyoti-changeallendoflinesequence

In fact, here is the extension code for reference

'use strict';

import * as vscode from 'vscode';
import { posix } from 'path';


export function activate(context: vscode.ExtensionContext) {

    // Runs 'Change All End Of Line Sequence' on all files of specified type.
    vscode.commands.registerCommand('keyoti/changealleol', async function () {

        async function convertLineEndingsInFilesInFolder(folder: vscode.Uri, fileTypeArray: Array<string>, newEnding: string): Promise<{ count: number }> {
            let count = 0;
            for (const [name, type] of await vscode.workspace.fs.readDirectory(folder)) {

                if (type === vscode.FileType.File && fileTypeArray.filter( (el)=>{return name.endsWith(el);} ).length>0){ 
                    const filePath = posix.join(folder.path, name);

                    var doc = await vscode.workspace.openTextDocument(filePath);

                    await vscode.window.showTextDocument(doc);
                    if(vscode.window.activeTextEditor!==null){
                        await vscode.window.activeTextEditor!.edit(builder => { 
                            if(newEnding==="LF"){
                                builder.setEndOfLine(vscode.EndOfLine.LF);
                            } else {
                                builder.setEndOfLine(vscode.EndOfLine.CRLF);
                            }
                            count ++; 
                        });

                    } else {
                        vscode.window.showInformationMessage(doc.uri.toString());
                    }
                }

                if (type === vscode.FileType.Directory && !name.startsWith(".")){
                    count += (await convertLineEndingsInFilesInFolder(vscode.Uri.file(posix.join(folder.path, name)), fileTypeArray, newEnding)).count;
                }
            }
            return { count };
        }

        let options: vscode.InputBoxOptions = {prompt: "File types to convert", placeHolder: ".cs, .txt", ignoreFocusOut: true};
        let fileTypes = await vscode.window.showInputBox(options);
        fileTypes = fileTypes!.replace(' ', '');
        let fileTypeArray: Array<string> = [];

        let newEnding = await vscode.window.showQuickPick(["LF", "CRLF"]);

        if(fileTypes!==null && newEnding!=null){
            fileTypeArray = fileTypes!.split(',');

            if(vscode.workspace.workspaceFolders!==null && vscode.workspace.workspaceFolders!.length>0){
                const folderUri = vscode.workspace.workspaceFolders![0].uri;
                const info = await convertLineEndingsInFilesInFolder(folderUri, fileTypeArray, newEnding);
                vscode.window.showInformationMessage(info.count+" files converted");

            }
        }

    });

}
Denti answered 12/3, 2020 at 16:36 Comment(2)
I want to run it for specific folder and for that I am trying to edit the code, But I do I run it. Can you give some light on it?Th
@SiddharthChoudhary The code is a VS Code extension, so to run it you have to have it in an extension. Good news is that you can get the extension from github.com/keyoti/VSCode-ChangeAllEOL - I believe you can just clone that to your machine, open it in VS Code and then press F5. It will open a test instance of VS Code and you can see your version of the extension working. More info code.visualstudio.com/api/get-started/your-first-extensionDenti
H
8

I've just faced the same issue on my Windows machine. Every time I opened a file it would set the EOL to CRLF (even though I explicitly set up a configuration for lf as people suggested). It appeared, that the problem is that I cloned my repository with the wrong Git configuration. It was CRLF by default. Anyway, here's what I did and it worked perfectly. No more CRLF in my workspace.

  1. Set up your Git configuration to lf with the command git config --global core.autocrlf false
  2. Now clone your project again: git clone ...
  3. Set up your Visual Studio Code instance, menu FilePreferencesSettingsFiles: Eol to "\n".
  4. Open the project, and everything should be as expected
Hirza answered 13/5, 2021 at 10:14 Comment(0)
K
7

For other people asking you can use the "Files.eol" setting is Visual Studio Code to change the line ending for every file.

"Files.eol": "\n"   // Unix
"Files.eol": "\r\n" // Windows
Koren answered 23/6, 2020 at 8:54 Comment(1)
VSCode for me required lower-case "files.eol". Try: CTRL+SHIFT+P -> Preferences: Open User Settings (JSON) -> Add line "files.eol": "\r\n"Franconia
S
5

I know this is late to the game but I was recently looking for a simple method without having to install anything else to my system.

If you have Git for windows installed then just open a Git Bash window in the desired folder and run dos2unix which appears to be bundled by default:

find . -name "*.filetype" -exec dos2unix {} \;

and it will convert all your endings to LF for you. It also ignores binary files if you get lazy and try and just use -name "*"

It helped me, hopefully helps others

Symptomatic answered 21/7, 2023 at 12:31 Comment(0)
R
1

Uninstall typescript

run

npm install -g typescript
git config --global core.autocrlf false

check

git config --global core.autocrlf 

if it shows false. try to clone and re-run the project

Romero answered 1/3, 2022 at 16:18 Comment(0)
C
1

First, ensure the line endings settings on your vscode is set to crlf. If you want this as a global setting press ctr+shift+p and type user settings json and select the first option to open the global settings file. If you just want it on a specific project create a settings.json file inside a .vscode folder at the base of your project. Then add this line there.

    ...
    "files.eol": "\r\n"

This doesn't solve the problem though. after every pull or after launching vscode the changes still show up. Just running a git add . will show no more changes which I think is what is desired but you don't want to do this every time.

To solve this, you need a .editorconfig file at the base of your project. In it, you can add:

   [*]
   ...
   end_of_line = crlf

My original post

Cud answered 31/12, 2022 at 7:58 Comment(0)
B
0

If you are using Prettier in your frontend project - add this to your .prettierrc config:

"endOfLine": "crlf",

Then simply run:

prettier --write
Boschvark answered 6/11, 2023 at 12:7 Comment(0)
W
0
git config core.autocrlf false

git rm --cached -r .         # Don’t forget the dot at the end

git reset --hard

Running these commands will work, Please commit all your changes

Wend answered 2/4 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.