Debian Codegraph @

R/utils-conversion.R

raw
1 #' A wrapper for rst2pdf
2 #'
3 #' Convert reST to PDF using \command{rst2pdf} (which converts from rst to PDF
4 #' using the ReportLab open-source library).
5 #' @param input The input rst file.
6 #' @param command Character string giving the path of the
7 #' \command{rst2pdf} program. If the program is not in your PATH, the full path has to be
8 #' given here.
9 #' @param options Extra command line options, e.g. \code{'-v'}.
10 #' @author Alex Zvoleff and Yihui Xie
11 #' @return An input file \file{*.rst} will produce \file{*.pdf} and this output
12 #' filename is returned if the conversion was successful.
13 #' @export
14 #' @seealso \code{\link{knit2pdf}}
15 #' @references \url{https://github.com/rst2pdf/rst2pdf}
16 rst2pdf = function(input, command = 'rst2pdf', options = '') {
17 out = with_ext(input, 'pdf')
18 system2(command, paste(shQuote(input), '-o', shQuote(out), options))
19 if (file.exists(out)) out else stop('conversion by rst2pdf failed!')
20 }
21
22 #' Convert various input files to various output files using \code{knit()} and
23 #' Pandoc
24 #'
25 #' Knits the input file and compiles to an output format using Pandoc.
26 #' @inheritParams knit
27 #' @param to Character string giving the Pandoc output format to use.
28 #' @param pandoc_wrapper An R function used to call Pandoc. If \code{NULL} (the
29 #' default), \code{rmarkdown::\link[rmarkdown]{pandoc_convert}()} will be used
30 #' if \pkg{rmarkdown} is installed, otherwise \code{\link{pandoc}()}.
31 #' @param ... Options to be passed to the \code{pandoc_wrapper} function.
32 #' @param encoding Ignored (always assumes UTF-8).
33 #' @author Trevor L. Davis
34 #' @return Returns the output of the \code{pandoc_wrapper} function.
35 #' @export
36 knit2pandoc = function(
37 input, output = NULL, tangle = FALSE, text = NULL, quiet = FALSE,
38 envir = parent.frame(), to = 'html', pandoc_wrapper = NULL, ..., encoding = 'UTF-8'
39 ) {
40 knit_output = knit(input, output, tangle, text, quiet, envir)
41 if (!is.null(pandoc_wrapper)) return(pandoc_wrapper(knit_output, to, ...))
42 if (!has_package('rmarkdown')) return(pandoc(knit_output, to, ...))
43 output = gsub(paste0(file_ext(knit_output), '$'), to, knit_output)
44 rmarkdown::pandoc_convert(knit_output, to, output = output, ...)
45 }
46
47 #' Convert Rnw or Rrst files to PDF
48 #'
49 #' Knit the input Rnw or Rrst document, and compile to PDF using
50 #' \code{tinytex::\link[tinytex]{latexmk}()} or \code{\link{rst2pdf}()}.
51 #' @inheritParams knit
52 #' @param compiler A character string giving the LaTeX engine used to compile
53 #' the tex document to PDF. For an Rrst file, setting \code{compiler} to
54 #' \code{'rst2pdf'} will use \code{\link{rst2pdf}} to compile the rst file to
55 #' PDF using the ReportLab open-source library.
56 #' @param ... Options to be passed to \code{tinytex::\link[tinytex]{latexmk}()}
57 #' or \code{\link{rst2pdf}()}.
58 #' @author Ramnath Vaidyanathan, Alex Zvoleff and Yihui Xie
59 #' @return The filename of the PDF file.
60 #' @note The \code{output} argument specifies the output filename to be passed
61 #' to the PDF compiler (e.g. a tex document) instead of the PDF filename.
62 #' @export
63 #' @examples #' compile with xelatex
64 #' ## knit2pdf(..., compiler = 'xelatex')
65 #'
66 #' #' compile a reST file with rst2pdf
67 #' ## knit2pdf(..., compiler = 'rst2pdf')
68 knit2pdf = function(
69 input, output = NULL, compiler = NULL, envir = parent.frame(), quiet = FALSE, ...
70 ) {
71 out = knit(input, output = output, envir = envir, quiet = quiet)
72 owd = setwd(dirname(out)); on.exit(setwd(owd))
73 if (is.null(compiler)) {
74 compiler = if (grepl('\\.rst$', out)) 'rst2pdf' else 'pdflatex'
75 }
76 if (identical(compiler, 'rst2pdf')) {
77 if (tolower(file_ext(out)) != 'rst')
78 stop('for rst2pdf compiler input must be a .rst file')
79 rst2pdf(basename(out), ...)
80 } else {
81 tinytex::latexmk(basename(out), engine = compiler, ...)
82 }
83 with_ext(out, 'pdf')
84 }
85
86 #' Convert an \file{Rnw} document to PDF
87 #'
88 #' Call \code{\link{knit}()} to compile the \file{.Rnw} input to \file{.tex},
89 #' and then \code{tinytex::\link[tinytex]{latexmk}()} to convert \file{.tex} to
90 #' \file{.pdf}.
91 #'
92 #' This function is similar to \code{\link{knit2pdf}()}, with the following differences:
93 #' \enumerate{
94 #' \item The default compiler is "xelatex" instead of "pdflatex".
95 #' \item \code{output} uses the file extension ".pdf" instead of ".tex".
96 #' \item Before knitting, it tries to remove the \code{output} file and will throw a clear error if the file cannot be removed.
97 #' \item \code{output} could be under any dir, not necessarily the same directory as \code{input}.
98 #' \item It cleans up intermediate files by default, including the ".tex" file.
99 #' \item It stops knitting when any error occurs (by setting the chunk option \code{error = FALSE}).
100 #' }
101 #' @inheritParams knit
102 #' @param output Path of the PDF output file. By default, it uses the same name
103 #' as the \code{input}, but changes the file extension to ".pdf".
104 #' @param compiler,... The LaTeX engine and other arguments to be passed to
105 #' \code{tinytex::\link[tinytex]{latexmk}()}. The default compiler is
106 #' \code{xelatex}.
107 #' @param clean If \code{TRUE}, the intermediate files will be removed.
108 #' @param error If \code{FALSE}, knitting stops when any error occurs.
109 #' @return The \code{output} file path.
110 #' @export
111 rnw2pdf = function(
112 input, output = with_ext(input, 'pdf'), compiler = 'xelatex',
113 envir = parent.frame(), quiet = FALSE, clean = TRUE, error = FALSE, ...
114 ) {
115 # On Windows, when tweaking the content, users may forget to close the PDF
116 # file (thus can't be written). Since knitting may take quite some time, it's
117 # better to check the write permission of the output file in advance.
118 if (xfun::file_exists(output) && !file.remove(output)) stop(
119 "The file '", output, "' cannot be removed (may be locked by a PDF reader)."
120 )
121 old = opts_chunk$set(error = error)
122 on.exit(opts_chunk$set(old), add = TRUE)
123 file_tex = knit(input, envir = envir, quiet = quiet)
124 if (clean) on.exit(file.remove(file_tex), add = TRUE)
125 file_pdf = tinytex::latexmk(file_tex, engine = compiler, clean = clean, ...)
126 if (!xfun::same_path(output, file_pdf)) file.rename(file_pdf, output)
127 output
128 }
129
130 #' Convert markdown to HTML using knit() and mark_html()
131 #'
132 #' This is a convenience function to knit the input markdown source and call
133 #' \code{markdown::\link[markdown]{mark_html}()} in the \pkg{markdown}
134 #' package to convert the result to HTML.
135 #' @inheritParams knit
136 #' @param ... Options passed to
137 #' \code{markdown::\link[markdown]{mark_html}()}.
138 #' @param force_v1 Boolean; whether to force rendering the input document as an
139 #' R Markdown v1 document, even if it is for v2.
140 #' @export
141 #' @seealso \code{\link{knit}}, \code{markdown::\link[markdown]{mark_html}}
142 #' @return If the argument \code{text} is NULL, a character string (HTML code)
143 #' is returned; otherwise the result is written into a file and the filename
144 #' is returned.
145 #' @note The \pkg{markdown} package is for R Markdown v1, which is much less
146 #' powerful than R Markdown v2, i.e. the \pkg{rmarkdown} package
147 #' (\url{https://rmarkdown.rstudio.com}). To render R Markdown v2 documents to
148 #' HTML, please use \code{rmarkdown::render()} instead.
149 #' @examples # a minimal example
150 #' writeLines(c("# hello markdown", '```{r hello-random, echo=TRUE}', 'rnorm(5)', '```'), 'test.Rmd')
151 #' knit2html('test.Rmd')
152 #' if (interactive()) browseURL('test.html')
153 #'
154 #' unlink(c('test.Rmd', 'test.html', 'test.md'))
155 knit2html = function(
156 input, output = NULL, ..., envir = parent.frame(), text = NULL,
157 quiet = FALSE, encoding = 'UTF-8', force_v1 = getOption('knitr.knit2html.force_v1', FALSE)
158 ) {
159 if (is_cran_check() && !has_package('markdown'))
160 return(vweave_empty(input, .reason = 'markdown'))
161
162 is_lite = FALSE
163 if (!force_v1 && is.null(text)) {
164 # test if an Rmd input should be rendered via rmarkdown::render() or (mark|lite)down::mark()
165 res = xfun::yaml_body(read_utf8(input))$yaml[['output']]
166 if (is.list(res)) res = names(res)
167 rmd_v2 = length(res) > 0 && is.character(res) && {
168 is_lite = any(grepl('^litedown::', res) | res == 'html')
169 !is_lite && !any(grepl('^markdown::', res))
170 }
171 if (rmd_v2) warning2(
172 'It seems you should call rmarkdown::render() instead of knitr::knit2html() ',
173 'because ', input, ' appears to be an R Markdown v2 document.'
174 )
175 }
176 out = knit(input, text = text, envir = envir, quiet = quiet)
177 mark = if (is_lite) litedown::mark else markdown::mark_html
178 if (is.null(text)) {
179 output = with_ext(if (is.null(output) || is.na(output)) out else output, 'html')
180 mark(out, output, ...)
181 invisible(output)
182 } else mark(text = out, ...)
183 }
184
185 #' Knit an R Markdown document and post it to WordPress
186 #'
187 #' This function is a wrapper around the \pkg{RWordPress} package. It compiles
188 #' an R Markdown document to HTML and post the results to WordPress. Please note
189 #' that \pkg{RWordPress} has not been updated for several years, which is
190 #' \href{https://github.com/yihui/knitr/issues/1866}{not a good sign}. For
191 #' blogging with R, you may want to try the \pkg{blogdown} package instead.
192 #' @param input Filename of the Rmd document.
193 #' @param title Title of the post.
194 #' @param ... Other meta information of the post, e.g. \code{categories = c('R',
195 #' 'Stats')} and \code{mt_keywords = c('knitr', 'wordpress')}, et cetera.
196 #' @param shortcode A length-2 logical vector: whether to use the shortcode
197 #' \samp{[sourcecode lang='lang']}, which can be useful to WordPress.com users
198 #' for syntax highlighting of source code and output. The first element
199 #' applies to source code, and the second applies to text output. By default,
200 #' both are \code{FALSE}.
201 #' @param action Whether to create a new post, update an existing post, or
202 #' create a new page.
203 #' @param postid If \code{action} is \code{editPost}, the post id \code{postid}
204 #' must be specified.
205 #' @param publish Boolean: publish the post immediately?
206 #' @inheritParams knit
207 #' @export
208 #' @references \url{https://yihui.org/knitr/demo/wordpress/}
209 #' @author William K. Morris, Yihui Xie, and Jared Lander
210 #' @note This function will convert the encoding of the post and the title to
211 #' UTF-8 internally. If you have additional data to send to WordPress (e.g.
212 #' keywords and categories), you may have to manually convert them to the
213 #' UTF-8 encoding with the \code{\link{iconv}(x, to = 'UTF-8')} function
214 #' (especially when using Windows).
215 #' @examples # see the reference
216 knit2wp = function(
217 input, title = 'A post from knitr', ..., envir = parent.frame(), shortcode = FALSE,
218 action = c('newPost', 'editPost', 'newPage'), postid, publish = TRUE
219 ) {
220 do.call('library', list(package = 'RWordPress', character.only = TRUE))
221 xfun::do_once(
222 warning2(
223 'This function is based on the RWordPress package, which is no longer actively ',
224 'maintained (https://github.com/yihui/knitr/issues/1866). For blogging with R, ',
225 'you may try the blogdown package instead.'
226 ), 'knitr.knit2wp.warning'
227 )
228 out = knit(input, envir = envir); on.exit(unlink(out))
229 content = read_utf8(out)
230 if (missing(title) && length(title2 <- xfun::yaml_body(content)$yaml$title) == 1)
231 title = title2
232 content = markdown::mark(text = content)
233 shortcode = rep(shortcode, length.out = 2L)
234 if (shortcode[1]) content = gsub(
235 '<pre><code class="([[:alpha:]]+)">(.+?)</code></pre>',
236 '[sourcecode language="\\1"]\\2[/sourcecode]', content
237 )
238 content = gsub(
239 '<pre><code( class="no-highlight"|)>(.+?)</code></pre>',
240 if (shortcode[2]) '[sourcecode]\\2[/sourcecode]' else '<pre>\\2</pre>', content
241 )
242
243 content = enc2utf8(content)
244 title = enc2utf8(title)
245
246 # figure out if we are making a newPost or overwriting an existing post
247 action = match.arg(action)
248
249 # build a list of arguments to be fed into either newPost or editPost
250 # the first argument is the content, which itself is a list containing
251 # description
252 # title
253 # ...
254 # then there is the publish argument
255 WPargs = list(content = list(description = content, title = title, ...), publish = publish)
256
257 # if we are editing the post, also include the argument for postid
258 if (action == "editPost") WPargs = c(postid = postid, WPargs)
259
260 do.call(action, args = WPargs)
261 }
262
263 #' Watch an input file continuously and knit it when it is updated
264 #'
265 #' Check the modification time of an input file continously in an infinite loop.
266 #' Whenever the time indicates the file has been modified, call a function to
267 #' recompile the input file.
268 #'
269 #' This is actually a general function not necessarily restricted to
270 #' applications in \pkg{knitr}. You may specify any \code{compile} function to
271 #' process the \code{input} file. To stop the infinite loop, press the
272 #' \samp{Escape} key or \samp{Ctrl + C} (depending on your editing environment
273 #' and operating system).
274 #' @param input An input file path, or a character vector of mutiple input file paths.
275 #' @param compile A function to compile the \code{input} file. This could be e.g.
276 #' \code{\link{knit}} or \code{\link{knit2pdf}}, depending on the input file
277 #' and the output you want.
278 #' @param interval A time interval to pause in each cycle of the infinite loop.
279 #' @param ... Other arguments to be passed to the \code{compile} function.
280 #' @export
281 #' @examples # knit_watch('foo.Rnw', knit2pdf)
282 #'
283 #' # knit_watch('foo.Rmd', rmarkdown::render)
284 knit_watch = function(input, compile = knit, interval = 1, ...) {
285 mtime = function(...) file.info(...)[, 'mtime']
286 last_time = mtime(input)
287 updated = function() {
288 this_time = mtime(input)
289 on.exit(last_time <<- this_time, add = TRUE)
290 this_time > last_time
291 }
292 for (f in input) compile(f, ...)
293 while (TRUE) {
294 for (f in input[updated()]) compile(f, ...)
295 Sys.sleep(interval)
296 }
297 }