Rstudio 键盘快捷键内联代码

Rstudio Keyboard Shortcut Inline Code

Rstudio 中是否有用于在 RMarkDown 文档中插入内联 R 代码的键盘快捷键?

ctr + alt + i 正在插入一个新的代码块。与此类似,最好有一个键盘快捷键来插入 r(内联 R 代码)。
我检查了 Rstudio 中的 Tools/Modify 键盘快捷键,但我在那里找不到任何有用的命令。

此外,浏览备忘单和文档对我也没有帮助。

一种解决方案是定义代码片段。

  1. 工具菜单中选择全局选项
  2. 跳转到代码部分。
  3. 编辑选项卡下寻找片段并点击编辑片段
  4. 选择Markdown。它将显示现有的片段。最后定义您自己的代码段,如下图所示:


5. 单击保存 完成。

键入 inr 后跟 Shift+tab 应该插入内联 r 代码片段。

注意:由于某些原因我无法控制光标位置,最好将光标定位在最后一个反勾之前。

另一个解决方案可能是编写一个小插件。请参阅此 RStudio Addins 了解更多信息

github 实际上有一个专门针对此用例的打包插件。

install.packages("devtools")
devtools::install_github("ThinkR-open/remedy")

# if you want to have the package update the hotkey settings
remedy::set_hotkeys 

https://github.com/ThinkR-open/remedy

这可能对 OP 不再有帮助,但由于我正在寻找相同的解决方案,但在上面发布的补救措施包中没有找到它,我想我会分享最终对我有用的片段:

`r `r \`${1:text}`

关键是在内嵌 r 代码中包含要打印的语法。需要在文本参数之前额外转义一个反引号,我不完全理解,但这就是有效的。

my answer to a similar question you can combine a working R Markdown Snippet (as suggested by @user1864652) with the shrtcts 包相关以向代码段添加键绑定:

  1. 为代码段添加名称,例如 inl(对于内联代码):

    snippet inl
        `r `r \``[=10=]
    
  2. 在 RStudio 控制台中使用命令 shrtcts::edit_shortcuts() 打开定义自定义快捷方式的文件。

  3. 将以下代码粘贴到该文件中(在 @shortcut 行中设置您喜欢的键绑定)。请注意,函数第二行中插入的文本必须与步骤 1 中新代码段的名称相匹配:

    #' Inline R Code
    #'
    #' @description
    #'   If Editor has selection, transform current selection to inline R code.
    #'   If Editor has no selection, write new inline R code.
    #' @interactive
    #' @shortcut Cmd+Shift+I
    function() {
      if (rstudioapi::selectionGet()$value == "") {
        rstudioapi::insertText("inl")
        rstudioapi::executeCommand("insertSnippet") |>
          capture.output() |>
          invisible()
      } else {
        # Gets The Active Document
        ctx <- rstudioapi::getActiveDocumentContext()
    
        # Checks that a document is active
        if (!is.null(ctx)) {
    
          # Extracts selection as a string
          selected_text <- ctx$selection[[1]]$text
    
          # modify string
          selected_text <- stringr::str_glue("`r {selected_text}`")
    
          # replaces selection with string
          rstudioapi::modifyRange(ctx$selection[[1]]$range, selected_text)
        }
      }
    }
    

    此解决方案使用本地管道 |>,因此需要 R 4.1。 您当然可以在每一行中定义单独的变量,或者如果您使用 R 的早期版本,则可以使用 magrittr 管道。 此外,stringr::str_glue() 命令可以很容易地替换为基础 R 解决方案以避免依赖。

  4. 在 RStudio 控制台中使用命令 shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE) 添加新快捷方式及其分配的键绑定。然后重启RStudio。

现在您可以使用例如cmd+shift+i 没有 selection 将光标放在内联代码的第二个反引号之前,然后按 Tab 在第二个反引号之后继续编写。 或者您可以 select 文本,然后按 cmd+shift+i 将 selected 文本转换为内联代码。

上面的解决方案可以很容易地适用于 RMarkdown 文档中的粗体、斜体或等宽(代码字体)文本,或者在美元符号内书写以添加内联 Latex 数学。 您只需替换行中的代码段名称

rstudioapi::insertText("inl") 

并在行

中修改所需的输出
stringr::str_glue("`r {selected_text}`")

例如stringr::str_glue("**{selected_text}**") 用于粗体文本。