In Rnw/LaTeX one use of the common output from knitr hooks might be decorating with some fancy environment the data from chunks.
For example code specific to chunk can produce core data for tables and the hook code before and after provide the repetitive decorations.
Consider the following snippet:
\documentclass{article}
\begin{document}
<<myhooks, include=FALSE>>=
printhook=function(before, options, envir) {
if (before) {
return('\nCommon R \\LaTeX\\ in before-hook')
} else {
return('\nCommon R \\LaTeX\\ in after-hook')
}
}
knit_hooks$set(lprint = printhook)
@
<<test, results='asis', lprint=TRUE, echo=FALSE>>=
cat("R \\LaTeX\\ in current chunk\n")
@
\end{document}
The problem is that the LaTeX output is approx like follows:
\begin{kframe}
Common R \LaTeX\ in before-hook
\end{kframe}
R \LaTeX\ in current chunk
\begin{kframe}
Common R \LaTeX\ in after-hook
\end{kframe}
The hook code is not actually asis, but it gets wrapped in the kframe
environment, which prevents from gluing the three pieces together.
How can we remove the enclosing kframe
?
I do not have an elegant solution for this problem. Below is one possible solution. The basic idea is to replace the output hook chunk
when results == 'asis'
, no source code is echoed, and no plots are produced in a code chunk:
\documentclass{article}
\begin{document}
<<myhooks, include=FALSE>>=
local({
hook_chunk = knit_hooks$get('chunk')
knit_hooks$set(chunk = function(x, options) {
x = hook_chunk(x, options)
if (options$results == 'asis' && !options$echo && options$fig.num == 0) {
# remove all kframe's
gsub('\\\\(begin|end)\\{kframe\\}', '', x)
} else x
})
})
printhook=function(before, options, envir) {
if (before) {
return('\nCommon R \\LaTeX\\ in before-hook')
} else {
return('\nCommon R \\LaTeX\\ in after-hook')
}
}
knit_hooks$set(lprint = printhook)
@
<<test, results='asis', lprint=TRUE, echo=FALSE>>=
cat("R \\LaTeX\\ in current chunk\n")
@
\end{document}