This builds on the reprex::reprex() function to take a chunk of code, run it and copy the formatted code and output to the clipboard. Note that this does NOT run in a clean session and is thus unlikely to create reproducible examples. Instead, it is intended to be used to quickly get a formatted bit of code and output that is not self-contained, e.g., for teaching materials.

run_and_format(code = NULL, venue = "gh")

Arguments

code

The code to run - can be NULL, then the code is retrieved from the clipboard.

venue

Character. Must be one of the following (case insensitive):

  • "gh" for GitHub-Flavored Markdown, the default

  • "r" for a runnable R script, with commented output interleaved. Also useful for Slack code snippets; select "R" from the "Type" drop-down menu to enjoy nice syntax highlighting.

  • "rtf" for Rich Text Format (not supported for un-reprexing)

  • "html" for an HTML fragment suitable for inclusion in a larger HTML document (not supported for un-reprexing)

  • "slack" for pasting into a Slack message. Optimized for people who opt out of Slack's WYSIWYG interface. Go to Preferences > Advanced > Input options and select "Format messages with markup". (If there is demand for a second Slack venue optimized for use with WYSIWYG, please open an issue to discuss.)

  • "so" for Stack Overflow Markdown. Note: this is just an alias for "gh", since Stack Overflow started to support CommonMark-style fenced code blocks in January 2019.

  • "ds" for Discourse, e.g., forum.posit.co. Note: this is currently just an alias for "gh".

Examples

if (interactive()) {
  name <- "Lukas"
  run_and_format(paste("My name is", name))
}