Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #' Converts an R reStructuredText document (Rrst) to R Markdown (Rmd)
- #'
- #' @param input character string with the path of the file to convert
- #' @param output optional character string with the path for the output file
- #' @param out_dir optional character string with the output directory. Not used
- #' if \code{output} is supplied.
- #' @param output_file logical whether to return the output to a file or not.
- #' If \code{FALSE}, then \code{output} and \code{out_dir} are ignored.
- #'
- #' @importFrom readr read_file write_file
- #' @importFrom tools file_path_sans_ext
- rrst_to_rmd <- function(input, output, out_dir, output_file = TRUE) {
- library(readr)
- library(tools)
- if (!file.exists(input))
- stop(sprintf('Unable to find %s', input))
- # Find basic file name and file path
- input_name <- file_path_sans_ext(basename(input))
- # Read file into R
- txt <- read_file(input)
- #### Conversions -----------------------------------------------------------
- # h1
- txt_edit <- gsub('\\n~~~~*\\n', '\n======\n', txt)
- # h2
- txt_edit <- gsub('\\n\\+\\+\\+\\+*\\n', '\n------\n', txt_edit)
- # h3
- txt_edit <- gsub('\\n\\!\\!\\!\\!*\\n', '\\!\\!\\!\\!\\!\\!\\!\\!\n',
- txt_edit)
- txt_edit <- gsub('(\\n\\n){1}(.+?)(\\!\\!\\!\\!\\!\\!\\!\\!)',
- '\n\n### \\2', txt_edit, perl = TRUE)
- # inline math
- txt_edit <- gsub('(?<!`)(?<=(?!``).)`(?!`)', '$', txt_edit, perl = TRUE)
- txt_edit <- gsub(":math:", '', txt_edit)
- # inline code chunks
- txt_edit <- gsub('``', '`', txt_edit)
- # display code chunks
- txt_edit <- gsub('\\n\\.\\. \\{', '\n```{', txt_edit)
- txt_edit <- gsub('\\n\\.\\. \\.\\.', '\n```', txt_edit)
- # display math
- txt_edit <- gsub('(math::)(\\n\\n)', '\\1', txt_edit, perl = TRUE)
- txt_edit <- gsub('(math::)(\\s+)', '\\1', txt_edit)
- txt_edit <- gsub('math::.+?\\K(\\n{1} +)', 'PLACEHOLDER', txt_edit,
- perl = TRUE)
- txt_edit <- gsub('math::.*\\K\\n\\n', '\n$$\n\n', txt_edit, perl = TRUE)
- txt_edit <- gsub('.. math::', '\n$$\n ', txt_edit, perl = TRUE)
- txt_edit <- gsub('PLACEHOLDER', '\n ', txt_edit, perl = TRUE)
- # Cleanup
- txt_edit <- gsub('\\n\\n\\n', '\n\n', txt_edit)
- # Return output ------------------------------------------------------------
- if (isTRUE(output_file)) {
- if (missing(output)) {
- if (missing(out_dir))
- input_path <- dirname(input)
- else input_path <- out_dir
- output <- paste0(input_path, '/', input_name, '.Rmd')
- }
- write_file(txt_edit, path = output)
- }
- else
- return(txt_edit)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement