格式化 - 立即 - Visual Studio项目中的所有文件

时间:2023-01-06 11:15:39

I am interested in formatting all the files in a Visual Studio (ver. 2005) project all at once.

我有兴趣一次性格式化Visual Studio(版本2005)项目中的所有文件。

Currently, there is a way to format a single document by doing something like Edit->Advanced->Format Document. However, I don't see a single command to format all the files of a project all at once.

目前,有一种方法可以通过执行Edit-> Advanced-> Format Document等操作来格式化单个文档。但是,我没有看到一个命令来同时格式化项目的所有文件。

Any idea how to do that?

知道怎么做吗?

4 个解决方案

#1


Tim Abell wrote a macro to do this on his blog:

蒂姆阿贝尔在他的博客上写了一个宏来做到这一点:

Here's a handy macro script for visual studio I knocked together today. It runs "edit, format document" on every document of the listed file types.

这是我今天碰到的视觉工作室的一个方便的宏脚本。它在列出的文件类型的每个文档上运行“编辑,格式化文档”。

You have to keep an eye on it as it's interactive and does sometimes pop up a message and wait for an answer.

您必须密切关注它,因为它是交互式的,有时会弹出消息并等待答案。

You can get the vb file at http://github.com/timabell/vs-formatter-macro More info at http://wiki.github.com/timabell/vs-formatter-macro

您可以访问http://github.com/timabell/vs-formatter-macro获取vb文件。更多信息请访问http://wiki.github.com/timabell/vs-formatter-macro

The original code is available at the blog post. Note that this is older than the version available on github above.

原始代码可在博客文章中找到。请注意,这比上面的github上提供的版本旧。

#2


The Format All Files extension worked for me. Nothing to do, just install and click!

Format All Files扩展程序适用于我。无所事事,只需安装并点击即可!

#3


Note, that the following solution does not work by itself starting with Visual Studio 2015. You need to apply the answer by Marcus Mangelsdorf as well. Then, this script works in Visual Studio 2015 and 2017.

请注意,从Visual Studio 2015开始,以下解决方案本身不起作用。您还需要应用Marcus Mangelsdorf的答案。然后,此脚本适用于Visual Studio 2015和2017。


Phil Haack outlined a good procedure - adding a reusable script to indent the project.

Phil Haack概述了一个很好的程序 - 添加一个可重复使用的脚本来缩进项目。

Open your NuGet profile for edition

  1. Open the Package Manager;
  2. 打开包管理器;

  3. Type $profile to see the location of your NuGet profile;
  4. 输入$ profile以查看NuGet个人资料的位置;

  5. Type mkdir –force (split-path $profile) to create the profile's folder if it does not exist;
  6. 键入mkdir -force(split-path $ profile)以创建配置文件的文件夹(如果它不存在);

  7. Edit the profile with the command notepad $profile.
  8. 使用命令notepad $ profile编辑配置文件。

Add the reusable method to the NuGet profile

Phil used davidfowl's Format-Document method which he found at https://gist.github.com/davidfowl/984358:

Phil使用davidfowl的Format-Document方法,他在https://gist.github.com/davidfowl/984358上找到了这个方法:

