.Rnw文件中的\ Sexpr {}特殊LaTeX字符($,&,%,#等) [英] \Sexpr{} special LaTeX characters ($, &, %, # etc.) in .Rnw-file
问题描述
这与默认的内联挂钩有关,我意识到这一点,并且我已经尝试过使用它(挂钩),并且还阅读了有关钩子的页面,但我无法解决我的问题.我什至尝试了Sacha Epskamp的此建议,但就我而言,它并没有解决这个问题.
It has something to do with the default inline hook, I realize that and I have tried getting at it (the hook) and also read this thread and Yihui's page about hooks, but I haven't been able to solve my issue. I even tried this suggestion from Sacha Epskamp, but it didn't do this trick in my case.
我正在使用\Sexpr
并按照\Sexpr{load("meta.data.saved"); meta.data[1,7]}
的方式执行一些操作以在报告中打印关键字,问题是写这些关键字的人(我无法控制的人)正在使用特殊的LaTeX字符( $,&,%,#等),并且在没有\
的情况下将它们传递到我的.tex文件时,我遇到了麻烦.
I'm using \Sexpr
and doing something along the lines of \Sexpr{load("meta.data.saved"); meta.data[1,7]}
to print a keyword in my report, the problem is that people writing these keywords (people I can't control) are using special LaTeX characters ($, &, %, # etc.) and when they are passed to my .tex file without an \
I'm having a bad time.
我有一个带有此代码的.Rnw文件,
I have an .Rnw file with this code,
\documentclass{article}
\begin{document}
Look \Sexpr{foo <- "me&you"; foo} at this.
\end{document}
Thsi创建一个带有非法LaTeX字符的.tex文件.像这样
Thsi creates an .tex file with an illegal LaTeX character. Like this,
<!-- Preamble omitted for this example. -->
\begin{document}
Look me&you at this.
\end{document}
我有兴趣获得如下所示的输出
I'm interested to get an output that looks like this,
<!-- Preamble omitted for this example. -->
\begin{document}
Look me\&you at this.
\end{document}
很抱歉这个简单的问题,但是有人可以帮助我,也许其他人也可以开始如何为\Sexpr
修改默认的内联挂钩吗?
Sorry for the simple question, but can someone help me, and maybe others, getting starting on how to modify the default inline hook for \Sexpr
?
推荐答案
@agstudy提供的解决方案显示了基本思想,下面是一个更强大的版本:
The solution provided by @agstudy has shown the basic idea, and here is a more robust version:
hook_inline = knit_hooks$get('inline')
knit_hooks$set(inline = function(x) {
if (is.character(x)) x = knitr:::escape_latex(x)
hook_inline(x)
})
仅当内联结果为character时才修改默认的内联钩子(否则只使用默认的钩子).我有一个内部函数escape_latex()
,希望可以正确地转义所有特殊的LaTeX字符.
It only modifies the default inline hook when the inline result is character (otherwise just use the default hook). I have an internal function escape_latex()
which hopefully escapes all special LaTeX characters correctly.
这篇关于.Rnw文件中的\ Sexpr {}特殊LaTeX字符($,&,%,#等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!