How to quickly change variable names in Vim?

The following is how to rename a variable which is defined in the current scope {}.

Move your cursor to the variable usage. Press gd. Which means – move cursor to the definition.
Now Press [{ – this will bring you to the scope begin.
Press V – will turn on Visual Line selection.
Press % – will jump to the opposite } thus will select the whole scope.
Press :s/ – start of the substitute command.
<C-R>/ – will insert pattern that match variable name (that name you were on before pressing gd).
/newname/gc<CR> – will initiate search and replace with confirmation on every match.

Now you have to record a macros or even better – map a key.

Here are the final mappings:

" For local replace
nnoremap gr gd[{V%::s/<C-R>///gc<left><left><left>

" For global replace
nnoremap gR gD:%s/<C-R>///gc<left><left><left>

Put this to your .vimrc or just execute.
After this pressing gr on the local variable will bring you to :s command where you simply should enter new_variable_name and press Enter.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)