editorconfig.vim (20650B)
1 " plugin/editorconfig.vim: EditorConfig native Vim script plugin file 2 " Copyright (c) 2011-2019 EditorConfig Team 3 " All rights reserved. 4 " 5 " Redistribution and use in source and binary forms, with or without 6 " modification, are permitted provided that the following conditions are met: 7 " 8 " 1. Redistributions of source code must retain the above copyright notice, 9 " this list of conditions and the following disclaimer. 10 " 2. Redistributions in binary form must reproduce the above copyright notice, 11 " this list of conditions and the following disclaimer in the documentation 12 " and/or other materials provided with the distribution. 13 " 14 " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 15 " AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 " ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 18 " LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 19 " CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 20 " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 21 " INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 22 " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 23 " ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 24 " POSSIBILITY OF SUCH DAMAGE. 25 " 26 27 " check for Vim versions and duplicate script loading. 28 if v:version < 700 || exists("g:loaded_EditorConfig") 29 finish 30 endif 31 let g:loaded_EditorConfig = 1 32 33 let s:saved_cpo = &cpo 34 set cpo&vim 35 36 " variables {{{1 37 38 " Make sure the globals all exist 39 if !exists('g:EditorConfig_exec_path') 40 let g:EditorConfig_exec_path = '' 41 endif 42 43 if !exists('g:EditorConfig_verbose') 44 let g:EditorConfig_verbose = 0 45 endif 46 47 if !exists('g:EditorConfig_preserve_formatoptions') 48 let g:EditorConfig_preserve_formatoptions = 0 49 endif 50 51 if !exists('g:EditorConfig_max_line_indicator') 52 let g:EditorConfig_max_line_indicator = 'line' 53 endif 54 55 if !exists('g:EditorConfig_exclude_patterns') 56 let g:EditorConfig_exclude_patterns = [] 57 endif 58 59 if !exists('g:EditorConfig_disable_rules') 60 let g:EditorConfig_disable_rules = [] 61 endif 62 63 if !exists('g:EditorConfig_enable_for_new_buf') 64 let g:EditorConfig_enable_for_new_buf = 0 65 endif 66 67 if !exists('g:EditorConfig_softtabstop_space') 68 let g:EditorConfig_softtabstop_space = 1 69 endif 70 71 if !exists('g:EditorConfig_softtabstop_tab') 72 let g:EditorConfig_softtabstop_tab = 1 73 endif 74 75 " Copy some of the globals into script variables --- changes to these 76 " globals won't affect the plugin until the plugin is reloaded. 77 if exists('g:EditorConfig_core_mode') && !empty(g:EditorConfig_core_mode) 78 let s:editorconfig_core_mode = g:EditorConfig_core_mode 79 else 80 let s:editorconfig_core_mode = '' 81 endif 82 83 if exists('g:EditorConfig_exec_path') && !empty(g:EditorConfig_exec_path) 84 let s:editorconfig_exec_path = g:EditorConfig_exec_path 85 else 86 let s:editorconfig_exec_path = '' 87 endif 88 89 let s:initialized = 0 90 91 " }}}1 92 93 " shellslash handling {{{1 94 function! s:DisableShellSlash(bufnr) " {{{2 95 " disable shellslash for proper escaping of Windows paths 96 97 " In Windows, 'shellslash' also changes the behavior of 'shellescape'. 98 " It makes 'shellescape' behave like in UNIX environment. So ':setl 99 " noshellslash' before evaluating 'shellescape' and restore the 100 " settings afterwards when 'shell' does not contain 'sh' somewhere. 101 let l:shell = getbufvar(a:bufnr, '&shell') 102 if has('win32') && empty(matchstr(l:shell, 'sh')) 103 let s:old_shellslash = getbufvar(a:bufnr, '&shellslash') 104 setbufvar(a:bufnr, '&shellslash', 0) 105 endif 106 endfunction " }}}2 107 108 function! s:ResetShellSlash(bufnr) " {{{2 109 " reset shellslash to the user-set value, if any 110 if exists('s:old_shellslash') 111 setbufvar(a:bufnr, '&shellslash', s:old_shellslash) 112 unlet! s:old_shellslash 113 endif 114 endfunction " }}}2 115 " }}}1 116 117 " Mode initialization functions {{{1 118 119 function! s:InitializeVimCore() 120 " Initialize vim core. Returns 1 on failure; 0 on success 121 " At the moment, all we need to do is to check that it is installed. 122 try 123 let l:vim_core_ver = editorconfig_core#version() 124 catch 125 return 1 126 endtry 127 return 0 128 endfunction 129 130 function! s:InitializeExternalCommand() 131 " Initialize external_command mode 132 133 if empty(s:editorconfig_exec_path) 134 echo 'Please specify a g:EditorConfig_exec_path' 135 return 1 136 endif 137 138 if g:EditorConfig_verbose 139 echo 'Checking for external command ' . s:editorconfig_exec_path . ' ...' 140 endif 141 142 if !executable(s:editorconfig_exec_path) 143 echo 'File ' . s:editorconfig_exec_path . ' is not executable.' 144 return 1 145 endif 146 147 return 0 148 endfunction 149 " }}}1 150 151 function! s:Initialize() " Initialize the plugin. {{{1 152 " Returns truthy on error, falsy on success. 153 154 if empty(s:editorconfig_core_mode) 155 let s:editorconfig_core_mode = 'vim_core' " Default core choice 156 endif 157 158 if s:editorconfig_core_mode ==? 'external_command' 159 if s:InitializeExternalCommand() 160 echohl WarningMsg 161 echo 'EditorConfig: Failed to initialize external_command mode. ' . 162 \ 'Falling back to vim_core mode.' 163 echohl None 164 let s:editorconfig_core_mode = 'vim_core' 165 endif 166 endif 167 168 if s:editorconfig_core_mode ==? 'vim_core' 169 if s:InitializeVimCore() 170 echohl ErrorMsg 171 echo 'EditorConfig: Failed to initialize vim_core mode. ' . 172 \ 'The plugin will not function.' 173 echohl None 174 return 1 175 endif 176 177 elseif s:editorconfig_core_mode ==? 'external_command' 178 " Nothing to do here, but this elseif is required to avoid 179 " external_command falling into the else clause. 180 181 else " neither external_command nor vim_core 182 echohl ErrorMsg 183 echo "EditorConfig: I don't know how to use mode " . s:editorconfig_core_mode 184 echohl None 185 return 1 186 endif 187 188 let s:initialized = 1 189 return 0 190 endfunction " }}}1 191 192 function! s:GetFilenames(path, filename) " {{{1 193 " Yield full filepath for filename in each directory in and above path 194 195 let l:path_list = [] 196 let l:path = a:path 197 while 1 198 let l:path_list += [l:path . '/' . a:filename] 199 let l:newpath = fnamemodify(l:path, ':h') 200 if l:path == l:newpath 201 break 202 endif 203 let l:path = l:newpath 204 endwhile 205 return l:path_list 206 endfunction " }}}1 207 208 function! s:UseConfigFiles(from_autocmd) abort " Apply config to the current buffer {{{1 209 " from_autocmd is truthy if called from an autocmd, falsy otherwise. 210 211 " Get the properties of the buffer we are working on 212 if a:from_autocmd 213 let l:bufnr = str2nr(expand('<abuf>')) 214 let l:buffer_name = expand('<afile>:p') 215 let l:buffer_path = expand('<afile>:p:h') 216 else 217 let l:bufnr = bufnr('%') 218 let l:buffer_name = expand('%:p') 219 let l:buffer_path = expand('%:p:h') 220 endif 221 call setbufvar(l:bufnr, 'editorconfig_tried', 1) 222 223 " Only process normal buffers (do not treat help files as '.txt' files) 224 " When starting Vim with a directory, the buftype might not yet be set: 225 " Therefore, also check if buffer_name is a directory. 226 if index(['', 'acwrite'], &buftype) == -1 || isdirectory(l:buffer_name) 227 return 228 endif 229 230 if empty(l:buffer_name) 231 if g:EditorConfig_enable_for_new_buf 232 let l:buffer_name = getcwd() . "/." 233 else 234 if g:EditorConfig_verbose 235 echo 'Skipping EditorConfig for unnamed buffer' 236 endif 237 return 238 endif 239 endif 240 241 if getbufvar(l:bufnr, 'EditorConfig_disable', 0) 242 if g:EditorConfig_verbose 243 echo 'EditorConfig disabled --- skipping buffer "' . l:buffer_name . '"' 244 endif 245 return 246 endif 247 248 " Ignore specific patterns 249 for pattern in g:EditorConfig_exclude_patterns 250 if l:buffer_name =~ pattern 251 if g:EditorConfig_verbose 252 echo 'Skipping EditorConfig for buffer "' . l:buffer_name . 253 \ '" based on pattern "' . pattern . '"' 254 endif 255 return 256 endif 257 endfor 258 259 " Check if any .editorconfig does exist 260 let l:conf_files = s:GetFilenames(l:buffer_path, '.editorconfig') 261 let l:conf_found = 0 262 for conf_file in conf_files 263 if filereadable(conf_file) 264 let l:conf_found = 1 265 break 266 endif 267 endfor 268 if !l:conf_found 269 return 270 endif 271 272 if !s:initialized 273 if s:Initialize() 274 return 275 endif 276 endif 277 278 if g:EditorConfig_verbose 279 echo 'Applying EditorConfig ' . s:editorconfig_core_mode . 280 \ ' on file "' . l:buffer_name . '"' 281 endif 282 283 if s:editorconfig_core_mode ==? 'vim_core' 284 if s:UseConfigFiles_VimCore(l:bufnr, l:buffer_name) == 0 285 call setbufvar(l:bufnr, 'editorconfig_applied', 1) 286 endif 287 elseif s:editorconfig_core_mode ==? 'external_command' 288 call s:UseConfigFiles_ExternalCommand(l:bufnr, l:buffer_name) 289 call setbufvar(l:bufnr, 'editorconfig_applied', 1) 290 else 291 echohl Error | 292 \ echo "Unknown EditorConfig Core: " . 293 \ s:editorconfig_core_mode | 294 \ echohl None 295 endif 296 endfunction " }}}1 297 298 " Custom commands, and autoloading {{{1 299 300 " Autocommands, and function to enable/disable the plugin {{{2 301 function! s:EditorConfigEnable(should_enable) 302 augroup editorconfig 303 autocmd! 304 if a:should_enable 305 autocmd BufNewFile,BufReadPost,BufFilePost * call s:UseConfigFiles(1) 306 autocmd VimEnter,BufNew * call s:UseConfigFiles(1) 307 endif 308 augroup END 309 endfunction 310 311 " }}}2 312 313 " Commands {{{2 314 command! EditorConfigEnable call s:EditorConfigEnable(1) 315 command! EditorConfigDisable call s:EditorConfigEnable(0) 316 317 command! EditorConfigReload call s:UseConfigFiles(0) " Reload EditorConfig files 318 " }}}2 319 320 " On startup, enable the autocommands 321 call s:EditorConfigEnable(1) 322 323 " }}}1 324 325 " UseConfigFiles function for different modes {{{1 326 327 function! s:UseConfigFiles_VimCore(bufnr, target) 328 " Use the Vim script EditorConfig core 329 try 330 let l:config = editorconfig_core#handler#get_configurations( 331 \ { 'target': a:target } ) 332 call s:ApplyConfig(a:bufnr, l:config) 333 return 0 " success 334 catch 335 return 1 " failure 336 endtry 337 endfunction 338 339 function! s:UseConfigFiles_ExternalCommand(bufnr, target) 340 " Use external EditorConfig core (e.g., the C core) 341 342 call s:DisableShellSlash(a:bufnr) 343 let l:exec_path = shellescape(s:editorconfig_exec_path) 344 call s:ResetShellSlash(a:bufnr) 345 346 call s:SpawnExternalParser(a:bufnr, l:exec_path, a:target) 347 endfunction 348 349 function! s:SpawnExternalParser(bufnr, cmd, target) " {{{2 350 " Spawn external EditorConfig. Used by s:UseConfigFiles_ExternalCommand() 351 352 let l:cmd = a:cmd 353 354 if empty(l:cmd) 355 throw 'No cmd provided' 356 endif 357 358 let l:config = {} 359 360 call s:DisableShellSlash(a:bufnr) 361 let l:cmd = l:cmd . ' ' . shellescape(a:target) 362 call s:ResetShellSlash(a:bufnr) 363 364 let l:parsing_result = split(system(l:cmd), '\v[\r\n]+') 365 366 " if editorconfig core's exit code is not zero, give out an error 367 " message 368 if v:shell_error != 0 369 echohl ErrorMsg 370 echo 'Failed to execute "' . l:cmd . '". Exit code: ' . 371 \ v:shell_error 372 echo '' 373 echo 'Message:' 374 echo l:parsing_result 375 echohl None 376 return 377 endif 378 379 if g:EditorConfig_verbose 380 echo 'Output from EditorConfig core executable:' 381 echo l:parsing_result 382 endif 383 384 for one_line in l:parsing_result 385 let l:eq_pos = stridx(one_line, '=') 386 387 if l:eq_pos == -1 " = is not found. Skip this line 388 continue 389 endif 390 391 let l:eq_left = strpart(one_line, 0, l:eq_pos) 392 if l:eq_pos + 1 < strlen(one_line) 393 let l:eq_right = strpart(one_line, l:eq_pos + 1) 394 else 395 let l:eq_right = '' 396 endif 397 398 let l:config[l:eq_left] = l:eq_right 399 endfor 400 401 call s:ApplyConfig(a:bufnr, l:config) 402 endfunction " }}}2 403 404 " }}}1 405 406 " Set the buffer options {{{1 407 function! s:SetCharset(bufnr, charset) abort " apply config['charset'] 408 409 " Remember the buffer's state so we can set `nomodifed` at the end 410 " if appropriate. 411 let l:orig_fenc = getbufvar(a:bufnr, "&fileencoding") 412 let l:orig_enc = getbufvar(a:bufnr, "&encoding") 413 let l:orig_modified = getbufvar(a:bufnr, "&modified") 414 415 if a:charset == "utf-8" 416 call setbufvar(a:bufnr, '&fileencoding', 'utf-8') 417 call setbufvar(a:bufnr, '&bomb', 0) 418 elseif a:charset == "utf-8-bom" 419 call setbufvar(a:bufnr, '&fileencoding', 'utf-8') 420 call setbufvar(a:bufnr, '&bomb', 1) 421 elseif a:charset == "latin1" 422 call setbufvar(a:bufnr, '&fileencoding', 'latin1') 423 call setbufvar(a:bufnr, '&bomb', 0) 424 elseif a:charset == "utf-16be" 425 call setbufvar(a:bufnr, '&fileencoding', 'utf-16be') 426 call setbufvar(a:bufnr, '&bomb', 1) 427 elseif a:charset == "utf-16le" 428 call setbufvar(a:bufnr, '&fileencoding', 'utf-16le') 429 call setbufvar(a:bufnr, '&bomb', 1) 430 endif 431 432 let l:new_fenc = getbufvar(a:bufnr, "&fileencoding") 433 434 " If all we did was change the fileencoding from the default to a copy 435 " of the default, we didn't actually modify the file. 436 if !l:orig_modified && (l:orig_fenc ==# '') && (l:new_fenc ==# l:orig_enc) 437 if g:EditorConfig_verbose 438 echo 'Setting nomodified on buffer ' . a:bufnr 439 endif 440 call setbufvar(a:bufnr, '&modified', 0) 441 endif 442 endfunction 443 444 function! s:ApplyConfig(bufnr, config) abort 445 if g:EditorConfig_verbose 446 echo 'Options: ' . string(a:config) 447 endif 448 449 if s:IsRuleActive('indent_style', a:config) 450 if a:config["indent_style"] == "tab" 451 call setbufvar(a:bufnr, '&expandtab', 0) 452 elseif a:config["indent_style"] == "space" 453 call setbufvar(a:bufnr, '&expandtab', 1) 454 endif 455 endif 456 457 if s:IsRuleActive('tab_width', a:config) 458 let l:tabstop = str2nr(a:config["tab_width"]) 459 call setbufvar(a:bufnr, '&tabstop', l:tabstop) 460 else 461 " Grab the current ts so we can use it below 462 let l:tabstop = getbufvar(a:bufnr, '&tabstop') 463 endif 464 465 if s:IsRuleActive('indent_size', a:config) 466 " if indent_size is 'tab', set shiftwidth to tabstop; 467 " if indent_size is a positive integer, set shiftwidth to the integer 468 " value 469 if a:config["indent_size"] == "tab" 470 call setbufvar(a:bufnr, '&shiftwidth', l:tabstop) 471 if type(g:EditorConfig_softtabstop_tab) != type([]) 472 call setbufvar(a:bufnr, '&softtabstop', 473 \ g:EditorConfig_softtabstop_tab > 0 ? 474 \ l:tabstop : g:EditorConfig_softtabstop_tab) 475 endif 476 else 477 let l:indent_size = str2nr(a:config["indent_size"]) 478 if l:indent_size > 0 479 call setbufvar(a:bufnr, '&shiftwidth', l:indent_size) 480 if type(g:EditorConfig_softtabstop_space) != type([]) 481 call setbufvar(a:bufnr, '&softtabstop', 482 \ g:EditorConfig_softtabstop_space > 0 ? 483 \ l:indent_size : g:EditorConfig_softtabstop_space) 484 endif 485 endif 486 endif 487 488 endif 489 490 if s:IsRuleActive('end_of_line', a:config) && 491 \ getbufvar(a:bufnr, '&modifiable') 492 if a:config["end_of_line"] == "lf" 493 call setbufvar(a:bufnr, '&fileformat', 'unix') 494 elseif a:config["end_of_line"] == "crlf" 495 call setbufvar(a:bufnr, '&fileformat', 'dos') 496 elseif a:config["end_of_line"] == "cr" 497 call setbufvar(a:bufnr, '&fileformat', 'mac') 498 endif 499 endif 500 501 if s:IsRuleActive('charset', a:config) && 502 \ getbufvar(a:bufnr, '&modifiable') 503 call s:SetCharset(a:bufnr, a:config["charset"]) 504 endif 505 506 augroup editorconfig_trim_trailing_whitespace 507 autocmd! BufWritePre <buffer> 508 if s:IsRuleActive('trim_trailing_whitespace', a:config) && 509 \ get(a:config, 'trim_trailing_whitespace', 'false') ==# 'true' 510 execute 'autocmd BufWritePre <buffer=' . a:bufnr . '> call s:TrimTrailingWhitespace()' 511 endif 512 augroup END 513 514 if s:IsRuleActive('insert_final_newline', a:config) 515 if exists('+fixendofline') 516 if a:config["insert_final_newline"] == "false" 517 call setbufvar(a:bufnr, '&fixendofline', 0) 518 else 519 call setbufvar(a:bufnr, '&fixendofline', 1) 520 endif 521 elseif exists(':SetNoEOL') == 2 522 if a:config["insert_final_newline"] == "false" 523 silent! SetNoEOL " Use the PreserveNoEOL plugin to accomplish it 524 endif 525 endif 526 endif 527 528 " highlight the columns following max_line_length 529 if s:IsRuleActive('max_line_length', a:config) && 530 \ a:config['max_line_length'] != 'off' 531 let l:max_line_length = str2nr(a:config['max_line_length']) 532 533 if l:max_line_length >= 0 534 call setbufvar(a:bufnr, '&textwidth', l:max_line_length) 535 if g:EditorConfig_preserve_formatoptions == 0 536 " setlocal formatoptions+=tc 537 let l:fo = getbufvar(a:bufnr, '&formatoptions') 538 if l:fo !~# 't' 539 let l:fo .= 't' 540 endif 541 if l:fo !~# 'c' 542 let l:fo .= 'c' 543 endif 544 call setbufvar(a:bufnr, '&formatoptions', l:fo) 545 endif 546 endif 547 548 if exists('+colorcolumn') 549 if l:max_line_length > 0 550 if g:EditorConfig_max_line_indicator == 'line' 551 " setlocal colorcolumn+=+1 552 let l:cocol = getbufvar(a:bufnr, '&colorcolumn') 553 if !empty(l:cocol) 554 let l:cocol .= ',' 555 endif 556 let l:cocol .= '+1' 557 call setbufvar(a:bufnr, '&colorcolumn', l:cocol) 558 elseif g:EditorConfig_max_line_indicator == 'fill' && 559 \ l:max_line_length < getbufvar(a:bufnr, '&columns') 560 " Fill only if the columns of screen is large enough 561 call setbufvar(a:bufnr, '&colorcolumn', 562 \ join(range(l:max_line_length+1, 563 \ getbufvar(a:bufnr, '&columns')), 564 \ ',')) 565 elseif g:EditorConfig_max_line_indicator == 'exceeding' 566 call setbufvar(a:bufnr, '&colorcolumn', '') 567 for l:match in getmatches() 568 if get(l:match, 'group', '') == 'ColorColumn' 569 call matchdelete(get(l:match, 'id')) 570 endif 571 endfor 572 call matchadd('ColorColumn', 573 \ '\%' . (l:max_line_length + 1) . 'v.', 100) 574 elseif g:EditorConfig_max_line_indicator == 'fillexceeding' 575 let &l:colorcolumn = '' 576 for l:match in getmatches() 577 if get(l:match, 'group', '') == 'ColorColumn' 578 call matchdelete(get(l:match, 'id')) 579 endif 580 endfor 581 call matchadd('ColorColumn', 582 \ '\%'. (l:max_line_length + 1) . 'v.\+', -1) 583 endif 584 endif 585 endif 586 endif 587 588 call editorconfig#ApplyHooks(a:config) 589 endfunction 590 591 " }}}1 592 593 function! s:TrimTrailingWhitespace() " {{{1 594 " Called from within a buffer-specific autocmd, so we can use '%' 595 if getbufvar('%', '&modifiable') 596 " don't lose user position when trimming trailing whitespace 597 let s:view = winsaveview() 598 try 599 silent! keeppatterns keepjumps %s/\s\+$//e 600 finally 601 call winrestview(s:view) 602 endtry 603 endif 604 endfunction " }}}1 605 606 function! s:IsRuleActive(name, config) " {{{1 607 return index(g:EditorConfig_disable_rules, a:name) < 0 && 608 \ has_key(a:config, a:name) 609 endfunction "}}}1 610 611 let &cpo = s:saved_cpo 612 unlet! s:saved_cpo 613 614 " vim: fdm=marker fdc=3