R/02_instantmd.R

# integrate default header and code folding, make plugin


# suppressPackageStartupMessages(library(tidyverse))
# library(plotly)
# x <- iris %>% nest(-Species)
#
# ### Plot of `r x$Species[1]`
# ## `r x$Species[1]` has a mean petal length of `r mean(x$data[[1]]$Petal.Length)`
# hist(x$data[[1]]$Sepal.Width)
# # a regular comment
# hist(x$data[[1]]$Sepal.Length)
# ## something else
# if (TRUE)
#   letters[1:5] else
#     LETTERS[1:5]
# (ggplot(iris,aes(Sepal.Length, Sepal.Width)) + geom_point()) %>% ggplotly()

instantmd0 <- function(){
txt <-
  selection <- rstudioapi::primary_selection(
    rstudioapi::getSourceEditorContext())[["text"]]
instantmd(txt)
}

#' Build report from lines of code
#'
#' @param txt
#'
#' @return output file path
#' @export
instantmd <- function(txt){
  header <- paste0(
    "---\n",
    "title: mmmd report\n",
    "author: '`r Sys.getenv(\"USERNAME\")`'\n",
    "date: '`r Sys.Date()`'\noutput:\n",
    "  html_document:\n",
    "    code_folding: hide\n",
    "---\n\n")

  body <- strsplit(txt, "\n")[[1]] %>%
    tibble::tibble(code = .) %>%
    dplyr::filter(code != "") %>%
    dplyr::mutate(commented = substr(trimws(code),1,2) == "##",
                  code = ifelse(commented,
                                purrr::map_chr(code,~substr(.,3,nchar(.))) %>% trimws,
                                code),
                  groupid = cumsum(commented * c(1,diff(commented)))) %>%
    dplyr::group_by(groupid) %>%
    dplyr::summarize(res = list(c(as.list(code[commented]),
                                  list(code_to_chunk(code[!commented]))))) %>% #
    dplyr::pull(res) %>%
    unlist()  %>%
    paste(collapse = "\n\n")

  rmd <- paste0(header,body)

  temp_rmd <- tempfile(fileext = ".Rmd")
  write(rmd,temp_rmd)

  output_file <- rmarkdown::render(temp_rmd)
  browseURL(output_file)
  output_file
}
moodymudskipper/mmmd documentation built on May 15, 2019, 9:14 p.m.