knitr文件在扫描使用\ @xverbatim

时间:2018-05-31 21:18:42

标签: latex knitr sweave rnw

我有以下.Rnw文件:

\documentclass{article}

\usepackage[table]{xcolor}
\usepackage{multicol}

\begin{document}

\begin{multicols}{2}
\hskip-3.5cm\begin{tabular}{|l|}
\hline
\cellcolor[RGB]{0,0,140}{\large\textbf{\textcolor{white}{Bill To: }}}\\
\hline

\textbf{
"asdf"
}\\
\\[-1em]
\textbf{asdf@asdf.com} \\
\hline
\end{tabular}
\hskip6cm\begin{tabular}{|l|l|}
\hline
Date: & 05/31/2018 \\
\hline
Invoice \#: & 1234asdf \\
\hline
\end{tabular}
\end{multicols}


\end{document}

给了我预期的pdf:enter image description here

然而,当我更换" asdf"用R代码:

\documentclass{article}

\usepackage[table]{xcolor}
\usepackage{multicol}

\begin{document}

\begin{multicols}{2}
\hskip-3.5cm\begin{tabular}{|l|}
\hline
\cellcolor[RGB]{0,0,140}{\large\textbf{\textcolor{white}{Bill To: }}}\\
\hline

\textbf{
<<asdf>>=
cat("asdf")
@
}\\
\\[-1em]
\textbf{asdf@asdf.com} \\
\hline
\end{tabular}
\hskip6cm\begin{tabular}{|l|l|}
\hline
Date: & 05/31/2018 \\
\hline
Invoice \#: & 1234asdf \\
\hline
\end{tabular}
\end{multicols}


\end{document}

我收到以下错误:

File ended while scanning use of \@xverbatim

查看生成的.tex文件,这是相关部分:

\textbf{
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{cat}\hlstd{(}\hlstr{"asdf"}\hlstd{)}
\end{alltt}
\begin{verbatim}
## asdf
\end{verbatim}
\end{kframe}
\end{knitrout}
}\\

这就是.log文件所说的内容:

Runaway argument?
 #### asdf \end {verbatim} \end {kframe} \end {knitrout} \check@icr \expandafte
r \ETC.
! File ended while scanning use of \@xverbatim.
<inserted text> 
                \par 
<*> test2.tex

I suspect you have forgotten a `}', causing me
to read past where you wanted me to stop.
I'll try to recover; but if the error is serious,
you'd better type `E' or `X' now and fix your file.

! Emergency stop.
<*> test2.tex

我做错了什么?

1 个答案:

答案 0 :(得分:1)

默认情况下,R输出包含在LaTeX逐字环境中,您不能将其中一个放在\textbf内。有几种不同的方法可以解决这个问题。

最简单的方法是使用块选项results='asis',即

\textbf{
<<asdf,results='asis',echo=FALSE>>=
cat("asdf")
@
}

这将阻止knitr在输出周围添加环境; LaTeX代码只是

\textbf{
asdf
}

应该没问题。

如果您想要默认格式但只想更改文本的字体或样式,事情就更难了。您需要告诉knitr使用其他环境而不是verbatim,例如Verbatim包提供的fancyvrb环境。您可以通过更改输出挂钩来完成此操作。例如,这应该工作

% in the preamble:
\usepackage{fancyvrb}
<<include=FALSE>>=
oldhook <- knitr::knit_hooks$get("output")
bold <- function(x, options)
  paste0("\\begin{Verbatim}[fontseries=b]\n", x, "\\end{Verbatim}")
@

% in the body:
<<asdf,echo=FALSE>>=
knitr::knit_hooks$set(output = bold)
cat("asdf")
@
% Optionally restore the old hook...
<<include=FALSE>>=
knitr::knit_hooks$set(output = oldhook)
@

但是,它并不总是有效,因为某些选项(如fontseries=b)与knitr所做的设置冲突。您可以更改为斜体(使用fontshape=it),但不能更改为粗体。所以坚持第一个建议。