robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 ) 71return v or error ( message , 0 ) 72end 73 74--- Show a warning message 75--- @param msg string Message to show 76local function warn ( msg , ... ) 77vim . notify_once ( msg : format ( ... ), vim . log . levels . WARN , { 78title ='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 ) 93assert ( 94vim . 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) 97if val == 'utf-8' or val == 'utf-8-bom' then 98vim . bo [ bufnr ]. fileencoding ='utf-8' 99vim . bo [ bufnr ]. bomb =val == 'utf-8-bom' 100elseif val == 'utf-16be' then 101vim . bo [ bufnr ]. fileencoding ='utf-16' 102else 103vim . bo [ bufnr ]. fileencoding =val 104end 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 ) 111vim . 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 ) 119assert ( val == 'tab' or val == 'space' , 'indent_style must be either "tab" or "space"' ) 120vim . bo [ bufnr ]. expandtab =val == 'space' 121if val == 'tab' and not opts . indent_size then 122vim . bo [ bufnr ]. shiftwidth =0 123vim . bo [ bufnr ]. softtabstop =0 124end 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 ) 132if val == 'tab' then 133vim . bo [ bufnr ]. shiftwidth =0 134vim . bo [ bufnr ]. softtabstop =0 135else 136local n =assert ( vim . _tointeger ( val ), 'indent_size must be an integer' ) 137vim . bo [ bufnr ]. shiftwidth =n 138vim . bo [ bufnr ]. softtabstop =- 1 139if not opts . tab_width then 140vim . bo [ bufnr ]. tabstop =n 141end 142end 143end 144 145--- The display size of a single tab character. Sets the 'tabstop' option. 146function properties . tab_width ( bufnr , val ) 147vim . 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 ) 153local n =vim . _tointeger ( val ) 154if n then 155vim . bo [ bufnr ]. textwidth =n 156else 157assert ( val == 'off' , 'max_line_length must be an integer or "off"' ) 158vim . bo [ bufnr ]. textwidth =0 159end 160end 161 162--- When `"true"`, trailing whitespace is automatically removed when the buffer is written. 163function properties . trim_trailing_whitespace ( bufnr , val ) 164assert ( 165val == 'true' or val == 'false' , 166'trim_trailing_whitespace must be either "true" or "false"' 167) 168if val == 'true' then 169nvim_on ( 'BufWritePre' , 'nvim.editorconfig' , { buf =bufnr } , function () 170local mode =vim . api . nvim_get_mode (). mode 171if mode : sub ( 1 , 1 ) == 'i' or mode : sub ( 1 , 1 ) == 'R' or mode : sub ( 1 , 2 ) == 'ni' then 172return 173end 174local view =vim . fn . winsaveview () 175vim . api . nvim_command ( 'silent! undojoin' ) 176vim . api . nvim_command ( 'silent keepjumps keeppatterns %s/\\s\\+$//e' ) 177vim . fn . winrestview ( view ) 178end ) 179else 180vim . api . nvim_clear_autocmds ( { 181event ='BufWritePre' , 182group ='nvim.editorconfig' , 183buf =bufnr , 184} ) 185end 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 ) 191assert ( val == 'true' or val == 'false' , 'insert_final_newline must be either "true" or "false"' ) 192vim . 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 196local endofline =val == 'true' 197if vim . bo [ bufnr ]. endofline ~= endofline then 198nvim_on ( 'BufWritePre' , 'nvim.editorconfig' , { buf =bufnr , once =true } , function () 199vim . bo [ bufnr ]. endofline =endofline 200end ) 201end 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 ) 207local 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 210assert ( val : len () == 2 or val : len () == 5 , error_msg ) 211 212local language_code =val : sub ( 1 , 2 ): lower () 213assert ( language_code : match ( '%l%l' ), error_msg ) 214if val : len () == 2 then 215vim . bo [ bufnr ]. spelllang =language_code 216else 217assert ( val : sub ( 3 , 3 ) == '-' , error_msg ) 218 219local territory_code =val : sub ( 4 , 5 ): lower () 220assert ( territory_code : match ( '%l%l' ), error_msg ) 221vim . bo [ bufnr ]. spelllang =language_code .. '_' .. territory_code 222end 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 ) 235local placeholder ='@@PLACEHOLDER@@' 236local glob1 =vim . fn . substitute ( 237glob : gsub ( '{(%d+)%.%.(%d+)}' , '[%1-%2]' ), 238'\\*\\@<!\\*\\*\\@!' , 239placeholder , 240'g' 241) 242local regpat =vim . fn . glob2regpat ( glob1 ) 243return ( 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 ) 252if not line : find ( '^%s*[^ #;]' ) then 253return 254end 255 256--- @type string? 257local glob =line : match ( '^%s*%[(.*)%]%s*$' ) 258if glob then 259return glob 260end 261 262local key , val =line : match ( '^%s*([^:= ][^:=]-)%s*[:=]%s*(.-)%s*$' ) 263if key ~= nil and val ~= nil then 264return nil , key : lower (), val : lower () 265end 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 ) 274local pat --- @type vim.regex? 275local opts ={} --- @type table<string,string> 276local is_root =false 277local f =io . open ( dir .. '/.editorconfig' ) 278if f then 279for line in f : lines () do 280--- @cast line string 281local glob , key , val =parse_line ( line ) 282if glob then 283glob =glob : find ( '/' ) and ( dir .. '/' .. glob : gsub ( '^/' , '' )) or ( '**/' .. glob ) 284local ok , regpat =pcall ( glob2regpat , glob ) 285if ok then 286pat =vim . regex ( regpat ) 287else 288pat =nil 289warn ( 'editorconfig: Error occurred while parsing glob pattern "%s": %s' , glob , regpat ) 290end 291elseif key ~= nil and val ~= nil then 292if key == 'root' then 293assert ( val == 'true' or val == 'false' , 'root must be either "true" or "false"' ) 294is_root =val == 'true' 295elseif pat and pat : match_str ( filepath ) then 296opts [ key ] =val 297end 298end 299end 300f : close () 301end 302return 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 ) 314buf =buf or vim . api . nvim_get_current_buf () 315if not vim . api . nvim_buf_is_valid ( buf ) then 316return 317end 318 319local path =vim . fs . normalize ( vim . api . nvim_buf_get_name ( buf )) 320if vim . bo [ buf ]. buftype ~= '' or not vim . bo [ buf ]. modifiable or path == '' then 321return 322end 323 324local opts ={} --- @type table<string,string> 325for parent in vim . fs . parents ( path ) do 326local parent_opts , is_root =parse ( path , parent ) 327for k , v in pairs ( parent_opts ) do 328if opts [ k ] == nil then 329opts [ k ] =v 330end 331end 332 333if is_root then 334break 335end 336end 337 338local applied ={} --- @type table<string,string> 339for opt , val in pairs ( opts ) do 340if val ~= 'unset' then 341local func =M . properties [ opt ] 342if func then 343local ok , err =pcall ( func , buf , val , opts ) 344if ok then 345applied [ opt ] =val 346else 347warn ( 'editorconfig: invalid value for option %s: %s. %s' , opt , val , err ) 348end 349end 350end 351end 352 353vim . b [ buf ]. editorconfig =applied 354end 355 356return M