How to quickly change variable names in Vim?

前端 未结 7 1893
庸人自扰
庸人自扰 2020-12-12 08:55

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 va

7条回答
  •  一整个雨季
    2020-12-12 09:07

    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. / - will insert pattern that match variable name (that name you were on before pressing gd). /newname/gc - 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////gc
    
    " For global replace
    nnoremap gR gD:%s////gc
    

    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.

提交回复
热议问题