robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

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