How to quickly change variable names in Vim?

前端 未结 7 1891
庸人自扰
庸人自扰 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:21

    Put this in your .vimrc

    " Function to rename the variable under the cursor
    function! Rnvar()
      let word_to_replace = expand("")
      let replacement = input("new name: ")
      execute '%s/\(\W\)' . word_to_replace . '\(\W\)/\1' . replacement . '\2/gc'
    endfunction
    

    Call it with :call Rnvar()

    expand("") gets the word under the cursor. The search string uses % for file-scope, and the \(\W\) patterns look for non-word characters at the boundary of the word to replace, and save them in variables \1 and \2 so as to be re-inserted in the replacement pattern.

提交回复
热议问题