editorconfig.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. --- @brief
  2. --- Nvim supports EditorConfig. When a file is opened, after running |ftplugin|s
  3. --- and |FileType| autocommands, Nvim searches all parent directories of that file
  4. --- for ".editorconfig" files, parses them, and applies any properties that match
  5. --- the opened file. Think of it like 'modeline' for an entire (recursive)
  6. --- directory. For more information see https://editorconfig.org/.
  7. --- @brief [g:editorconfig]() [b:editorconfig]()
  8. ---
  9. --- EditorConfig is enabled by default. To disable it, add to your config:
  10. --- ```lua
  11. --- vim.g.editorconfig = false
  12. --- ```
  13. ---
  14. --- (Vimscript: `let g:editorconfig = v:false`). It can also be disabled
  15. --- per-buffer by setting the [b:editorconfig] buffer-local variable to `false`.
  16. ---
  17. --- Nvim stores the applied properties in [b:editorconfig] if it is not `false`.
  18. --- @brief [editorconfig-custom-properties]()
  19. ---
  20. --- New properties can be added by adding a new entry to the "properties" table.
  21. --- The table key is a property name and the value is a callback function which
  22. --- accepts the number of the buffer to be modified, the value of the property
  23. --- in the `.editorconfig` file, and (optionally) a table containing all of the
  24. --- other properties and their values (useful for properties which depend on other
  25. --- properties). The value is always a string and must be coerced if necessary.
  26. --- Example:
  27. ---
  28. --- ```lua
  29. ---
  30. --- require('editorconfig').properties.foo = function(bufnr, val, opts)
  31. --- if opts.charset and opts.charset ~= "utf-8" then
  32. --- error("foo can only be set when charset is utf-8", 0)
  33. --- end
  34. --- vim.b[bufnr].foo = val
  35. --- end
  36. ---
  37. --- ```
  38. --- @brief [editorconfig-properties]()
  39. ---
  40. --- The following properties are supported by default:
  41. --- @type table<string,fun(bufnr: integer, val: string, opts?: table)>
  42. local properties = {}
  43. --- Modified version of the builtin assert that does not include error position information
  44. ---
  45. --- @param v any Condition
  46. --- @param message string Error message to display if condition is false or nil
  47. --- @return any v if not false or nil, otherwise an error is displayed
  48. local function assert(v, message)
  49. return v or error(message, 0)
  50. end
  51. --- Show a warning message
  52. --- @param msg string Message to show
  53. local function warn(msg, ...)
  54. vim.notify_once(msg:format(...), vim.log.levels.WARN, {
  55. title = 'editorconfig',
  56. })
  57. end
  58. --- If "true", then stop searching for `.editorconfig` files in parent
  59. --- directories. This property must be at the top-level of the
  60. --- `.editorconfig` file (i.e. it must not be within a glob section).
  61. function properties.root()
  62. -- Unused
  63. end
  64. --- One of `"utf-8"`, `"utf-8-bom"`, `"latin1"`, `"utf-16be"`, or `"utf-16le"`.
  65. --- Sets the 'fileencoding' and 'bomb' options.
  66. function properties.charset(bufnr, val)
  67. assert(
  68. vim.list_contains({ 'utf-8', 'utf-8-bom', 'latin1', 'utf-16be', 'utf-16le' }, val),
  69. 'charset must be one of "utf-8", "utf-8-bom", "latin1", "utf-16be", or "utf-16le"'
  70. )
  71. if val == 'utf-8' or val == 'utf-8-bom' then
  72. vim.bo[bufnr].fileencoding = 'utf-8'
  73. vim.bo[bufnr].bomb = val == 'utf-8-bom'
  74. elseif val == 'utf-16be' then
  75. vim.bo[bufnr].fileencoding = 'utf-16'
  76. else
  77. vim.bo[bufnr].fileencoding = val
  78. end
  79. end
  80. --- One of `"lf"`, `"crlf"`, or `"cr"`.
  81. --- These correspond to setting 'fileformat' to "unix", "dos", or "mac",
  82. --- respectively.
  83. function properties.end_of_line(bufnr, val)
  84. vim.bo[bufnr].fileformat = assert(
  85. ({ lf = 'unix', crlf = 'dos', cr = 'mac' })[val],
  86. 'end_of_line must be one of "lf", "crlf", or "cr"'
  87. )
  88. end
  89. --- One of `"tab"` or `"space"`. Sets the 'expandtab' option.
  90. function properties.indent_style(bufnr, val, opts)
  91. assert(val == 'tab' or val == 'space', 'indent_style must be either "tab" or "space"')
  92. vim.bo[bufnr].expandtab = val == 'space'
  93. if val == 'tab' and not opts.indent_size then
  94. vim.bo[bufnr].shiftwidth = 0
  95. vim.bo[bufnr].softtabstop = 0
  96. end
  97. end
  98. --- A number indicating the size of a single indent. Alternatively, use the
  99. --- value "tab" to use the value of the tab_width property. Sets the
  100. --- 'shiftwidth' and 'softtabstop' options. If this value is not "tab" and
  101. --- the tab_width property is not set, 'tabstop' is also set to this value.
  102. function properties.indent_size(bufnr, val, opts)
  103. if val == 'tab' then
  104. vim.bo[bufnr].shiftwidth = 0
  105. vim.bo[bufnr].softtabstop = 0
  106. else
  107. local n = assert(tonumber(val), 'indent_size must be a number')
  108. vim.bo[bufnr].shiftwidth = n
  109. vim.bo[bufnr].softtabstop = -1
  110. if not opts.tab_width then
  111. vim.bo[bufnr].tabstop = n
  112. end
  113. end
  114. end
  115. --- The display size of a single tab character. Sets the 'tabstop' option.
  116. function properties.tab_width(bufnr, val)
  117. vim.bo[bufnr].tabstop = assert(tonumber(val), 'tab_width must be a number')
  118. end
  119. --- A number indicating the maximum length of a single
  120. --- line. Sets the 'textwidth' option.
  121. function properties.max_line_length(bufnr, val)
  122. local n = tonumber(val)
  123. if n then
  124. vim.bo[bufnr].textwidth = n
  125. else
  126. assert(val == 'off', 'max_line_length must be a number or "off"')
  127. vim.bo[bufnr].textwidth = 0
  128. end
  129. end
  130. --- When `"true"`, trailing whitespace is automatically removed when the buffer is written.
  131. function properties.trim_trailing_whitespace(bufnr, val)
  132. assert(
  133. val == 'true' or val == 'false',
  134. 'trim_trailing_whitespace must be either "true" or "false"'
  135. )
  136. if val == 'true' then
  137. vim.api.nvim_create_autocmd('BufWritePre', {
  138. group = 'nvim.editorconfig',
  139. buffer = bufnr,
  140. callback = function()
  141. local view = vim.fn.winsaveview()
  142. vim.api.nvim_command('silent! undojoin')
  143. vim.api.nvim_command('silent keepjumps keeppatterns %s/\\s\\+$//e')
  144. vim.fn.winrestview(view)
  145. end,
  146. })
  147. else
  148. vim.api.nvim_clear_autocmds({
  149. event = 'BufWritePre',
  150. group = 'nvim.editorconfig',
  151. buffer = bufnr,
  152. })
  153. end
  154. end
  155. --- `"true"` or `"false"` to ensure the file always has a trailing newline as its last byte.
  156. --- Sets the 'fixendofline' and 'endofline' options.
  157. function properties.insert_final_newline(bufnr, val)
  158. assert(val == 'true' or val == 'false', 'insert_final_newline must be either "true" or "false"')
  159. vim.bo[bufnr].fixendofline = val == 'true'
  160. -- 'endofline' can be read to detect if the file contains a final newline,
  161. -- so only change 'endofline' right before writing the file
  162. local endofline = val == 'true'
  163. if vim.bo[bufnr].endofline ~= endofline then
  164. vim.api.nvim_create_autocmd('BufWritePre', {
  165. group = 'nvim.editorconfig',
  166. buffer = bufnr,
  167. once = true,
  168. callback = function()
  169. vim.bo[bufnr].endofline = endofline
  170. end,
  171. })
  172. end
  173. end
  174. --- A code of the format ss or ss-TT, where ss is an ISO 639 language code and TT is an ISO 3166 territory identifier.
  175. --- Sets the 'spelllang' option.
  176. function properties.spelling_language(bufnr, val)
  177. local error_msg =
  178. 'spelling_language must be of the format ss or ss-TT, where ss is an ISO 639 language code and TT is an ISO 3166 territory identifier.'
  179. assert(val:len() == 2 or val:len() == 5, error_msg)
  180. local language_code = val:sub(1, 2):lower()
  181. assert(language_code:match('%l%l'), error_msg)
  182. if val:len() == 2 then
  183. vim.bo[bufnr].spelllang = language_code
  184. else
  185. assert(val:sub(3, 3) == '-', error_msg)
  186. local territory_code = val:sub(4, 5):lower()
  187. assert(territory_code:match('%l%l'), error_msg)
  188. vim.bo[bufnr].spelllang = language_code .. '_' .. territory_code
  189. end
  190. end
  191. --- Modified version of [glob2regpat()] that does not match path separators on `*`.
  192. ---
  193. --- This function replaces single instances of `*` with the regex pattern `[^/]*`.
  194. --- However, the star in the replacement pattern also gets interpreted by glob2regpat,
  195. --- so we insert a placeholder, pass it through glob2regpat, then replace the
  196. --- placeholder with the actual regex pattern.
  197. ---
  198. --- @param glob string Glob to convert into a regular expression
  199. --- @return string regex Regular expression
  200. local function glob2regpat(glob)
  201. local placeholder = '@@PLACEHOLDER@@'
  202. local glob1 = vim.fn.substitute(
  203. glob:gsub('{(%d+)%.%.(%d+)}', '[%1-%2]'),
  204. '\\*\\@<!\\*\\*\\@!',
  205. placeholder,
  206. 'g'
  207. )
  208. local regpat = vim.fn.glob2regpat(glob1)
  209. return (regpat:gsub(placeholder, '[^/]*'))
  210. end
  211. --- Parse a single line in an EditorConfig file
  212. --- @param line string Line
  213. --- @return string? glob pattern if the line contains a pattern
  214. --- @return string? key if the line contains a key-value pair
  215. --- @return string? value if the line contains a key-value pair
  216. local function parse_line(line)
  217. if not line:find('^%s*[^ #;]') then
  218. return
  219. end
  220. --- @type string?
  221. local glob = line:match('^%s*%[(.*)%]%s*$')
  222. if glob then
  223. return glob
  224. end
  225. local key, val = line:match('^%s*([^:= ][^:=]-)%s*[:=]%s*(.-)%s*$')
  226. if key ~= nil and val ~= nil then
  227. return nil, key:lower(), val:lower()
  228. end
  229. end
  230. --- Parse options from an `.editorconfig` file
  231. --- @param filepath string File path of the file to apply EditorConfig settings to
  232. --- @param dir string Current directory
  233. --- @return table<string,string|boolean> Table of options to apply to the given file
  234. local function parse(filepath, dir)
  235. local pat --- @type vim.regex?
  236. local opts = {} --- @type table<string,string|boolean>
  237. local f = io.open(dir .. '/.editorconfig')
  238. if f then
  239. for line in f:lines() do
  240. local glob, key, val = parse_line(line)
  241. if glob then
  242. glob = glob:find('/') and (dir .. '/' .. glob:gsub('^/', '')) or ('**/' .. glob)
  243. local ok, regpat = pcall(glob2regpat, glob)
  244. if ok then
  245. pat = vim.regex(regpat)
  246. else
  247. pat = nil
  248. warn('editorconfig: Error occurred while parsing glob pattern "%s": %s', glob, regpat)
  249. end
  250. elseif key ~= nil and val ~= nil then
  251. if key == 'root' then
  252. assert(val == 'true' or val == 'false', 'root must be either "true" or "false"')
  253. opts.root = val == 'true'
  254. elseif pat and pat:match_str(filepath) then
  255. opts[key] = val
  256. end
  257. end
  258. end
  259. f:close()
  260. end
  261. return opts
  262. end
  263. local M = {}
  264. -- Exposed for use in syntax/editorconfig.vim`
  265. M.properties = properties
  266. --- @private
  267. --- Configure the given buffer with options from an `.editorconfig` file
  268. --- @param bufnr integer Buffer number to configure
  269. function M.config(bufnr)
  270. bufnr = bufnr or vim.api.nvim_get_current_buf()
  271. if not vim.api.nvim_buf_is_valid(bufnr) then
  272. return
  273. end
  274. local path = vim.fs.normalize(vim.api.nvim_buf_get_name(bufnr))
  275. if vim.bo[bufnr].buftype ~= '' or not vim.bo[bufnr].modifiable or path == '' then
  276. return
  277. end
  278. local opts = {} --- @type table<string,string|boolean>
  279. for parent in vim.fs.parents(path) do
  280. for k, v in pairs(parse(path, parent)) do
  281. if opts[k] == nil then
  282. opts[k] = v
  283. end
  284. end
  285. if opts.root then
  286. break
  287. end
  288. end
  289. local applied = {} --- @type table<string,string|boolean>
  290. for opt, val in pairs(opts) do
  291. if val ~= 'unset' then
  292. local func = M.properties[opt]
  293. if func then
  294. --- @type boolean, string?
  295. local ok, err = pcall(func, bufnr, val, opts)
  296. if ok then
  297. applied[opt] = val
  298. else
  299. warn('editorconfig: invalid value for option %s: %s. %s', opt, val, err)
  300. end
  301. end
  302. end
  303. end
  304. vim.b[bufnr].editorconfig = applied
  305. end
  306. return M