I am trying to encapsulate variables with a method. For example, I am converting this:

return variable1;

To this:

return verify(variable1);

Is there a way to quickly repeat this action (ideally with the dot command or a macro of some sort) for other variables?

  • 3
    Something like :%s/return \(\i*\);/return verify(\1);/?
    – muru
    Apr 27, 2016 at 21:43
  • @muru omg, that was brilliant!!
    – AgileNinja
    Apr 27, 2016 at 22:18

2 Answers 2


If you already have the surround plugin, you can do ysiwfverify<CR>. Tim Pope has another plugin called repeat that lets you repeat surround commands with ..

Without any plugin or setup, you can simply do ciwverify(<C-r><C-o>")<Esc> and repeat with ..

  • 2
    @romainl Nice, +1! Just a minor suggestion, for the 2nd solution ciwverify(<C-r>")<Esc>. When I use it, the dot register is filled with verify(variable1) (assuming the word under the cursor was variable1). Which means that when I hit dot on a second variable, let's say variable2, it's replaced with verify(variable1) whereas I wanted verify(variable2). However, if I prefix the unnamed register with <C-o> (or <C-p>), it works because then the dot register contains verify(^R^O"). So, to make the 2nd solution repeatable with dot, ciwverify(<C-r><C-o>")<esc> could be used. Apr 28, 2016 at 5:11
  • @user9433424, very good point. Let me update my answer.
    – romainl
    Apr 28, 2016 at 5:46

Another solution is to use macros (I love macros!).

First put return in the search register: /return<CR> or :let @/="return"

Then record your macro:


which can be decomposed like this

qq start recording in the register q
n  go to the next occurence of the word in the search register (here 'return')
w  go to the beginning of the word following 'return'
i  enter insert mode
verify( input the function which will encapsulate your variable
e  go to the end of the word after the bracket
a  enter insert mode after the word
)  input the closing bracket
q  stop recording

You can then execute the macro with @q and repeat it with @@.

Edit Thanks to @Nobe4 you can even make it one keystroke shorter this way:


<c-o> allows to go into normal mode for only one command and then go back automatically to insert mode.

  • 1
    instead of using <Esc>ea you can use <c-o>w :)
    – nobe4
    Apr 28, 2016 at 7:49
  • @Nobe4 here comes the vimgolf :-) Thanks for the suggestion I'll edit my answer.
    – statox
    Apr 28, 2016 at 7:51

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.