Is there a flag for: s [ubstitute] in Vim that won't save the template?

I am trying to create autocmdone that will replace all the spaces in the file when I exit insert mode. However, AFAIK, which would make Vim remember the pattern and delete what was already there.

" Add function for remove tailing whitespaces
command! CleanupTrailingSpaces :%s/\s\+$//ge | :nohlsearch
autocmd InsertLeave * :CleanupTrailingSpaces

Is there a flag for :s[ubstitute]which will not allow saving the template?

+5
source share
2 answers

Such a flag will be useful, but does not yet exist. However, you can save and reset the register as follows:

" Add function for remove tailing whitespaces
command! CleanupTrailingSpaces let reset = @/ | %s/\s\+$//ge | let @/ = reset | nohlsearch
autocmd InsertLeave * :CleanupTrailingSpaces
+8
source

I got something similar from vimcasts . :-)

function! <SID>StripTrailingWhitespaces()
    " Preparation: save last search, and cursor position.
    let _s=@/
    let l = line(".")
    let c = col(".")
    " Do the business:
    %s/\s\+$//e
    " Clean up: restore previous search history, and cursor position
    let @/=_s
    call cursor(l, c)
endfunction

nnoremap <silent> <F5> :call <SID>StripTrailingWhitespaces()<CR>
autocmd BufWritePre *.py,*.js :call <SID>StripTrailingWhitespaces()
+3
source

All Articles