-
Notifications
You must be signed in to change notification settings - Fork 2
/
render_natbib.R
84 lines (83 loc) · 2.17 KB
/
render_natbib.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#' Render a Markdown file with `natbib` bibliography
#' @export
#' @importFrom rmarkdown render
#' @importFrom assertthat assert_that is.string is.flag noNA
#' @importFrom utils file_test
#' @param file the name of the `Rmd` file.
#' @param path the path of the `Rmd` file.
#' @param encoding the encoding of the `Rmd` file. Default to 'UTF-8'.
#' @param engine the LaTeX engine the compile the document.
#' Defaults to `"xelatex"`.
#' @param display open the pdf in a reader. Defaults to TRUE.
#' @param keep keep intermediate files after successful compilation.
#' Defaults to "none".
#' @param clean TRUE to clean intermediate files created during rendering of the
#' R markdown into `tex`.
#' @family utils
render_natbib <- function(
file,
path = ".",
encoding = "UTF-8",
engine = c("xelatex", "pdflatex"),
display = TRUE,
keep = c("none", "all", "tex"),
clean = TRUE
) {
engine <- match.arg(engine)
keep <- match.arg(keep)
assert_that(is.string(file))
assert_that(is.string(path))
assert_that(is.string(encoding))
assert_that(file_test("-d", path))
assert_that(file_test("-f", paste(path, file, sep = "/")))
assert_that(grepl("\\.[Rr]md$", file))
assert_that(is.flag(display))
assert_that(noNA(display))
assert_that(is.flag(clean))
assert_that(noNA(clean))
current <- getwd()
setwd(path)
output <- gsub("\\.[Rr]md$", "", file)
render(
file,
output_file = paste0(output, ".tex"),
encoding = encoding,
clean = clean
)
log <- system(paste(engine, output))
if (log == 1) {
setwd(current)
stop()
}
log <- system(paste("bibtex", output))
if (log == 1) {
setwd(current)
stop()
}
log <- system(paste(engine, output))
if (log == 1) {
setwd(current)
stop()
}
log <- system(paste(engine, output))
if (log == 1) {
setwd(current)
stop()
}
if (display) {
file.show(paste0(output, ".pdf"))
}
if (keep != "all") {
file.remove(
paste0(
output,
c(".aux", ".bbl", ".blg", ".toc", ".lof", ".log", ".lot", ".out")
)
)
if (keep == "none") {
file.remove(paste0(output, ".tex"))
unlink(paste0(output, "_files"), recursive = TRUE)
}
}
setwd(current)
}