Skip to content

Commit

Permalink
add a demo for pretty printing
Browse files Browse the repository at this point in the history
  • Loading branch information
yihui committed Feb 12, 2012
1 parent d0db78e commit 4892b3a
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions _posts/2012-02-11-pretty.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
layout: default
title: Pretty printing
subtitle: Print highlighted source code of a function
category: demo
---

In the **knitr** mailing list there was a [question](https://groups.google.com/d/topic/knitr/ZTfm9fM6fQs/discussion) on how to print the highlighted source code of functions. It is a good example of showing how to make use of chunk hooks to add extra stuff to a chunk.

Of course it is fairly easy to print the source code of a function, as long as it is available to the user -- just write the name of the function, and R will print its source when this name is evaluated, but the problem is the printed result is treated as text output from a chunk, so it is put in the `verbatim` environment, and nothing is highlighted.

Below is a complete demo showing how to use a chunk hook extract the source code of a function using `dump()`, format the code with the **formatR** package, and finally pass to the **highlight** package. The hook returns a character string, so the result will be written into the output as well.

<script src="https://gist.github.com/1805862.js"> </script>

When we set the custom chunk option `printfun` to be the name of a function, the hook function will be called when the chunk is evaluated because the corresponding chunk option is not `NULL`.

An important thing to remember is the chunk must not be empty (e.g. we can write a comment in it), otherwise **knitr** will skip this chunk. You may wonder why the second `print-my-fun` chunk is empty, and the reason is it borrows code from the first `print-my-fun` chunk since they have the same label (see the [code reference](/knitr/demo/reference/) demo).

0 comments on commit 4892b3a

Please sign in to comment.