tags:

views:

85

answers:

2

Any idea on how to delete all the spaces and tabs at the end of all my lines in my code using vim? I sometimes use commands to add things at the end of my lines, but sometimes, because of these unexpected blanks (that is, I put these blanks there inadvertently while coding), which serve no purpose whatsoever, these commands don't do the right job... so i'd like to get rid of the blanks once and for all using some vim command. Thanks in advance!

+6  A: 

In vim:

:%s/\s\+$//

Explanation:

  • : command
  • % apply to entire file
  • s search and replace
  • /\s\+$/ regex for one or more whitespace characters followed by the end of a line
  • // replacement value of an empty string
Amber
`\s\+$` is the regular expression, and an empty string is the replacement. `/` is simply a separator. You can use e.g. `_` in its place.
strager
Thanks... I'm familiar with the syntax, didn't know for the whitespace characters though! Anyway, it works :) I'll accept your answer as soon as I can.
Nigu
@strager: I'm aware of that; but it's much easier to represent an empty string when you have delimiters around it. The fact that two `/` characters are included in both the regex portion and the replacement value should probably be a clue that they're not especially a part of either. ;)
Amber
Okay; I guess people can use my comment if they're confused on that point. ;P
strager
+3  A: 

I use this function :

func! DeleteTrailingWS()
  exe "normal mz"
  %s/\s\+$//ge
  exe "normal `z"
endfunc

Leader,w to remove trailing white spaces

noremap <leader>w :call DeleteTrailingWS()<CR>

Remove trailing white spaces when saving a python file:

autocmd BufWrite *.py :call DeleteTrailingWS()
Drasill