Reputation: 60056
What is a good way to automate substitute commands in vim?
Suppose I have something like:
s/foo/bar/g
except much more complex and I want to run it on selected ranges without having to type the substitute command?
How can I save the substitute command and give it short convenient name that I can invoke it by?
Upvotes: 0
Views: 258
Reputation: 4733
You could try mapping below pressing the space key twice on a particular word will autofill the substitute command with the word under the cursor and wait for you to enter the replacement name
" super quick search and replace
nnoremap <Space><Space> :'{,'}s/\<<C-r>=expand('<cword>')<CR>\>/
nnoremap <Space>% :%s/\<<C-r>=expand('<cword>')<CR>\>/
in your case just put the cursor on the foo word and press the space bar twice. You should see
:'{,'}s/\<foo\>/
Then type the word bar
'{,'}s/\<foo\>/bar
all occurrences of foo will be replaced by bar
Upvotes: 1
Reputation: 195029
You can create a function with range supported, and in the function do the substitution. Also create a custom command to call the function with range.
However the easiest way I think, is creating an abbrev
in your vimrc file:
cab RR s/foo/bar/g
thus, when you selected lines, or in command line gave ranges (like 3,5 or % ...
) you press RR<space>
the s/foo/bar/g
will be filled automatically. You can do some adjustment or just press enter let it go.
Upvotes: 1