Skip to content

Feature Request: Execute and Carbonise selected Code #27

@DavZim

Description

@DavZim

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions