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

Skip to first unread message

Ben Bolker

Feb 11, 2012, 8:43:21 PM2/11/12

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


Now describe the first function and show it:

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:


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?

Ben Bolker

Yihui Xie

Feb 11, 2012, 9:35:47 PM2/11/12
to Ben Bolker,
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: 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.

Yihui Xie <>
Phone: 515-294-2465 Web:
Department of Statistics, Iowa State University
2215 Snedecor Hall, Ames, IA

Reply all
Reply to author
0 new messages