Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

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

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.

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.

I have an .Rnw file with this code,

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

Thsi creates an .tex file with an illegal LaTeX character. Like this,

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

I'm interested to get an output that looks like this,

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
})

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...