简体   繁体   English

如何在类似 Unix 的 Visual Studio Code 中的所有文件中制作所有行结尾 (EOL)?

[英]How can I make all line endings (EOLs) in all files in Visual Studio Code, Unix-like?

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.我使用Windows 10 Home ,我通常使用 Visual Studio Code (VS Code) 编辑 Linux Bash 脚本以及 PHP 和 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).我没有开发任何专用于 Windows 的东西,我不介意我编辑的所有文件的默认 EOL 都是 Unix 之类的 (nix)。

How could I ensure that all EOLs, in all files whatsoever (from whatever file extension), are nix, in Visual Studio Code?我如何确保所有文件中的所有 EOL(来自任何文件扩展名)在 Visual Studio Code 中都是 nix?


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).在我用 Visual Studio Code 在 Windows 中编写了一些 Bash 脚本后,我问了这个问题,将它们作为项目的一部分上传到 GitHub,一位审查该项目的高级程序员告诉我,我在那里有Windows EOL ,还有BOM问题如果我将那里的 EOL 更改为 nix(或者至少我是这么理解的),我可以解决这个问题。


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.因为我所有的开发都是面向 Linux 的,所以我希望默认情况下,我编辑的任何文件都有 nix EOL,即使它是唯一的 Windows。

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.接受的答案解释了如何对所有文件执行此操作(在设置中使用 files.eol),但是如果您需要覆盖该设置,则右下角有一个指示符,您可以单击并更改此文件。 Took me a while to notice that this was clickable.我花了一段时间才注意到这是可点击的。

在右下角的消息栏中查看 CRLF

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.这是在提交639a3cb时添加的,因此您显然需要在该提交之后使用一个版本。

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 .注意:即使文件中有单个CRLF ,上述设置也将被忽略,整个文件将被转换为CRLF You first need to convert all CRLF into LF before you can open it in Visual Studio Code.您首先需要将所有CRLF转换为LF然后才能在 Visual Studio Code 中打开它。

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

I searched for a simple solution for days and didn't have any success after I found some Git commands that changed all files from CRLF to LF .在发现一些将所有文件从CRLF更改为LF Git 命令后,我搜索了几天的简单解决方案并没有取得任何成功。

As pointed out by Mats , make sure to commit changes before executing the following commands.正如Mats指出的,确保在执行以下命令之前提交更改。

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

You can find the option in Visual Studio Code settings.您可以在 Visual Studio Code 设置中找到该选项。 It's under "Text Editor"→"Files"→"Eol".它在“文本编辑器”→“文件”→“Eol”下。 Here you can select whether you want \\n or \\r\\n or auto.您可以在此处选择是否需要 \\n 或 \\r\\n 或自动。

在此处输入图片说明

To convert the line ending for existing files转换现有文件的行尾

We can use dos2unix in WSL or in your Shell terminal.我们可以在WSL或您的 Shell 终端中使用dos2unix

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

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.我想将工作区中的所有换行符从 CRLF 批量转换为 LF。

I made a simple extension to do it我做了一个简单的扩展来做到这一点

https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.keyoti-changeallendoflinesequence 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");

            }
        }

    });

}

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”设置的人来说,Visual Studio Code 可以更改每个文件的行尾。

"Files.eol": "\n"   // Unix
"Files.eol": "\r\n" // Windows

I've just faced the same issue on my Windows machine.我刚刚在我的 Windows 机器上遇到了同样的问题。 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).每次我打开一个文件时,它都会将 EOL 设置为CRLF (即使我按照人们的建议明确设置了lf的配置)。 It appeared, that the problem is that I cloned my repository with the wrong Git configuration .看来,问题是我用错误的 Git 配置克隆了我的存储库。 It was CRLF by default.默认是CRLF Anyway, here's what I did and it worked perfectly.无论如何,这就是我所做的,并且效果很好。 No more CRLF in my workspace.我的工作区中不再有CRLF

  1. Set up your Git configuration to lf with the command git config --global core.autocrlf false使用命令git config --global core.autocrlf false将您的 Git 配置设置为lf
  2. Now clone your project again: git clone ...现在再次克隆您的项目: git clone ...
  3. Set up your Visual Studio Code instance, menu FilePreferencesSettingsFiles : Eol to "\\n".设置您的 Visual Studio Code 实例,菜单FilePreferencesSettingsFiles : Eol到“\\n”。
  4. Open the project, and everything should be as expected打开项目,一切都应该如你所愿

Uninstall typescript卸载 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尝试克隆并重新运行项目

First, ensure the line endings settings on your vscode is set to crlf .首先,确保您的 vscode 上的行尾设置设置为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.如果您希望将其作为全局设置,请按ctr+shift+p并键入user settings json和 select 第一个选项以打开全局设置文件。 If you just want it on a specific project create a settings.json file inside a .vscode folder at the base of your project.如果您只想在特定项目上使用它,请在项目底部的.vscode文件夹中创建一个settings.json文件。 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.每次拉动后或启动 vscode 后,更改仍会显示。 Just running a git add.只是运行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.要解决这个问题,您需要在项目的基础上有一个 .editorconfig 文件。 In it, you can add:在其中,您可以添加:

   [*]
   ...
   end_of_line = crlf

My original post我的原帖

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以在命令行上用Windows行尾替换Unix行尾吗? - Can I replace Unix line endings with Windows line endings on the commandline? 如何配置Compass在Windows上使用Unix行结尾生成文件? - How to configure Compass to generate files with Unix line endings on Windows? R:使用cat()获取类似Unix的linebreak LF写入文件 - R: Getting Unix-like linebreak LF writing files with cat() 如何在PowerShell中将参数传递给类似Unix的命令(通过MinGW) - How to pass arguments to Unix-like commands (via MinGW) in PowerShell Windows命令行:如何在没有位置的情况下列出所有文件夹中的所有文件只是文件列表 - Windows Command line: how can I list all files in all folders without the location just a list of files 适用于Windows的便携式unix环境 - Portable unix-like environment for Windows 如何识别大量文件的行尾 - How to identify line endings on a large number of files 在OS X上运行时,如何提交带有LF行结尾的文件,但将某些文件类型保留在CRLF中? - How can I commit files with LF line endings, but keep certain file types in CRLF when running on OS X? 如何从Unix编写DOS行结尾到文件 - How to write DOS line endings to a file from Unix 如何控制Lua DOS &lt;==&gt; Unix输出的行尾 - How to control line endings output by lua DOS<==>Unix
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM