How can you automatically remove trailing whitespace in vim

后端 未结 13 2133
星月不相逢
星月不相逢 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:08

    Compilation of above plus saving cursor position:

    fun! StripTrailingWhitespaces()
        let l = line(".")
        let c = col(".")
        keepp %s/\s\+$//e
        call cursor(l, c)
    endfun
    
    autocmd FileType c,cpp,java,php,ruby,python autocmd BufWritePre  :call StripTrailingWhitespaces()
    

    If you want to apply this on save to any file, leave out the second autocmd and use a wildcard *:

    autocmd BufWritePre * :call StripTrailingWhitespaces()
    

提交回复
热议问题