carbonate
carbonate copied to clipboard
Feature Request: Execute and Carbonise selected Code
It would be awesome to have a function that takes takes the currently selected code, executes it and creates a carbon of it. This would be similar to reprex but using carbon. As a next step this could be put in a RStudio AddIn to be bound to a keyboard shortcut.
I frequently hit this when preparing code-heavy slide, where I have multiple small code chunks that should be "styled" with carbon.
Example
Note this requires to select code while executing some parts of the code. This can be achieved by putting the code in the console without executing it, selecting the code to display, moving the cursor to the console again and hitting enter. This process would be simplified by using an RStudio addin.
# this is just first rough function, this does not handle plots or other outputs well...
evaluate_code <- function(code = NULL) {
code <- if (is.null(code))
rstudioapi::primary_selection(rstudioapi::getSourceEditorContext())$text
e <- evaluate::evaluate(code)
res <- sapply(e, function(y) if ("src" %in% names(y)) y[["src"]] else paste0("#>", y))
res <- gsub("\\n", "", res)
paste(res, collapse = "\n")
}
# while having some the below code selected, execute `res <- evalute_code()`
x <- 1:10
x
# will result in
cat(res)
#> x <- 1:10
#> x
#> #> [1] 1 2 3 4 5 6 7 8 9 10
# maybe have some way of giving arguments to the function regarding styling or so.
# alternative to carbon.yml
carbon_this_browser <- function(code = NULL, eval = TRUE, style = TRUE) {
code_res <- if (eval) evaluate_code(code) else code
if (style) code_res <- styler::style_text(code_res)
carb <- carbon$new(code_res)
carb$browse()
}
# again, have the below code selected while calling `carbon_this_browser()` Note that this will also style the code (optional I guess)
x=1: 10
x
The last example will open this url.
Similarly, the download function could be wrapped as well (I cannot try this out on my machine due to proxy issues with RSelenium, therefore I need to download the file manually).
Does this make sense to you and is it worth looking into it?
i think you are trying to do something similar to this: https://twitter.com/yoniceedee/status/1056587571042705410
the flow i envisioned in the past was to reun code in reprex with an r venue and then pass in that file into carbonate.
I guess they are broadly similar but with the added dependency of pasting the code as a gist. Let me quickly throw together a MWE so you can see what I mean precisely.