\ Sexpr {} special LaTeX characters ($, &,%, #, etc.) in the .Rnw file

This has something to do with the default built-in hook, I understand that I tried to get it (hook), and also read this topic and the Yihui page about hooks , but I could not solve my problem. I even tried this suggestion from Sacha Epskamp, ​​but in my case it did not help.

I use \Sexpr and do something on the lines \Sexpr{load("meta.data.saved"); meta.data[1,7]} \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) use special LaTeX characters ($, &,%, # etc.), and when they are transferred to my .tex file without \ , I have a bad time.

I have a .Rnw file with this code,

 \documentclass{article} \begin{document} Look \Sexpr{foo <- "me&you"; foo} at this. \end{document} 

Thsi creates a .tex file with the illegal LaTeX symbol. Like this,

 <!-- Preamble omitted for this example. --> \begin{document} Look me&you at this. \end{document} 

I am interested in getting an output that looks like this:

 <!-- Preamble omitted for this example. --> \begin{document} Look me\&you at this. \end{document} 

Sorry for the simple question, but can someone help me, and possibly others, start by changing the default hook for \Sexpr ?

+3
source share
2 answers

The solution provided by @agstudy showed the main 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) }) 

It only changes the built-in hook by default when the built-in result is a character (otherwise use only the default). I have an internal escape_latex() function, which we hope fully escapes all special LaTeX characters.

+7
source

In this case, the hooks work. I configure it as follows:

 inline_hook <- function(x) { x <- gsub("\\&", "\\\\&", x) x <- gsub("\\$", "\\\\$", x) ## good luck for all Latex special character ## $ % _ { } & ~ ^ < > | \ } knit_hooks$set(inline = inline_hook) 

Then

  knit(input='report.Rnw') 

Your report.tex will play.

PS: I think it’s better not to let users do what they want.

+3
source

Source: https://habr.com/ru/post/1492521/


All Articles