0

In the text below, if I want to replace book1 and book2 with pen I could yark pen and go to the beginning of the 2 and 3 lines and hit . (dot) to replace the words.

pen;
book1;
book2;
book3;

but, how can I replace multiple words with yanked text? For example, I want to replace book 1 and book 2 with pen

Before:

pen;
book 1;
book 2;
book 3;

After:

pen;
pen;
pen;
book 3;

Is it possible to replace book 1 and book 2 without yanking the word pen twice? Maybe a keybind you think is good?

  • 1
    Using vi to edit is certainly normal and on-topic here. Feel free to delete here and re-ask at vi.SE if you'd prefer, though. – Jeff Schaller Sep 28 '19 at 20:15
1

This reddit comment is the best solution I got. Pretty neat.

I defined a command to substitute text without changing default register. Maybe this will serve you too. It might be based on this or this, I don't really remember where I got the idea, but I saw it somewhere before implementing.

nnoremap <silent> cp :let g:substitutemotion_reg = v:register
            \ <bar> set opfunc=SubstituteMotion<CR>g@

" substitute {motion} text with contents of a register function!
SubstituteMotion(type, ...)
    let l:reg = g:substitutemotion_reg
    if a:0
        " visual mode, use '< and '> marks
        silent exe "normal! `<" . a:type . "`>\"_c\<c-r>" . l:reg . "\<esc>"
    elseif a:type == 'line'
        " linewise
        silent exe "normal! '[V']\"_c\<c-r>" . l:reg . "\<esc>"
    elseif a:type == 'block'
        " blockwise-visual
        silent exe "normal! `[\<C-V>`]\"_c\<c-r>" . l:reg . "\<esc>"
    else
        " characterwise
        silent exe "normal! `[v`]\"_c\<c-r>" . l:reg . "\<esc>"
    endif endfunction 

To use it, type something like cpi( which will lead to replacement of the text within closest pair of parenthesis with the contents of default register.

|improve this answer|||||
0

I need this so often, I wrote a plugin to simplify and allow maximum speed: ReplaceWithRegister.

This plugin offers a two-in-one gr command that replaces text covered by a {motion} / text object, entire line(s) or the current selection with the contents of a register; the old text is deleted into the black-hole register, i.e. it's gone. It transparently handles many corner cases and allows for a quick repeat via the standard . command. Should you not like it, its page has links to alternatives. (It works just like @s1n7az's snippet, but as a plugin is more sophisticated and robust.)

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.