How can you automatically remove trailing whitespace in vim

后端 未结 13 2128
星月不相逢
星月不相逢 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 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.

提交回复
热议问题