Vinz
Vinz

Reputation: 6057

vim 7.4 saving substitution pattern and replacement

I have a function in my .vimrc file to remove any whitespace at the end of my lines:

" Remove trailing space on write
function! <SID>StripTrailingWhitespaces()
    let _s=@/
    let l = line(".")
    let c = col(".")
    %s/\s\+$//e
    let @/=_s
    call cursor(l, c)
endfu

With this function, the search pattern @/ is saved and restored, so I can continue to search (n) my previous pattern. But if I was in the middle of a search and replace, using &, it now search correctly but replace with an empty string.

I read that vim 8 has a :keeppatterns option that might help me (I didn't check yet) but I'm stuck with vim 7.4 for the time being.

Is is possible to save and restore the 'replacement' part of a :s command ?

Upvotes: 0

Views: 474

Answers (1)

pappix
pappix

Reputation: 91

As you mentioned the :s is a command not a search, thus if you want to retrieve it you just need to access the command history: : and up

( According to vim help:keeppatterns {command} allows to execute command without adding anything to the search pattern, I don't believe it would be much useful to you if I understand correctly you use case)

If you want to still use a "column command" :@: will still work after the function run.

When you re-run with & vim will re-run the last search with the last substitute. Since the search history has been restored in the function it will use the previous search but will still apply the replace with the last replace (the one in the function) thus resulting in a replace with empty string.

Upvotes: 1

Related Questions