# Function to format all documents based on https://gist.github.com/984353
function Format-Document {
    param(
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [string[]]$ProjectName
    )
    Process {
        $ProjectName | %{ 
                        Recurse-Project -ProjectName $_ -Action { param($item)
                        if($item.Type -eq 'Folder' -or !$item.Language) {
                            return
                        }

                        $window = $item.ProjectItem.Open('{7651A701-06E5-11D1-8EBD-00A0C90F26EA}')
                        if ($window) {
                            Write-Host "Processing `"$($item.ProjectItem.Name)`""
                            [System.Threading.Thread]::Sleep(100)
                            $window.Activate()
                            $Item.ProjectItem.Document.DTE.ExecuteCommand('Edit.FormatDocument')
                            $Item.ProjectItem.Document.DTE.ExecuteCommand('Edit.RemoveAndSort')
                            $window.Close(1)
                        }
                    }
        }
    }
}

function Recurse-Project {
    param(
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [string[]]$ProjectName,
        [parameter(Mandatory = $true)]$Action
    )
    Process {
        # Convert project item guid into friendly name
        function Get-Type($kind) {
            switch($kind) {
                '{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}' { 'File' }
                '{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}' { 'Folder' }
                default { $kind }
            }
        }

        # Convert language guid to friendly name
        function Get-Language($item) {
            if(!$item.FileCodeModel) {
                return $null
            }

            $kind = $item.FileCodeModel.Language
            switch($kind) {
                '{B5E9BD34-6D3E-4B5D-925E-8A43B79820B4}' { 'C#' }
                '{B5E9BD33-6D3E-4B5D-925E-8A43B79820B4}' { 'VB' }
                default { $kind }
            }
        }

        # Walk over all project items running the action on each
        function Recurse-ProjectItems($projectItems, $action) {
            $projectItems | %{
                $obj = New-Object PSObject -Property @{
                    ProjectItem = $_
                    Type = Get-Type $_.Kind
                    Language = Get-Language $_
                }

                & $action $obj

                if($_.ProjectItems) {
                    Recurse-ProjectItems $_.ProjectItems $action
                }
            }
        }

        if($ProjectName) {
            $p = Get-Project $ProjectName
        }
        else {
            $p = Get-Project
        }

        $p | %{ Recurse-ProjectItems $_.ProjectItems $Action } 
    }
}

# Statement completion for project names
Register-TabExpansion 'Recurse-Project' @{
    ProjectName = { Get-Project -All | Select -ExpandProperty Name }
}

Reopen Visual Studio to use the command

When you reopen Visual Studio, the command is available.

重新打开Visual Studio时,该命令可用。

Simply run it from the NuGet Package Manager Console: Format-Document This will re-format all files of the selected project.
To apply to the whole solution, use the command Get-Project -All | Format-Document, which lists the projects and then for each of them calls the reformatting command.

只需从NuGet包管理器控制台运行它:Format-Document这将重新格式化所选项目的所有文件。要应用于整个解决方案,请使用命令Get-Project -All | Format-Document,列出项目,然后为每个项目调用重新格式化命令。

As the author put it:

正如作者所说:

With this in place, you can now indulge your OCD and run the Format-Document command to clean up your entire solution. I just ran it against <Project> and now can become the whitespace Nazi I’ve always wanted to be.

有了这个,您现在可以放纵您的OCD并运行Format-Document命令来清理整个解决方案。我只是针对 运行它,现在可以成为我一直想成为的空白纳粹。

10/10, would run again.

10/10,会再次运行。

#4


Additional step needed for Visual Studio 2015

Phil Haack's solution posted by ANeves is perfect, but for some reason $item.FileCodeModel.Language always returns null in Visual Studio 2015 making the Format-Document skip all files and effectively do nothing.

由ANeves发布的Phil Haack的解决方案是完美的,但由于某种原因$ item.FileCodeModel.Language在Visual Studio 2015中始终返回null,使得Format-Document跳过所有文件并且实际上什么都不做。

To (hackily) work around this limitation you can replace the Get-Language function:

要(hackily)解决此限制,您可以替换Get-Language函数:

# Convert language guid to friendly name
function Get-Language($item) {
    if(!$item.FileCodeModel) {
        return $null
    }

    $kind = $item.FileCodeModel.Language
    switch($kind) {
        '{B5E9BD34-6D3E-4B5D-925E-8A43B79820B4}' { 'C#' }
        '{B5E9BD33-6D3E-4B5D-925E-8A43B79820B4}' { 'VB' }
        default { $kind }
    }
}

with the following variant that uses the file's extension instead of the Language GUID:

使用以下使用文件扩展名而不是语言GUID的变体:

# Convert file extension to friendly language name
function Get-Language($item) {
   if(!$item.FileCodeModel) {
       return $null
   }

   $filename = $item.Name
   $ext = $filename.substring($filename.lastindexof('.'),
                              ($filename.length - $filename.lastindexof('.')))
   switch($ext) {
       '.cs' { 'C#' }
       '.vb' { 'VB' }
       # If you want to prevent re-formatting files that are not VB or C# source files 
       # (e.g. XML files in your project etc.), replace the following line with 
       # "default { $null }" (thanks to HHenn for this suggestion!)
       default { $ext }
   }            
}

#1


Tim Abell wrote a macro to do this on his blog:

蒂姆阿贝尔在他的博客上写了一个宏来做到这一点:

Here's a handy macro script for visual studio I knocked together today. It runs "edit, format document" on every document of the listed file types.

这是我今天碰到的视觉工作室的一个方便的宏脚本。它在列出的文件类型的每个文档上运行“编辑,格式化文档”。

You have to keep an eye on it as it's interactive and does sometimes pop up a message and wait for an answer.

您必须密切关注它,因为它是交互式的,有时会弹出消息并等待答案。

You can get the vb file at http://github.com/timabell/vs-formatter-macro More info at http://wiki.github.com/timabell/vs-formatter-macro

您可以访问http://github.com/timabell/vs-formatter-macro获取vb文件。更多信息请访问http://wiki.github.com/timabell/vs-formatter-macro

The original code is available at the blog post. Note that this is older than the version available on github above.

原始代码可在博客文章中找到。请注意,这比上面的github上提供的版本旧。

#2


The Format All Files extension worked for me. Nothing to do, just install and click!

Format All Files扩展程序适用于我。无所事事,只需安装并点击即可!

#3


Note, that the following solution does not work by itself starting with Visual Studio 2015. You need to apply the answer by Marcus Mangelsdorf as well. Then, this script works in Visual Studio 2015 and 2017.

请注意,从Visual Studio 2015开始,以下解决方案本身不起作用。您还需要应用Marcus Mangelsdorf的答案。然后,此脚本适用于Visual Studio 2015和2017。


Phil Haack outlined a good procedure - adding a reusable script to indent the project.

Phil Haack概述了一个很好的程序 - 添加一个可重复使用的脚本来缩进项目。

Open your NuGet profile for edition

  1. Open the Package Manager;
  2. 打开包管理器;

  3. Type $profile to see the location of your NuGet profile;
  4. 输入$ profile以查看NuGet个人资料的位置;

  5. Type mkdir –force (split-path $profile) to create the profile's folder if it does not exist;
  6. 键入mkdir -force(split-path $ profile)以创建配置文件的文件夹(如果它不存在);

  7. Edit the profile with the command notepad $profile.
  8. 使用命令notepad $ profile编辑配置文件。

Add the reusable method to the NuGet profile

Phil used davidfowl's Format-Document method which he found at https://gist.github.com/davidfowl/984358:

Phil使用davidfowl的Format-Document方法,他在https://gist.github.com/davidfowl/984358上找到了这个方法:

# Function to format all documents based on https://gist.github.com/984353
function Format-Document {
    param(
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [string[]]$ProjectName
    )
    Process {
        $ProjectName | %{ 
                        Recurse-Project -ProjectName $_ -Action { param($item)
                        if($item.Type -eq 'Folder' -or !$item.Language) {
                            return
                        }

                        $window = $item.ProjectItem.Open('{7651A701-06E5-11D1-8EBD-00A0C90F26EA}')
                        if ($window) {
                            Write-Host "Processing `"$($item.ProjectItem.Name)`""
                            [System.Threading.Thread]::Sleep(100)
                            $window.Activate()
                            $Item.ProjectItem.Document.DTE.ExecuteCommand('Edit.FormatDocument')
                            $Item.ProjectItem.Document.DTE.ExecuteCommand('Edit.RemoveAndSort')
                            $window.Close(1)
                        }
                    }
        }
    }
}

