How can you automatically remove trailing whitespace in vim

后端 未结 13 2069
星月不相逢
星月不相逢 2020-12-02 03:39

I am getting \'trailing whitespace\' errors trying to commit some files in git.

I want to remove these trailing whitespace characters automatically right before I sa

相关标签:
13条回答
  • 2020-12-02 03:59

    This is how I'm doing it. I can't remember where I stole it from tbh.

    autocmd BufWritePre * :call <SID>StripWhite()
    fun! <SID>StripWhite()
        %s/[ \t]\+$//ge
        %s!^\( \+\)\t!\=StrRepeat("\t", 1 + strlen(submatch(1)) / 8)!ge
    endfun
    
    0 讨论(0)
  • 2020-12-02 04:00

    I saw this solution in a comment at VIM Wikia - Remove unwanted spaces

    I really liked it. Adds a . on the unwanted white spaces.

    Put this in your .vimrc

    " Removes trailing spaces
    function TrimWhiteSpace()
      %s/\s*$//
      ''
    endfunction
    
    set list listchars=trail:.,extends:>
    autocmd FileWritePre * call TrimWhiteSpace()
    autocmd FileAppendPre * call TrimWhiteSpace()
    autocmd FilterWritePre * call TrimWhiteSpace()
    autocmd BufWritePre * call TrimWhiteSpace()
    
    0 讨论(0)
  • 2020-12-02 04:00

    The other approaches here somehow didn't work for me in MacVim when used in the .vimrc file. So here's one that does and highlights trailing spaces:

    set encoding=utf-8
    set listchars=trail:·
    set list
    
    0 讨论(0)
  • 2020-12-02 04:01

    A solution which simply strips trailing whitespace from the file is not acceptable in all circumstances. It will work in a project which has had this policy from the start, and so there are no such whitespace that you did not just add yourself in your upcoming commit.

    Suppose you wish merely not to add new instances of trailing whitespace, without affecting existing whitespace in lines that you didn't edit, in order to keep your commit free of changes which are irrelevant to your work.

    In that case, with git, you can can use a script like this:

    #!/bin/sh
    
    set -e # bail on errors
    
    git stash save commit-cleanup
    git stash show -p | sed '/^\+/s/ *$//' | git apply
    git stash drop
    

    That is to say, we stash the changes, and then filter all the + lines in the diff to remove their trailing whitespace as we re-apply the change to the working directory. If this command pipe is successful, we drop the stash.

    0 讨论(0)
  • 2020-12-02 04:06

    I also usually have a :

    match Todo /\s\+$/
    

    in my .vimrc file, so that end of line whitespace are hilighted.

    Todo being a syntax hilighting group-name that is used for hilighting keywords like TODO, FIXME or XXX. It has an annoyingly ugly yellowish background color, and I find it's the best to hilight things you don't want in your code :-)

    0 讨论(0)
  • 2020-12-02 04:07

    I found the answer here.

    Adding the following to my .vimrc file did the trick.

    autocmd BufWritePre *.py :%s/\s\+$//e
    
    0 讨论(0)
提交回复
热议问题