如何在 Vim 中快速更改变量名? [英] How to quickly change variable names in Vim?

查看:92
本文介绍了如何在 Vim 中快速更改变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vim 阅读大量包含许多单字母变量名的 C 和 Perl 代码.

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.

Vim 中是否有一些命令可以让我快速执行此操作?

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

我不认为正则表达式会起作用,因为:

I don’t think regexes would work because:

  1. 相同的单字母名称在不同的作用域块中可能有不同的用途;和

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

相同的字母组合可以是另一个较长的变量名称、字符串文字或注释的一部分.

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

是否有任何已知的解决方案?

Are there any known solutions?

推荐答案

以下是如何重命名定义在当前作用域{}中的变量.

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

将光标移动到变量用法.按 gd.这意味着 - 将光标移动到定义.现在按 [{ - 这将带您进入范围开始.按 V - 将打开可视线选择.按 % - 将跳转到相反的 } 从而选择整个范围.按 :s/ - 替代命令的开始.<C-R>/ - 将插入匹配变量名称的模式(您在按下 gd 之前所在的名称)./newname/gc<CR> - 将在每次匹配时启动搜索并替换为确认.

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.

以下是最终的映射:

" 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>

把它放到你的 .vimrc 或者直接执行.在局部变量上按下 gr 后将带您到 :s 命令,您只需输入 new_variable_name 并按 Enter.

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.

这篇关于如何在 Vim 中快速更改变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