]> git.lyx.org Git - lyx.git/blob - lib/scripts/lyxknitr.R
Merge branch 'master' of git.lyx.org:lyx
[lyx.git] / lib / scripts / lyxknitr.R
1 ## This program is free software; you can redistribute it and/or
2 ## modify it under the terms of the GNU General Public License as
3 ## published by the Free Software Foundation; either version 2 of the
4 ## License, or (at your option) any later version.
5 ##
6 ## This program is distributed in the hope that it will be useful, but
7 ## WITHOUT ANY WARRANTY; without even the implied warranty of
8 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9 ## General Public License for more details.
10
11 ## author Yihui Xie
12
13 ## knitr is an alternative package to Sweave, and has more features
14 ## and flexibility; see https://yihui.github.com/knitr
15
16 ## Rscript $$s/scripts/lyxknitr.R $$p$$i $$p$$o $$e $$r
17 ## $$p the path of the output (temp dir)
18 ## $$i the file name of the input Rnw
19 ## $$o the tex output
20 ## $$r path to the original input file (the lyx document)
21 ## $$e encoding (e.g. 'UTF-8')
22
23 library(knitr)
24
25 .cmdargs = commandArgs(TRUE)
26
27 .orig.enc = getOption("encoding")
28 options(encoding = .cmdargs[3])
29
30 ## the working directory is the same with the original .lyx file; you
31 ## can put your data files there and functions like read.table() can
32 ## work correctly without specifying the full path
33 setwd(.cmdargs[4])
34
35 ## copy the Rnw file to the current working directory if it does not exist
36 .tmp.file = tempfile(); .rnw.file = basename(.cmdargs[1])
37 .rnw.exists = file.exists(.rnw.file)
38 if (.rnw.exists) file.rename(.rnw.file, .tmp.file)
39 file.copy(.cmdargs[1], '.')
40 ## run knit() to get .tex or .R
41 knit(.rnw.file, tangle = 'tangle' %in% .cmdargs)
42
43 setwd(.cmdargs[4])
44 ## remove the copied .Rnw if it did not exist, otherwise move the original one back
45 if (.rnw.exists) file.rename(.tmp.file, .rnw.file) else unlink(.rnw.file)
46 file.rename(basename(.cmdargs[2]), .cmdargs[2])  # move .tex to the temp dir
47 rm(.tmp.file, .rnw.file, .rnw.exists)  # clean up these variables
48