]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxsweave.R
25cfcb3ac31e7e2a0d0b1ccee29e1f832348ac20
[lyx.git] / lib / scripts / lyxsweave.R
1 # file lyxsweave.R
2 # This file is part of LyX, the document processor.
3 # Licence details can be found in the file COPYING.
4
5 # author Jean-Marc Lasgouttes
6 # author Yihui Xie
7
8 # Full author contact details are available in file CREDITS
9
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
15
16 ls.args <- commandArgs(trailingOnly=TRUE)
17
18 # check whether Sweave.sty is seen by LaTeX. if it is not, we will
19 # copy it alongside the .tex file (in general in the temporary
20 # directory). This means that an exported LaTeX file will not work,
21 # but this is a problem of installation of R on the user's machine.
22 # The advantage compared to the use of stylepath, is that the exported
23 # .tex file will be portable to another machine. (JMarc)
24 ls.sweavesty <- system("kpsewhich Sweave.sty", intern=TRUE, ignore.stderr=TRUE)
25 if (!length(ls.sweavesty)) {
26    stypath <- file.path(R.home("share"), "texmf", "tex", "latex", "Sweave.sty")
27    file.copy(stypath, dirname(ls.args[2]), overwrite=TRUE)
28 }
29
30 # set default encoding for input and output files; ls.enc is used in
31 # the sweave module preamble to reset the encoding to what it was.
32 ls.enc <- getOption("encoding")
33 options(encoding=ls.args[3])
34
35 # Change current directory to the document directory, so that R can find 
36 # data files.
37 setwd(ls.args[4])
38
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(ls.args[2])), fixed = TRUE)
42 # replace 
43 ls.pr <- paste(dirname(ls.args[2]), tmpout, sep="/")
44
45 # finally run sweave
46 Sweave(file=ls.args[1], output=ls.args[2], syntax="SweaveSyntaxNoweb", prefix.string=ls.pr)
47
48 # remove absolute path from \includegraphics
49 ls.doc = readLines(ls.args[2])
50 ls.cmd = paste('\\includegraphics{', dirname(ls.args[2]), "/", sep = "")
51 ls.idx = grep(ls.cmd, ls.doc, fixed = TRUE)
52 if (length(ls.idx)) {
53    ls.doc[ls.idx] = sub(ls.cmd, "\\includegraphics{", ls.doc[ls.idx], fixed = TRUE)
54    writeLines(ls.doc, ls.args[2])
55 }