Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to quickly change variable names in Vim?

I am using Vim to read through a lot of C and Perl code containing many single letter variable names.

It would be nice to have some command to change the name of a variable to something more meaningful while I’m in the process of reading the code, so that I could read the rest of it faster.

Is there some command in Vim which could let me do this quickly?

I don’t think regexes would work because:

  1. the same single letter name might have different purposes in different scoping blocks; and

  2. the same combination of letters could be part of another longer variable name, a string literal, or a comment.

Are there any known solutions?

like image 261
Aditya Mukherji Avatar asked Feb 28 '09 07:02

Aditya Mukherji


People also ask

How do you change multiple variable names?

Place the cursor inside a variable you want to rename and press Ctrl + R . Then type other name and editor will change all occurrences of that variable.

How do you replace a variable name in VS code?

Renaming is a common operation related to refactoring source code and VS Code has a separate Rename Symbol command (F2). Some languages support rename symbol across files. Press F2 and then type the new desired name and press Enter. All usages of the symbol will be renamed, across files.


1 Answers

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.

like image 94
Mykola Golubyev Avatar answered Oct 15 '22 13:10

Mykola Golubyev