pretty-printing functions (variant of read_chunk?); line numbers?

229 views
Skip to first unread message

Ben Bolker

unread,
Feb 11, 2012, 8:43:21 PM2/11/12
to kn...@googlegroups.com

I have the following use case:

I would like to have a set of functions stored in a separate .R file.
Instead of using read_chunk() to read them all in as a block, I would
like source() the whole file and then display the functions one at a
time, with syntax highlighting.

I can get part of the way there via

<<>>=
source("myfunctions.R")
@

Now describe the first function and show it:
<<echo=FALSE,comment=>>=
first_function
@

But this doesn't get highlighted since it is treated as R *output*
rather than code.

I see that I could do something manual like this:

<<echo=FALSE,results=asis>>=
highlight(textConnection(deparse(first_function)),renderer=renderer_latex(document=FALSE))
@

But there must be a more elegant way to do this via hooks?
(This also drops comments in the source code, which I would like to
retain ...)

on a related note, I can get line numbers in a chunk by (1) installing
highlight 0.3.2 from r-forge and (2) putting show_line_numbers=TRUE into
the hack above; is there a simple/recommended way to enable this in a chunk?

thanks
Ben Bolker

Yihui Xie

unread,
Feb 11, 2012, 9:35:47 PM2/11/12
to Ben Bolker, kn...@googlegroups.com
This may not be a variant of read_chunk(), but it is indeed a very
interesting question. You are already on the right track, and the next
thing to do is to formalize and generalize it as a chunk hook. I have
created a demo here: https://gist.github.com/1805862 One thing to
remember is the chunk should not be empty (you have to put something
in it like comments), otherwise knitr will ignore this chunk.

Line numbers will be supported once highlight is on CRAN. I pinged
Romain twice about this. He seemed to have an unsolved problem with R
CMD check.

Regards,
Yihui
--
Yihui Xie <xiey...@gmail.com>
Phone: 515-294-2465 Web: http://yihui.name
Department of Statistics, Iowa State University
2215 Snedecor Hall, Ames, IA

Reply all
Reply to author
Forward
0 new messages