How to automatically strip trailing spaces on save in Vi and Vim?

Is there a .vimrc setting to automatically remove trailing whitespace when saving a file?

Ideally (to be safe) I would like to only have this functionality for certain files, e.g. *.rb

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This works (in the .vimrc file) for all files:

autocmd BufWritePre * :%s/s+$//e

This works (in the .vimrc file) for just ruby(.rb) files:

autocmd BufWritePre *.rb :%s/s+$//e

Method 2

To keep cursor position use something like:

function! <SID>StripTrailingWhitespaces()
    let l = line(".")
    let c = col(".")
    %s/s+$//e
    call cursor(l, c)
endfun

else cursor would end up at beginning of line of last replace after save.

Example: You have a space at end of line 122, you are on line 982 and
enter :w. Not restoring position, would result in cursor ending up at beginning of line 122 thus killing work flow.

Set up call to function using autocmd, some examples:

" Using file extension
autocmd BufWritePre *.h,*.c,*.java :call <SID>StripTrailingWhitespaces()

" Often files are not necessarily identified by extension, if so use e.g.:
autocmd BufWritePre * if &ft =~ 'sh|perl|python' | :call <SID>StripTrailingWhitespaces() | endif

" Or if you want it to be called when file-type i set
autocmd FileType sh,perl,python  :call <SID>StripTrailingWhitespaces()

" etc.

One can also use, but not needed in this case, getpos() by:

let save_cursor = getpos(".")
" Some replace command
call setpos('.', save_cursor)

" To list values to variables use:
let [bufnum, lnum, col, off] = getpos(".")

Method 3

My DeleteTrailingWhitespace plugin does this and, in contrast to the various simple :autocmds floating around, also handles special cases, can query the user, or abort writes with trailing whitespace.

The plugin page contains links to alternatives; there’s also a large discussion on the Vim Tips Wiki.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x