VS Code中如何设置多个垂直标尺

VS Code中如何设置多个垂直标尺

技术背景

在Visual Studio Code 0.10.10版本引入了设置多个垂直标尺的功能。垂直标尺可以帮助开发者直观地了解代码的长度,对于遵循特定代码风格规范非常有帮助。例如,Python项目的风格指南通常指定代码行长度为79或120个字符,Git提交信息应不超过50个字符。

实现步骤

全局设置

  1. 打开VS Code,选择菜单 FilePreferencesSettings
  2. 在用户或工作区设置中添加以下配置:
1
"editor.rulers": [80, 120]

此配置会在第80和120个字符位置显示垂直标尺。

自定义标尺颜色

可以通过以下配置自定义标尺颜色:

1
2
3
"workbench.colorCustomizations": {
"editorRuler.foreground": "#ff4081"
}

按语言级别设置

除了全局 editor.rulers 设置,还可以按语言级别进行设置。例如,在 settings.json 中添加以下配置:

1
2
3
4
5
6
7
"[git-commit]": {"editor.rulers": [50]},
"[python]": {
"editor.rulers": [
79,
120
]
}

不同版本的设置操作

  • Visual Studio Code 1.27.2
    1. 选择 File > Preference > Settings
    2. Search settings 中输入 rulers
    3. 点击第一个 Edit in settings.json 编辑用户设置。
    4. 点击 Default user settings 中设置左侧出现的笔图标,将其复制到用户设置并编辑。
  • Visual Studio Code 1.38.1:操作基本与1.27.2版本类似,但界面可能有所不同。
  • Visual Studio Code 1.43:支持为每个垂直标尺单独设置颜色。

其他版本设置示例

  • Visual Studio Code 1.14.2
    1. 按下 Shift + Command + P(非macOS用户按 Ctrl + P)打开命令面板。
    2. 输入 settings.json 打开设置文件。
    3. 在默认设置中,"editor.rulers": [] 表示不显示垂直标尺。
    4. 在右侧的 “user setting” 窗口中添加以下配置:
1
"editor.rulers": [140]

保存文件后,即可看到标尺。

核心代码

多个垂直标尺设置

1
2
3
{
"editor.rulers": [80, 125]
}

为标尺设置颜色

1
2
3
4
5
6
{
"workbench.colorCustomizations": {
"editorRuler.foreground": "#0099AA"
},
"editor.rulers": [80, 125]
}

为不同列的标尺设置不同颜色

1
2
3
4
5
6
7
8
9
10
11
"editor.rulers": [
{
"column": 80,
"color": "#ff9900"
},
100,
{
"column": 120,
"color": "#9f0af5"
}
]

按语言设置标尺

1
2
3
4
5
6
7
8
"[ruby]": {
"editor.rulers": [
{
"column": 100,
"color": "#00ff22"
}
]
}

最佳实践

不同项目的设置

  • Python项目:通常将标尺设置为79或120个字符。
1
2
3
"[python]": {
"editor.rulers": [79, 120]
}
  • Git提交信息:设置为不超过50个字符。
1
"[git-commit]": {"editor.rulers": [50]}

自定义颜色和透明度

为了使标尺不影响代码的可读性,可以设置较淡的颜色和透明度。

1
2
3
4
5
6
{
"workbench.colorCustomizations": {
"editorRuler.foreground": "#0099AA33"
},
"editor.rulers": [80, 125]
}

多个透明标尺叠加效果

通过叠加多个透明标尺,可以实现有趣的效果。

1
2
3
4
5
6
{
"workbench.colorCustomizations": {
"editorRuler.foreground": "#00999922"
},
"editor.rulers": [20, 40, 40, 60, 60, 60, 60, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80]
}

常见问题

配置未生效

如果配置后标尺未显示,可能需要重新加载VS Code窗口。按下 F1 打开快速输入菜单,输入 Developer: Reload Window 并选择该选项。

颜色设置不生效

检查颜色代码是否正确,确保颜色代码符合CSS颜色规范。同时,注意版本兼容性,某些版本可能不支持某些颜色设置方式。


VS Code中如何设置多个垂直标尺
https://119291.xyz/posts/how-to-set-multiple-vertical-rulers-in-vs-code/
作者
ww
发布于
2025年5月29日
许可协议