【发布时间】:2020-08-10 12:11:58
【问题描述】:
TL;DR
我希望某些乳胶命令(在本例中为 \definecolor)在某些情况下发生更改,因此我想在 R 中为这些命令创建文本并在标记期间将它们写入标记文件。我还不能使用 knitr hooks 让它完美地工作。
更多细节:
我想在.rnw 文件中定义的颜色数量(和样式)各不相同,因此我避免在.rnw 文件中对\definecolor 调用进行硬编码。
看来我可以用 knitr hooks 做到这一点,而且我非常接近。但我对一些事情感到困惑。
这是一个可重现的示例。 R文件优先
library(RColorBrewer)
library(knitr)
colNames <- c("one","two","three")
txtColors <- sub("#","",brewer.pal(6, "Dark2")[1:3])
# set the knitr hook to create color definitions within the rnw file
knitr::knit_hooks$set(setColors = function(before, options, envir) {
if (!before){
defs <- vector("list",length(txtColors))
for(i in 1:length(txtColors)){
defs[[i]] <- paste0("\\definecolor{",colNames[[i]],"Color}{HTML}{",txtColors[[i]],"}")
}
return(paste0("\\xglobal",unlist(defs), "\n"))
}
})
setwd(file.path("G:", "my", "working", "dir"))
knit2pdf("testColors_s.rnw")
这里还有一个 rnw 文件(将其命名为“testColors_s.rnw”)
\documentclass{article}
\usepackage{xcolor}
\begin{document}
<<setColorHook, setColors = TRUE>>=
@
\textcolor{oneColor}{The first color}
\textcolor{twoColor}{The second color}
\textcolor{threeColor}{The third color}
\end{document}
问题 #1。 我必须使用 \xglobal 全局设置颜色,因为(我猜)knitr 将这些调用放在 kframe 中。我可以制作一个避免 kframe 的钩子吗?还是不需要 xglobal 调用?
问题 #2。 我在运行时收到此警告:Warning message: Package xcolor Warning: Incompatible color definition on input line 57. 这是由 knitr 完成的颜色定义,而不是我。这是 tex 文件中的违规行:
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
如何避免此警告或阻止 knitr 创建此行?
我们将不胜感激有关执行此操作任何部分的任何提示。 提前致谢。
【问题讨论】: