Reputation: 1438
To keep my code neat I like to use Code Sections. On a Windows the shortcut for a new code section is ctrl+shift+R
and on a MAC it is Cmd+shift+R
. The formatting on the sections is
# <label> ---------------------------------------
but when I use knitr
to write a document and include code from an .R-file, this formatting does not match what knitr
is expecting of a label.
For example when using
read_chunk("foo.R")
<<label-a>>=
@
then label-a
in foo.R
must have at least four dashes -
before it - for example
## ---- label-a ----
1+2
rnorm(2)
Hence it would be nice to be able to change the keyboard shortcut in RStudio so that it creates a code section with formatting on the following form:
## ---- <label> ----
Is this possible?
Upvotes: 5
Views: 1224
Reputation: 122
I wanted to do the same but preferred to have automatic length generation based on the label length like the CTRL+SHIFT+R
hotkey does. Since R can evalute in snippets now:
snippet sect-
`r strtrim(paste("#----",parse(text = "$$"),strrep("-",150)),120)`
To use it, you can type in "sect-label", press SHIFT+TAB
, and it will automatically generate "#---- label -----------..." to a length of 120 characters (my IDE margin length).
Would be nice to automatically set for the margin length, however, but I couldn't find how to get the value for it.
Upvotes: 1
Reputation: 156
I asked the question over at RStudio support and although there is no direct way to do it, they suggested I might use the snippet functionality:
https://support.rstudio.com/hc/en-us/articles/204463668-Code-Snippets
You can add the following to the snippets:
snippet sec
## ---- ${1:label} ----
${2:}
The $ signs are placeholders that allow you to go there directly with . You just type in "sec", pres tab, the snippet is filled in, you write your label name and press tab to got after the snippet. Not the same as what you want, but pretty close. It works perfectly for me.
Upvotes: 4