简要了解EditorConfig

111 阅读2分钟

参考来源:EditorConfig

平常多人协作时,大家的格式风格并不一致,这对于有点强迫症的人来说看着属实难受。 查询了一番,找到了EditorConfig,便记录一二。

什么是EditorConfig

  • 为使用不同编辑器或IDE的、对同一项目进行开发的人员维护一致的编码风格。
  • 由用于定义编码样式的文件格式和一系列文本编辑器插件组成,其中的文本编辑器插件可以读取文件格式并根据已定义的样式进行样式修改。

例子

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# Matches multiple files with brace expansion notation
# Set default charset
[*.{js,py}]
charset = utf-8

# 4 space indentation
[*.py]
indent_style = space
indent_size = 4

# Tab indentation (no size specified)
[Makefile]
indent_style = tab

# Indentation override for all JS under lib directory
[lib/**.js]
indent_style = space
indent_size = 2

# Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2

EditorConfig文件规则

  • 打开文件的时候,EditorConfig的插件会在打开文件的目录以及每个父目录中查找.editorconfig文件。如果查找到达了根文件路径或者查找到一个设置了root=true.editorconfig文件,便会停止查找。
  • 读取规则是自上到下读取EditorConfig文件,且以最新发现的规则优先生效。
  • 在Windows中创建该文件时,命名为.editorconfig.,如此,Windows资源管理器会将其自动重命名为.editorconfig

支持的属性

需要注意,并非所有插件都支持所有的属性。完整的属性列表可参考:github.com/editorconfi…

indent_style

取值tabspace

  • tab,硬制表符
    • 通过按下Tab键实现。
    • 在不同的编辑器中显示的长度可能不一致。
  • space,软制表符
    • 通过按下空格键实现。
    • 长度固定,不受编辑器影响。
indent_size

取值为一个整数。定义每个缩进级别使用的列数和软制表符的宽度(如果选择了tab)。

end_of_line

取值lfcrcrlf,用于控制换行符的表示方式。

  • lf,回车符
    • 表示回车操作。
    • ASCII码为0x0D。
  • cr,换行符
    • 表示换行操作。
    • 一般作为Unix、Linux系统中的行尾标志。
    • ASCII码为0x0A。
  • crlf,回车符+换行符
    • 表示一行的结束。
    • 一般作为Windows系统中的行尾标志。
charset

字符集,取值 latinl utf-8 utf-8-bom utf-16be utf-16le

trim_trailing_whitespace
  • true,删除换行符之前的所有空白字符。
  • false,不删除。
insert_final_newline
  • true,文件在保存时以换行符结束。
  • false,不处理。