Unfortunately, it seem not possible.
I think the best is to learn some rules to apply systematically:
RStudio folding rules
A section that one can fold using the "Edit -> Folding -> Collapse All" will be any comment line (starting with #) which includes at least four trailing dashes (-), equal signs (=), or pound signs (#)
Instead of collapsing the { }, one could insert the section as expected by R, then use the "Edit -> Folding -> Collapse All".
Note: this will not work nicely with a selected region and "Edit -> Folding -> Collapse".
From the following code:
# function1 ####
function1 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
# function2 ====
function2 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
# function3 ----
function3 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
# function4 ####
function4 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
#### function5 ####
function5 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
I can fold it this way:
If one always use the same way to define function, it is possible to use awk to actually add a section before each function definition:
awk '{ if( $0 ~/function/ ) { print "####" $0 "\n" $0 }else{ print $0} }' code_function.R
From the following code contained in the file code_function.R
function1 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
function2 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
I run in a (linux) terminal:
awk '{ if( $0 ~/function/ ) { print "####" $0 "\n" $0 }else{ print $0} }' code_function.R > code_function_withSections.R
and I obtain the following file -- ugly file -- but a fast way to modify a 10000-functions file.
####function1 <- function(x){
function1 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}
####function2 <- function(x){
function2 <- function(x){
somecode <- 0
test <- 3
mean(c(1,2,3))
}