1

I want to define a global search and replace with confirmation command, something like:

command Gfr :s/<parameter1>/<parameter2>/gc

So I can type:

:Gfr foo bar

and Vim will find all occurrences of 'foo' in the document and ask for each whether I want to replace it with 'bar'.

Googling has led me to some tantalising hints that this is possible, but no definitive answer.

4
  • Why google when you can simply do :help :command in Vim itself and scroll around for five minutes?
    – romainl
    Commented Oct 10, 2023 at 8:42
  • BTW, the way your command is written it will operate on the current line only. To have it work on the entire buffer, use :%s. I recommend you familiarize yourself with :s instead of wrapping it in a command of your own. It quickly becomes second nature.
    – Friedrich
    Commented Oct 10, 2023 at 8:56
  • @romainl - I guess I'm just so used to finding my answers on StackExchange through Google that it's become a reflex; I keep forgetting vim has some pretty extensive documentation built in!
    – David Shaw
    Commented Oct 10, 2023 at 9:07
  • @Friedrich - thank you for that catch. And I agree, I really should set some time aside to learn :s. This question is really more a learning exercise for customising vim.
    – David Shaw
    Commented Oct 10, 2023 at 9:09

1 Answer 1

0

I would do:

function! Gfr(search, replace)
  execute '%s/' .. a:search .. '/' .. a:replace .. '/gc'
endfunction

command! -nargs=+ Gfr call Gfr(<f-args>)

To pass multiple parameters I propose to use a function and the <f-args> placeholder that converts the argument part of the command into a list of strings that a function can take.

The -nargs=+ force the user to have at least one argument (you cannot force exactly 2 with that parameters)

2
  • 1
    Works like a charm, thank you.
    – David Shaw
    Commented Oct 10, 2023 at 10:28
  • Thanks for the feedback :-) Welcome to Vim ;-) Commented Oct 10, 2023 at 10:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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