Moo*_*per 7 add-in r rstudio magrittr
我写了一个函数来帮助逐步执行管道链.
要使用它,用户必须将指令复制到剪贴板,然后执行该功能,然后移动到控制台继续.
我想构建一个插件,允许我选择指令并在Ctrl + P没有尴尬步骤的情况下运行该函数.
理想情况下,插件会:
我相信它与reprex addin正在做的非常相似,但我不知道从哪里开始,因为我是100%新的插件.
我调查了一下,rstudioapi::getActiveDocumentContext()但没有任何我感兴趣的东西.
我怎样才能做到这一点?
功能
debug_pipe <- function(.expr){
.pchain <-
if (missing(.expr)) readClipboard() # windows only , else try clipr::read_clip()
else deparse(substitute(.expr))
.lhs <- if (grepl("^\\s*[[:alnum:]_.]*\\s*<-",.pchain[1])) {
sub("^\\s*([[:alnum:]_.]*)\\s*<-.*","\\1",.pchain[1])
} else NA
.pchain <- sub("[^%]*<-\\s*","",.pchain) # remove lhs of assignment if exists
.pchain <- paste(.pchain,collapse = " ") # collapse
.pchain <- gsub("\\s+"," ",.pchain) # multiple spaces to single
.pchain <- strsplit(.pchain,"\\s*%>%\\s*")[[1]] # split by pipe
.pchain <- as.list(.pchain)
for (i in rev(seq_along(.pchain))) {
# function to count matches
.f <- function(x) sum(gregexpr(x,.pchain[i],fixed = TRUE)[[1]] != -1)
# check if unbalanced operators
.balanced <-
all(c(.f("{"),.f("("),.f("[")) == c(.f("}"),.f(")"),.f("]"))) &
!.f("'") %% 2 &
!.f('"') %% 2
if (!.balanced) {
# if unbalanced, combine with previous
.pchain[[i - 1]] <- paste(.pchain[[i - 1]],"%>%", .pchain[[i]])
.pchain[[i]] <- NULL
}
}
.calls <- Reduce( # build calls to display
function(x,y) paste0(x," %>%\n ",y),
.pchain, accumulate = TRUE)
.xinit <- eval(parse(text = .pchain[1]))
.values <- Reduce(function(x,y){ # compute all values
if (inherits(x,"try-error")) NULL
else try(eval(parse(text = paste("x %>%", y))),silent = TRUE)},
.pchain[-1], .xinit, accumulate = TRUE)
message("press enter to show, 's' to skip, 'q' to quit, lhs can be accessed with `.`")
for (.i in (seq_along(.pchain))) {
cat("\n",.calls[.i])
.rdl_ <- readline()
. <- .values[[.i]]
# while environment is explored
while (!.rdl_ %in% c("q","s","")) {
# if not an assignment, should be printed
if (!grepl("^\\s*[[:alnum:]_.]*\\s*<-",.rdl_)) .rdl_ <- paste0("print(",.rdl_,")")
# wrap into `try` to safely fail
try(eval(parse(text = .rdl_)))
.rdl_ <- readline()
}
if (.rdl_ == "q") return(invisible(NULL))
if (.rdl_ != "s") {
if (inherits(.values[[.i]],"try-error")) {
# a trick to be able to use stop without showing that
# debug_pipe failed in the output
opt <- options(show.error.messages = FALSE)
on.exit(options(opt))
message(.values[[.i]])
stop()
} else
{
print(.)
}
}
}
if (!is.na(.lhs)) assign(.lhs,tail(.values,1),envir = parent.frame())
invisible(NULL)
}
Run Code Online (Sandbox Code Playgroud)
示例代码:
library(dplyr)
# copy following 4 lines to clipboard, no need to execute
test <- iris %>%
slice(1:2) %>%
select(1:3) %>%
mutate(x=3)
debug_pipe()
# or wrap expression
debug_pipe(
test <- iris %>%
slice(1:2) %>%
select(1:3) %>%
mutate(x=3)
)
Run Code Online (Sandbox Code Playgroud)
以下是我的步骤:
两个很好的资源是:
新项目/R包/将包命名为pipedebug
将函数的代码放入文件夹.R中的文件中R。我们重命名该函数,pdbg因为我意识到magrittr已经有一个名为debug_pipe执行不同操作的函数(它执行浏览器并返回输入)。
我们必须添加第二个不带参数的函数,插件将触发该函数,我们可以随意命名它:
pdbg_addin <- function(){
selection <- rstudioapi::primary_selection(
rstudioapi::getSourceEditorContext())[["text"]]
rstudioapi::sendToConsole("",execute = F)
eval(parse(text=paste0("pdbg(",selection,")")))
}
Run Code Online (Sandbox Code Playgroud)
第一行捕获选择,改编自reprex的代码。
第二行是将空字符串发送到控制台而不执行它,这就是我发现的移动光标的全部内容,但可能有更好的方法。
第三行以选择作为参数运行主函数。
下一步是创建inst/rstudio/addins.dcf包含以下内容的文件:
Name: debug pipe
Description: debug pipes step by step
Binding: pdbg_addin
Interactive: false
Run Code Online (Sandbox Code Playgroud)
usethis::use_addin("pdbg_addin")将创建该文件,用模板填充该文件并将其打开,以便您可以对其进行编辑。
Ctrl+Shift+B
工具/插件/浏览插件/键盘快捷键/调试管道/Ctrl+P
在文本编辑器中复制/选择/Ctrl+P
test <- iris %>%
slice(1:2) %>%
select(1:3) %>%
mutate(x=3)
Run Code Online (Sandbox Code Playgroud)
在这里找到一个粗略的版本:
devtools::install_github("moodymudskipper/pipedebug")
?pdbg
Run Code Online (Sandbox Code Playgroud)
类似的努力:
@Alistaire 做到了这一点,并在他的页面上宣传了其他努力。