定义

  • 简言之,EditorConfig 用来定义代码格式,以实现不同编辑器、不同项目成员之间统一代码风格

目的

  • 帮助开发者在不同的编辑器和IDE之间定义和维护一致的代码风格

如何使用

  • 在响应工程项目的根目录添加.editorconfig文件
  • 当打开一个文件时,EditorConfig插件会在打开文件的目录和其每一级父目录查找.editorconfig文件,直到有一个配置文件root=true。EditorConfig配置文件从上往下读取,并且路径最近的文件最后被读取。匹配的配置属性按照属性应用在代码上,所以最接近代码文件的属性优先级最高。

注意:Windows 用户在项目根目录创建.editorconfig文件,可以先创建.editorconfig.文件,系统会自动重名为.editorconfig。

.editorconfig示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
root = true

[*]

# Change these settings to your own preference
indent_style = space
indent_size = 4

# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[{package,bower}.json]
indent_style = space
indent_size = 4

[pom.xml]
indent_style = space
indent_size = 4

editorconfig文件格式

  • EditorConfig文件使用INI格式。斜杠(/)作为路径分隔符,#或者;作为注释。EditorConfig文件使用UTF-8格式、CRLF或LF作为换行符。

  • 通配符:

* 匹配除/之外的任意字符串
** 匹配任意字符串
? 匹配任意单个字符
[name] 匹配name字符
[!name] 匹配非name字符
{s1,s2,s3} 匹配任意给定的字符串(since 0.11.0)
  • 属性:
indent_style: 设置缩进风格,tab或者空格。tab是hardtabs,space为softtabs。
indent_size: 缩进的宽度,即列数,整数。如果indent_style为tab,则此属性默认为tab_width。
tab_width: 设置tab的列数。默认是indent_size。
end_of_line: 换行符,lf、cr和crlf
charset: 编码,latin1、utf-8、utf-8-bom、utf-16be和utf-16le,不建议使用utf-8-bom。
trim_trailing_whitespace: 设为true表示会除去换行行首的任意空白字符。
insert_final_newline: 设为true表明使文件以一个空白行结尾
root: 表明是最顶层的配置文件,发现设为true时,才会停止查找.editorconfig文件。

实现方式

  • 某些IDE本身支持Editorconfig,如GitHub,Intellij IDEA,WebStorm等
  • 某些不支持的可以通过相应的插件提供支持

参考或引用