Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you automatically remove trailing whitespace in vim

People also ask

How do I get rid of trailing space in Linux?

sed 's/\s\+$/ filename.

How will you remove all leading and trailing whitespace in string?

We can eliminate the leading and trailing spaces of a string in Java with the help of trim(). trim() method is defined under the String class of java.

Which syntax is used for removing leading and trailing whitespaces?

String strip() – Remove Leading and Trailing White Spaces.


I found the answer here.

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

autocmd BufWritePre *.py :%s/\s\+$//e

The e flag at the end means that the command doesn't issue an error message if the search pattern fails. See :h :s_flags for more.


Compilation of above plus saving cursor position:

function! <SID>StripTrailingWhitespaces()
  if !&binary && &filetype != 'diff'
    let l:save = winsaveview()
    keeppatterns %s/\s\+$//e
    call winrestview(l:save)
  endif
endfun

autocmd FileType c,cpp,java,php,ruby,python autocmd BufWritePre <buffer> :call <SID>StripTrailingWhitespaces()

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

autocmd BufWritePre,FileWritePre,FileAppendPre,FilterWritePre *
  \ :call <SID>StripTrailingWhitespaces()

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 :-)


I both highlight existing trailing whitespace and also strip trailing whitespace.

I configure my editor (vim) to show white space at the end, e.g.

enter image description here

with this at the bottom of my .vimrc:

highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()

and I 'auto-strip' it from files when saving them, in my case *.rb for ruby files, again in my ~/.vimrc

function! TrimWhiteSpace()
    %s/\s\+$//e
endfunction
autocmd BufWritePre     *.rb :call TrimWhiteSpace()

Here's a way to filter by more than one FileType.

autocmd FileType c,cpp,python,ruby,java autocmd BufWritePre <buffer> :%s/\s\+$//e