0

I've discovered that I can edit the .vimrc file to create custom commands and would like to create simpler search and replace alternative commands, but have no idea how to edit %s/foo/bar/gc so that it uses the words I pass after the :command in vim instead of 'foo' and 'bar.' Would prefer a simple solution not requiring me to learn vimscript.

3

If you are using the :%s command, you are already using some very simple VimScript. So much for not learning it :)

If you want to create your custom command, you can use e.g.

com! -nargs=1 Replace :%s/<args>/gc

This defines a new command :Replace and you can use :Replace foo/bar to have all foo be replaced by bar across the complete document.

This is basically as simple and straight forward as possible, however this requires you to always supply an argument in the form searchterm/replaceterm e.g. you need to include the slash, so that dynamically a new command can be build up.

You could get very much sophisticated however, e.g. add some error management, use 2 arguments for searching and replacing, use a specific magic setting, so that it will handle e.g. . and \ correctly or how to handle the / if it appears in the search or replace term.

This however requires using a function and doing a bit more of processing of the arguments and is way much out of scope, if you do not want to learn VimScript.

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.