-
-
Notifications
You must be signed in to change notification settings - Fork 878
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
18 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). |