Function to sanitize strings for LaTeX compilation?

时间秒杀一切 提交于 2019-12-10 16:13:00

问题


While xtable() has a sanitize.text.function argument which allows to sanitize strings with special charaters to stop LaTeX compilation from breaking in Sweave/knitr documents, the package does not export the function to the userspace.

How can I sanitize strings like asdf_text outside of the xtable context, so as to have it transformed to something like asdf\_text? (If possible I would prefer a small, self-contained solution.)


回答1:


Unless I misunderstand your question, I think you've overlooked latexTranslate, which is also in the Hmisc package (and documented on the same help page as ?latex):

‘latexTranslate’ translates particular items in character strings to LaTeX format, e.g., makes ‘a^2 = a\$^2\$’ for superscript within variable labels. LaTeX names of greek letters (e.g., ‘"alpha"’) will have backslashes added if ‘greek==TRUE’. Math mode is inserted as needed. ‘latexTranslate’ assumes that input text always has matches, e.g. ‘[) [] (] ()’, and that surrounding by ‘\$\$’ is OK.

library("Hmisc")
latexTranslate("asdf_text")
## [1] "asdf\\_text"
latexTranslate("a^2")
## [1] "a$^{2}$"



回答2:


Thus far I found package reportRx which provides sanitizestr():

Sanitizes strings to not break LaTeX

Strings with special charaters will break LaTeX if returned 'asis' by knitr. This happens every time we use one of the main reportRx functions. We first sanitize our strings with this function to stop LaTeX from breaking.

require(reportRx)
sanitizestr("asdf_text")
## [1] "asdf\\_text"

My gripe however is that it comes with quite a number of dependencies...


Another solution is tikzDevice which provides sanitizeTexString(), and has many fewer mandatory dependencies:

Replace LaTeX Special Characters in a String

This function is used by tikzDevice when sanitize=TRUE to replace special LaTeX characters [..]

require(tikzDevice)
sanitizeTexString("asdf_text")
## [1] "asdf{\\_{}}text"


来源:https://stackoverflow.com/questions/32865384/function-to-sanitize-strings-for-latex-compilation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!