Tip #721: Auto remove white space when saving
| tip karma
Rating 33/15, Viewed by 1402
Read and edit this tip on the
Vim tip wiki.
The wiki may have a more recent version of this tip.
||May 16, 2004 20:58
||as of Vim:
I think it would be convenient to have Vim automatically remove the white spaces before saving to a file.
Just put the following line in your vimrc file. Everytime you issue a :w command, Vim will automatically have white spaces removed before saving.
autocmd BufWritePre * :%s/\s\+$//
I've tried using FileWritePre, but didn't work. Anybody know why?
<< delete word in FRONT of cursor |
useful mapping for <space> in normal mode: :nnoremap <space> i<space><esc> >>
May 17, 2004 3:07
|Sorry, current command will cause error when no trailing white space in the file. The correct command would be:
autocmd BufWritePre * :%s/\s*$//
May 17, 2004 8:17
|Actually, the original command with a different modification is better:
autocmd BufWritePre * :%s/\s\+$//e
The * causes a replacement on EVERY line, even those that don't actually contain trailing blanks. The + is better, and the e prevents the error.
I use the (possibly overkill) version here:
if ( GetVar( "noStripSpaces" ) != 1 )
" Remove trailing blanks upon saving except from lines containing sigdashes
au BufWritePre * silent! call StripTrailingSpaces()
The Mark() function is from Benji's foo.vim and is used simply to restore the cursor location when done. The variable 'noStripSpaces' can be set to 1 to prevent the stripping of spaces for a file if you like (:let b:noStripSpaces=1); this uses my getVar.vim script. (Both scripts can be found on this site.)
The substitute I use leaves lines that consist of -- followed by spaces (used to separate email signatures from the rest of the text): I don't use them anywhere else so it doesn't cause me any problems.
May 17, 2004 10:52
|Remember you can also specify filetype
autocmd BufWritePre *.pl :%s/\s\+$//e
or how about having this operate when you Enter the file:-
autocmd BufEnter *.php :%s/\s\+$//e
And let's get rid of those pesky ^M at the same time
autocmd BufEnter *.php :%s/[ \t\r]\+$//e
May 24, 2004 2:34
When I have the strip trailing spaces regex in my vimrc file, I get a prompt to save the file when I have made
no changes as a write is occuring to all lines. Is there a way of having a function like the StripTrailingSpaces()
function that sets a variable that I can check when exiting to see if any changes have occured?