是否有任何记录在 R 中使用ctags?这会有用吗?实施起来会不会很困难?
具体来说,我刚刚开始使用 Vim。能够在一个文件中编写 R 函数,在另一个文件(例如,Rnw 文件、测试文件或其他脚本)中使用该函数,并能够使用 Ctrl+] 导航到该函数,这将是很酷的资源。
这是对 Henrico 答案的修改,可以通过将以下代码复制并粘贴到一个人的 ~/.ctags 文件中来实现。Henrico 的代码不适用于缩进函数,但下面的代码可以。
--langdef=R
--langmap=r:.R.r
--regex-R=/^[ \t]*"?([.A-Za-z][.A-Za-z0-9_]*)"?[ \t]*<-[ \t]function/\1/f,Functions/
--regex-R=/^"?([.A-Za-z][.A-Za-z0-9_]*)"?[ \t]*<-[ \t][^f][^u][^n][^c][^t][^i][^o][^n]/\1/g,GlobalVars/
--regex-R=/[ \t]"?([.A-Za-z][.A-Za-z0-9_]*)"?[ \t]*<-[ \t][^f][^u][^n][^c][^t][^i][^o][^n]/\1/v,FunctionVariables/
这允许使用 ctags 和函数识别变量。如果您使用的是 taglist vim 插件,那么它可以让您区分全局变量和其他变量。此外,如果您使用的是 taglist,那么您需要将以下内容粘贴到您的 vimrc 中。
let tlist_r_settings = 'R;f:Functions;g:GlobalVariables;v:FunctionVariables'
这是我的主目录中的 .ctags 文件的内容。我在互联网的某个地方找到了它。使用它,您可以为 vim 生成标签文件。
--langdef=Splus
--langmap=Splus:.s.S.R.r.q
--regex-Splus=/^[ \t]+"?([.A-Za-z][.A-Za-z0-9_]*)"?[\t]*<-[\t]*function/\1/
--regex-Splus=/^"?([.A-Za-z][.A-Za-z0-9_]*)"?[ \t]*<-/\1/
可能您可以阅读如何向 ctags添加对新语言的支持。
rtags() 是从我目前看到的为 R 代码生成标签的最佳方法,因为它将考虑所有不同的分配方式,例如:
ok = c("<-", "=", "<<-", "assign",
"setGeneric", "setGroupGeneric", "setMethod",
"setClass", "setClassUnion")
使用 rtags() 的示例:
path <- "~/path/to/project"
rtags(path=path,
pattern = "[.]*\\.[RrSs]$",
keep.re = ".", # the value ('/R/') in the help page will only run through the codes in R/ folder.
verbose = TRUE,
ofile = file.path(path, 'TAGS'),
append = FALSE,
recursive = TRUE)
Universal-ctags有一个 R 解析器。
$ cat input.r
add <- function (x, y) {
3 -> z
return(x + y + z)
}
add (3, 4)
$ ./ctags --quiet --options=NONE -o - --kinds-R='*' --fields=+S input.r
add input.r /^add <- function (x, y) {$/;" f signature:(x, y)
x input.r /^add <- function (x, y) {$/;" z function:add
y input.r /^add <- function (x, y) {$/;" z function:add
z input.r /^ 3 -> z$/;" v function:add
此外,ctags 实现支持 R6Class 和 S4Class。
实际上,我认为rtags()
可以在 vim 中使用。
我使用 nvim-r 插件(可在https://www.vim.org/scripts/script.php?script_id=2628获得),并在我的~/.vimrc
文件中有以下内容:
:command! Rtags :!Rscript -e 'rtags(path="./", recursive=TRUE, ofile="TAGS")'
使用此设置,:Rtags
在 vim 中使用会重建标签,然后例如g]
当鼠标悬停在某个单词上时,会找到该单词的定义。
正如其他rtags()
+所提到的,可以为 vimetags2ctags()
生成一个(请参阅 参考资料)。您可以为 vim 创建一个自定义命令,以便它在 R 中使用. 为此,请将其放入您的:tagsfile
:h tags-and-searches
rtags()
Rscript
.vimrc
:command! Rtags :!Rscript -e 'rtags(path="./", recursive=TRUE, ofile="RTAGS")' -e 'etags2ctags("RTAGS", "rtags")' -e 'unlink("RTAGS")'
set tags+=rtags
现在,当你这样做时,:Rtags
vim 将运行外部进程Rscript
(它当然必须在其中PATH
)并评估rtags(path="./", recursive=TRUE, ofile="RTAGS");etags2ctags("RTAGS", "rtags");unlink("RTAGS")
. rtags()
将生成一个Emacs 标签格式RTAGS
的文件,然后将其转换为vim 可以读取的文件。删除文件,因为 vim 不需要它。etags2ctags()
rtags
unlink()
RTAGS
使set tags+=rtags
vim 搜索rtags
除了通常的文件之外的tags
文件(参见:h tags-and-searches
)