Related to my answer to a similar question you can combine a working R Markdown Snippet (as suggested by @user1864652) with the shrtcts package to add a keybinding to the snippet:
Add a name to the Snippet such as inl
(for inline code):
snippet inl
`r `r \`${1}`$0
Use the command shrtcts::edit_shortcuts()
in the RStudio Console to open the file where you define your custom shortcuts.
Paste the following code inside that file (set your preferred keybinding in the @shortcut
line). Note that the inserted text in the second line of the function must match the name of the new Snippet from Step 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)
}
}
}
This solution uses the native pipe |>
and thus requires R 4.1
.
You can of course just define separate variables in each line or use the magrittr
pipe if you use earlier versions of R
.
Further the stringr::str_glue()
command can be easily replaced with a base R
solution to avoid dependencies.
Use the command shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE)
in the RStudio Console to add the new shortcut with its assigned keybinding. Then restart RStudio.
Now you can use e.g. cmd+shift+i
without selection to place your cursor right before the second backtick of the inline code and press Tab
to continue writing after the second backtick.
Or you can select text and then press cmd+shift+i
to transform the selected text to inline code.
The solution above can be easily adapted for bold, italic or monospace (code font) text in RMarkdown documents or to write within Dollar signs to add Inline Latex Math.
You simply have to replace the snippet name in the line
rstudioapi::insertText("inl")
and modify the desired output in the line
stringr::str_glue("`r {selected_text}`")
to e.g. stringr::str_glue("**{selected_text}**")
for bold text.