editorconfig / editorconfig-vim

EditorConfig plugin for Vim
http://editorconfig.org
Other
3.14k stars 139 forks source link

Trim trailing whitespace only on modified lines #195

Open FlexW opened 2 years ago

FlexW commented 2 years ago

This will help when working on legacy codebases where one wants to move incrementally to .editorconfig. This mode is also more consistent with indent_style, which operates only on changes.

What are your thoughts? Alternatively, this mode could be made optional.

Fixes: #106

h3xx commented 2 years ago

Maybe if this was a configurable option (e.g. let g:EditorConfig_whitespace_trim_strategy="on_insert" with the default being "on_save" or something), it would be better.

To have this be the default behavior would annoy me. In my initial test, it prevented me from doing something I do on the regular: pasting in normal mode after trailing whitespace.

mmrwoods commented 1 year ago

Hi,

I have the same problem, but I have solved it using https://github.com/ntpeters/vim-better-whitespace, which relies on an external diff command to identify modified lines. Maybe that approach could be copied to editorconfig-vim? Or maybe editorconfig-vim could have an option to set a function or command to use for stripping whitespace which would override the built-in functionality?

FWIW, this is the workaround in my .vimrc...

" Disable editorconfig trim_trailing_whitespace, use better_whitespace
let g:EditorConfig_disable_rules = ['trim_trailing_whitespace']

" Automatically strip whitespace on save using better_whitespace plugin
let g:strip_whitespace_on_save = 1

" Only strip whitespace on modified lines and don't ask for confirmation
let g:strip_only_modified_lines = 1
let g:strip_whitespace_confirm = 0

" Use editorconfig hook to automatically enable/disable whitespace stripping
function! <SID>EditorConfigHook(config)
  try
    let l:trim_trailing_whitespace = a:config->get('trim_trailing_whitespace')
    if l:trim_trailing_whitespace == 'true'
      exec 'EnableStripWhitespaceOnSave'
    elseif l:trim_trailing_whitespace == 'false'
      exec 'DisableStripWhitespaceOnSave'
    endif
  catch
    echo 'EditorConfigHook Failed: ' . v:exception
  endtry
  return 0 " Return 0 to show no error happened
endfunction
call editorconfig#AddNewHook(function('<SID>EditorConfigHook'))

I've been using this for a month or so now and it seems to be working fine (not noticed any performance impact).