There is a keyboard shortcut in Typora and VScode. But I didn't find it in rstudio. I try to use snippets
\$${0}\$
but it's work as I expected.
There is a keyboard shortcut in Typora and VScode. But I didn't find it in rstudio. I try to use snippets
\$${0}\$
but it's work as I expected.
Related to my answer to a similar question you can combine a working R Markdown Snippet with the shrtcts package to add a keybinding to the snippet:
Create a new R Markdown Snippet which can also be used on its own by typing e.g. la
(for latex math) and press Shift+Tab:
snippet la
$${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:
#' Latex Math
#'
#' @description
#' If Editor has selection, surround current selection by Dollar signs.
#' If Editor has no selection, write between Dollar signs.
#' @interactive
#' @shortcut Cmd+L
function() {
if (rstudioapi::selectionGet()$value == "") {
rstudioapi::insertText("la")
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("${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+l
without selection to place your cursor right between two Dollar signs.
Or you can select text and then press cmd+l
to surround the selected text by Dollar signs.
The solution above can be easily adapted to write bold, italic or monospace (code font) text in RMarkdown documents. You simply have to replace the snippet name in the line
rstudioapi::insertText("la")
and modify the desired output in the line
stringr::str_glue("${selected_text}$")
to e.g. stringr::str_glue("**{selected_text}**")
for bold text.
As per the RStudio RMarkdown cheatsheet:
equation: $A = \pi*r^{2}$