2 # This file is part of LyX, the document processor.
3 # Licence details can be found in the file COPYING.
5 # author Jean-Marc Lasgouttes
8 # Full author contact details are available in file CREDITS
10 # Wrapper around Sweave that sets up some things for LyX
11 # argument 1 is the absolute name of the input file
12 # argument 2 is the absolute name of the output file
13 # argument 3 is the iconv name for the encoding of the file
14 # argument 4 is the original document directory
16 .cmdargs <- commandArgs(trailingOnly=TRUE)
17 .doc.enc <- .cmdargs[3]
19 # check whether Sweave.sty is seen by LaTeX. if it is not, we will
20 # copy it alongside the .tex file (in general in the temporary
21 # directory). This means that an exported LaTeX file will not work,
22 # but this is a problem of installation of R on the user's machine.
23 # The advantage compared to the use of stylepath, is that the exported
24 # .tex file will be portable to another machine. (JMarc)
25 if (!length(system("kpsewhich Sweave.sty", intern=TRUE, ignore.stderr=TRUE))) {
26 .texmf.path <- file.path(R.home("share"), "texmf")
27 if (!file.exists(.sweave.sty <- file.path(.texmf.path, "Sweave.sty"))) {
28 .sweave.sty <- file.path(.texmf.path, "tex", "latex", "Sweave.sty")
30 file.copy(.sweave.sty, dirname(.cmdargs[2]), overwrite=TRUE)
31 rm(list = c('.sweave.sty', '.texmf.path'))
35 # Change current directory to the document directory, so that R can find
39 # this is passed as a prefix.string to tell where temporary files should go
40 # the output file without extension and without '.'
41 tmpout <- gsub(".", "-", sub("\\.tex$", "", basename(.cmdargs[2])), fixed = TRUE)
43 .prefix.str <- paste(dirname(.cmdargs[2]), tmpout, sep="/")
46 # avoid the default Rplots.pdf
47 options(device = function(...) {
48 pdf(file = tempfile())
53 # The Sweave version provided with R >= 0.13.1 has proper handling for
54 # encodings and our workaround for previous versions does not work
55 # anymore. Therefore, the invocation has to be different.
56 if (is.null(formals(Sweave)$encoding)) {
57 # set default encoding for input and output files; .orig.enc is used in
58 # the sweave module preamble to reset the encoding to what it was.
59 .orig.enc <- getOption("encoding")
60 options(encoding=.doc.enc)
61 Sweave(file=.cmdargs[1], output=.cmdargs[2], syntax="SweaveSyntaxNoweb",
62 prefix.string=.prefix.str)
64 Sweave(file=.cmdargs[1], output=.cmdargs[2], syntax="SweaveSyntaxNoweb",
65 prefix.string=.prefix.str, encoding=.doc.enc)
68 # remove absolute path from \includegraphics
69 options(encoding=.doc.enc) # encoding may have been changed in the preamble chunk
70 ls.doc <- readLines(.cmdargs[2])
71 ls.cmd <- paste('\\includegraphics{', dirname(.cmdargs[2]), "/", sep = "")
72 ls.idx <- grep(ls.cmd, ls.doc, fixed = TRUE)
74 ls.doc[ls.idx] <- sub(ls.cmd, "\\includegraphics{", ls.doc[ls.idx], fixed = TRUE)
75 writeLines(ls.doc, .cmdargs[2])