Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing trailing white space only for edited lines

I had added the following function in my .vimrc for removing trailing white spaces just before saving

fun! <SID>StripTrailingWhitespaces()                                            
    let l = line(".")                                                           
    let c = col(".")                                                            
    %s/\s\+$//e                                                                 
    call cursor(l, c)                                                           
endfun                                                                          

autocmd BufWritePre *.h :call <SID>StripTrailingWhitespaces()
autocmd BufWritePre *.cpp :call <SID>StripTrailingWhitespaces()
autocmd BufWritePre *.c :call <SID>StripTrailingWhitespaces()

It works really well. However, in certain cases I would like to remove trailing white spaces only from lines that I have edited. This is to ensure that my diff output looks sane as for certain legacy code files almost all lines have trailing back spaces and I do not want to burden my code reviewer with unnecessary diff.

diff -b is not a solution right now since it also ignores white spaces from anywhere in a line and sometimes that change is important enough to be include in the diff output.

So my question is - is it possible to strip trailing white spaces from only the lines that have been edited in this session in a file in vim?

like image 742
ghostkadost Avatar asked Nov 29 '11 11:11

ghostkadost


1 Answers

One possibility would be to use autocmd InsertLeave to strip white spaces from current line every time you leave insert mode:

autocmd InsertLeave *.[ch] :call <SID>StripTrailingWhitespaces()

, and change substitute command of StripTrailingWhitespaces() function changed to

s/\s\+$//e

It will work if all lines that you include doesn't end in white spaces, only the last one. It will possible change lines that you didn't modified, if you enter and exit insert mode (i followed by ESC).

This solution can be changed to work if you include lines that does end in white space (pasted lines from legacy code, for example):

autocmd InsertEnter *.[ch] :let b:insert_start = line('.')
autocmd InsertLeave *.[ch] :call <SID>StripTrailingWhitespaces()

fun! StripTrailingWhitespaces()
    let original_cursor = getpos('.')
    exe b:insert_start . ',.s/\s\+$//e'
    call setpos('.', original_cursor)
endfun     

If the replacement on lines due to enter and exit insert mode (i followed by ESC) is a problem then the solution could save b:changedtick-variable when entering insert mode and check it when leaving insert mode to detect changes.

like image 154
mMontu Avatar answered Sep 28 '22 17:09

mMontu