C++ 在 Visual Studio 代码中垂直对齐声明

C++ vertically align declarations in Visual Studio Code

我尝试在 Visual Studio 代码中进行垂直声明对齐。

此代码:

struct A {
  double a;
  int b;
}

必须转换成这样:

struct A {
  double a;
  int    b;
}

注意,这里不是赋值,这只是具有对齐字段的结构声明。

是否有 Visual Studio 代码的任何扩展?

Clang 格式

可能,你应该也可以使用 clang-format 和它的 AlignConsecutiveDeclarations 选项,但我还没有验证这是否可行对于连续 class 个成员声明(如果没有,此部分将被删除):

AlignConsecutiveDeclarations (bool)

If true, aligns consecutive declarations.

This will align the declaration names of consecutive lines. This will result in formattings like

int         aaaa = 12;
float       b = 23;
std::string ccc = 23;

Visual Studio 代码格式化程序:代码对齐

以下受影响部分中提到的扩展适用于Visual Studio;不是 Visual Studio 代码(按照 OP 的要求)。同一作者发布了 VSCode 的代码对齐的早期改编版本,但是:

Current State

Many of Code alignment's best features are currently missing. The plan is to release early and release often, and to eventually reach parity.

Main code alignment repository: https://github.com/cpmcgrath/codealignment

...

Visual Studio 扩展名 Code alignment 允许您格式化,例如按照您在示例中显示的方式构造成员。

引用 it's documentation:

The Code alignment extension allows you to align by more than just the equals ...

Some more examples

private string m_firstName = string.Empty; => private string  m_firstName = string.Empty; 
private string m_surname = string.Empty;   => private string  m_surname   = string.Empty; 
private int m_age = 18;                    => private int     m_age       = 18; 
private Address m_address;                 => private Address m_address;

...

对于那些使用Clion的人来说,Editor > Code Style > C/C++中有一个选项。在 Wrapping and Braces 选项卡中,您可以选中 Variable groups | Align in columns 复选框。

clang-format 与 "AlignConsecutiveDeclarations" 输出:

struct A {
  double a;
  int    b;
}