function Recurse-Project {
    param(
        [parameter(ValueFromPipelineByPropertyName = $true)]
        [string[]]$ProjectName,
        [parameter(Mandatory = $true)]$Action
    )
    Process {
        # Convert project item guid into friendly name
        function Get-Type($kind) {
            switch($kind) {
                '{6BB5F8EE-4483-11D3-8BCF-00C04F8EC28C}' { 'File' }
                '{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}' { 'Folder' }
                default { $kind }
            }
        }

        # Convert language guid to friendly name
        function Get-Language($item) {
            if(!$item.FileCodeModel) {
                return $null
            }

            $kind = $item.FileCodeModel.Language
            switch($kind) {
                '{B5E9BD34-6D3E-4B5D-925E-8A43B79820B4}' { 'C#' }
                '{B5E9BD33-6D3E-4B5D-925E-8A43B79820B4}' { 'VB' }
                default { $kind }
            }
        }

        # Walk over all project items running the action on each
        function Recurse-ProjectItems($projectItems, $action) {
            $projectItems | %{
                $obj = New-Object PSObject -Property @{
                    ProjectItem = $_
                    Type = Get-Type $_.Kind
                    Language = Get-Language $_
                }

                & $action $obj

                if($_.ProjectItems) {
                    Recurse-ProjectItems $_.ProjectItems $action
                }
            }
        }

        if($ProjectName) {
            $p = Get-Project $ProjectName
        }
        else {
            $p = Get-Project
        }

        $p | %{ Recurse-ProjectItems $_.ProjectItems $Action } 
    }
}

