Debian Codegraph @

R/convert.R

raw
1 #' Open file
2 #'
3 #' Tries to open a file with operating system's default program.
4 #' @param f file (with full path)
5 #' @references This function is a fork of David Hajage's \code{convert} function: \url{https://github.com/eusebe/ascii/blob/master/R/export.r}
6 #' @export
7 openFileInOS <- function(f) {
8
9 if (missing(f)) {
10 stop('No file to open!')
11 }
12
13 f <- path.expand(f)
14
15 if (!file.exists(f)) {
16 stop('File not found!')
17 }
18
19 if (grepl('w|W', .Platform$OS.type)) {
20 ## we are on Windows
21 shell.exec(f) #nolint
22 } else {
23 if (grepl('darwin', version$os)) {
24 ## Mac
25 system(paste(shQuote('open'), shQuote(f)), wait = FALSE, ignore.stderr = TRUE)
26 } else {
27 ## Linux
28 system(paste(shQuote('/usr/bin/xdg-open'), shQuote(f)), #nolint
29 wait = FALSE,
30 ignore.stdout = TRUE)
31 }
32 }
33
34 }
35
36 #' Converts Pandoc to other format
37 #'
38 #' Calling John MacFarlane's great program to convert specified file (see \code{f} parameter below) or character vector (see \code{text} parameter) to other formats like \code{HTML}, \code{pdf}, \code{docx}, \code{odt} etc.
39 #' @param f Pandoc's markdown format file path. If URL is provided then the generated file's path is \code{tempfile()} but please bear in mind that this way only images with absolute path would shown up in the document.
40 #' @param text Pandoc's markdown format character vector. Treated as the content of \code{f} file - so the \code{f} parameter is ignored. The generated file's path is \code{tempfile()}.
41 #' @param format required output format. For all possible values here check out Pandoc homepage: \url{https://johnmacfarlane.net/pandoc/}
42 #' @param open try to open converted document with operating system's default program
43 #' @param options optionally passed arguments to Pandoc (instead of \code{pander}'s default)
44 #' @param footer add footer to document with meta-information
45 #' @param proc.time optionally passed number in seconds which would be shown in the generated document's footer
46 #' @param portable.html instead of using local files, rather linking JS/CSS files to an online CDN for portability and including base64-encoded images if converting to \code{HTML} without custom \code{options}
47 #' @param pandoc.binary custom path to \code{pandoc}'s binary if not found in the path or not set in the \code{RSTUDIO_PANDOC} env var
48 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
49 #' @note This function depends on \code{Pandoc} which should be pre-installed on user's machine. See the \code{INSTALL} file of the package.
50 #' @return Converted file's path.
51 #' @importFrom tools file_path_sans_ext
52 #' @importFrom utils packageDescription
53 #' @export
54 #' @examples \dontrun{
55 #' Pandoc.convert(text = c('# Demo', 'with a paragraph'))
56 #' Pandoc.convert('https://rapporter.github.io/pander/minimal.md')
57 #' # Note: the generated HTML is not showing images with relative path from the above file.
58 #' # Based on that `pdf`, `docx` etc. formats would not work! If you want to convert an
59 #' # online markdown file to other formats with this function, please pre-process the file
60 #' # to have absolute paths instead.
61 #' }
62 Pandoc.convert <- function(f, text, format = 'html', open = TRUE, options = '',
63 footer = FALSE, proc.time, portable.html = TRUE,
64 pandoc.binary = panderOptions('pandoc.binary')) {
65
66 ## check for Pandoc
67 if (pandoc.binary == '') {
68 if (grepl('w|W', .Platform$OS.type))
69 message('You may install Pandoc easily with "install.pandoc()" from the "installr" package.')
70 stop("It seems Pandoc is not installed or path of binary is not found. Did you restarted R after Pandoc install? See installation details by running:\n\n\t readLines(system.file('includes/html/footer.html', package='pander'))\n") #nolint
71 }
72 if (!file.exists(pandoc.binary)) {
73 stop(paste('Pandoc binary is not found at provided location:', pandoc.binary))
74 }
75
76 ## dealing with provided character vector
77 if (!missing(text)) {
78 f <- tempfile()
79 cat(text, file = f, sep = '\n')
80 }
81
82 ## content
83 rl <- readLines(f, warn = FALSE)
84
85 ## dealing with URLs
86 if (grepl('^https*://.*', f)) {
87 f.dir <- tempdir()
88 f.out <- paste0(tempfile(), '.', format)
89 } else {
90 f.dir <- dirname(f)
91 f.out <- paste0(file_path_sans_ext(f), '.', format)
92 }
93
94 ## force UTF-8 encoding #nolint
95 ## if (!grepl('utf', Sys.getlocale())) { #nolint
96
97 ## convert content to UTF-8
98 text <- iconv(readLines(f, warn = FALSE), from = '', to = 'UTF-8')
99
100 ## do not touch original input file
101 if (!missing(f)) {
102 f <- tempfile()
103 ## remove tempfile if not needed any more
104 on.exit(unlink(f))
105 }
106
107 ## write content with UTF-8 encoding
108 con <- file(f, 'w', encoding = 'UTF-8')
109 cat(text, file = con, sep = '\n')
110 close(con)
111
112 ## } #nolint
113
114 ## add nifty HTML/CSS/JS components
115 if (format == 'html') {
116
117 if (options == '') {
118
119 options <- sprintf('-A "%s"', system.file('includes/html/footer.html', package = 'pander'))
120
121 if (portable.html) {
122 options <- paste('--self-contain', options)
123 }
124
125 }
126
127 } else {
128
129 if (options == '' && any(grepl('^#', rl))) {
130 options <- '--toc'
131 }
132
133 }
134
135 ## add other formats' templates
136 ## TODO
137
138 ## add footer to file
139 if (footer) {
140 if (length(rl) > 0 && !grepl('This report was generated', tail(rl, 1))) {
141 cat(sprintf('\n\n-------\nThis report was generated with [R](https://www.r-project.org/) (%s) and [pander](https://github.com/rapporter/pander) (%s)%son %s platform.', sprintf('%s.%s', R.version$major, R.version$minor), packageDescription('pander')$Version, ifelse(missing(proc.time), ' ', sprintf(' in %s sec ', format(proc.time))), R.version$platform), file = f, append = TRUE) #nolint
142 }
143 }
144
145 ## set specified dir
146 wd <- getwd()
147 setwd(f.dir)
148
149 ## call Pandoc
150 cmd <- sprintf('%s -f markdown -s %s %s -o %s', shQuote(pandoc.binary), options, shQuote(f), shQuote(f.out))
151 if (grepl('w|W', .Platform$OS.type)) {
152 res <- suppressWarnings(tryCatch(shell(cmd, intern = TRUE), error = function(e) e)) #nolint
153 } else {
154 res <- suppressWarnings(tryCatch(system(cmd, intern = TRUE), error = function(e) e))
155 }
156
157 ## inject HTML header
158 if (format == 'html'
159 && grepl(sprintf('^(--self-contain )*-A "%s"$', system.file('includes/html/footer.html', package='pander')), options)) { #nolint
160
161 rl <- readLines(f.out, warn = FALSE)
162 he <- grep('</head>', rl)
163 ho <- readLines(system.file('includes/html/header.html', package = 'pander'), warn = FALSE)
164
165 if (portable.html) {
166 ch <- ho
167 } else {
168 ch <- gsub('http://cdn.rapporter.net/pander', system.file('includes/', package = 'pander'), ho)
169 }
170
171 writeLines(c(rl[1 : (he - 1)], ch, rl[he:length(rl)]), f.out)
172
173 }
174
175 ## revert settings
176 setwd(wd)
177
178 ## return
179 if (!is.null(attr(res, 'status'))) {
180 warning(paste0('Pandoc had some problems while converting to ',
181 format, ': \n\n', paste(res, collapse = '\n'),
182 '\n\nPandoc was called as:\n\n\t', cmd))
183 } else {
184 if (open) {
185 openFileInOS(f.out)
186 }
187 return(f.out)
188 }
189
190 }