# Statement completion for project names
Register-TabExpansion 'Recurse-Project' @{
    ProjectName = { Get-Project -All | Select -ExpandProperty Name }
}

Reopen Visual Studio to use the command

When you reopen Visual Studio, the command is available.

重新打开Visual Studio时,该命令可用。

Simply run it from the NuGet Package Manager Console: Format-Document This will re-format all files of the selected project.
To apply to the whole solution, use the command Get-Project -All | Format-Document, which lists the projects and then for each of them calls the reformatting command.

只需从NuGet包管理器控制台运行它:Format-Document这将重新格式化所选项目的所有文件。要应用于整个解决方案,请使用命令Get-Project -All | Format-Document,列出项目,然后为每个项目调用重新格式化命令。

As the author put it:

正如作者所说:

With this in place, you can now indulge your OCD and run the Format-Document command to clean up your entire solution. I just ran it against <Project> and now can become the whitespace Nazi I’ve always wanted to be.

有了这个,您现在可以放纵您的OCD并运行Format-Document命令来清理整个解决方案。我只是针对 运行它,现在可以成为我一直想成为的空白纳粹。

10/10, would run again.

10/10,会再次运行。

#4


Additional step needed for Visual Studio 2015

Phil Haack's solution posted by ANeves is perfect, but for some reason $item.FileCodeModel.Language always returns null in Visual Studio 2015 making the Format-Document skip all files and effectively do nothing.

由ANeves发布的Phil Haack的解决方案是完美的,但由于某种原因$ item.FileCodeModel.Language在Visual Studio 2015中始终返回null,使得Format-Document跳过所有文件并且实际上什么都不做。

To (hackily) work around this limitation you can replace the Get-Language function:

要(hackily)解决此限制,您可以替换Get-Language函数:

# Convert language guid to friendly name
function Get-Language($item) {
    if(!$item.FileCodeModel) {
        return $null
    }

    $kind = $item.FileCodeModel.Language
    switch($kind) {
        '{B5E9BD34-6D3E-4B5D-925E-8A43B79820B4}' { 'C#' }
        '{B5E9BD33-6D3E-4B5D-925E-8A43B79820B4}' { 'VB' }
        default { $kind }
    }
}

with the following variant that uses the file's extension instead of the Language GUID:

使用以下使用文件扩展名而不是语言GUID的变体:

# Convert file extension to friendly language name
function Get-Language($item) {
   if(!$item.FileCodeModel) {
       return $null
   }

   $filename = $item.Name
   $ext = $filename.substring($filename.lastindexof('.'),
                              ($filename.length - $filename.lastindexof('.')))
   switch($ext) {
       '.cs' { 'C#' }
       '.vb' { 'VB' }
       # If you want to prevent re-formatting files that are not VB or C# source files 
       # (e.g. XML files in your project etc.), replace the following line with 
       # "default { $null }" (thanks to HHenn for this suggestion!)
       default { $ext }
   }            
}