9.8 Option hooks

Sometimes you may want to change certain chunk options dynamically according to the values of other chunk options, and you may use the object opts_hooks to set up an option hook to do it. An option hook is a function associated with the option and to be executed when a corresponding chunk option is not NULL. For example, we can tweak the fig.width option so that it is always no smaller than fig.height:

knitr::opts_hooks$set(fig.width = function(options) {
  if (options$fig.width < options$fig.height) {
    options$fig.width <- options$fig.height
  }
  options
})

Because fig.width will never be NULL, this hook function is always executed before a code chunk to update its chunk options. For the code chunk below, the actual value of fig.width will be 6 instead of the initial 5 if the above option hook has been set up:

```{r fig.width = 5, fig.height = 6}
plot(1:10)
```

As another example, we rewrite the last example in Section 9.5 so we can use a single chunk option console = TRUE to imply comment = "" and prompt = TRUE. Note that console is not a built-in knitr chunk option but a custom and arbitrary option name instead. Its default value will be NULL. Below is a full example:

```{r, include=FALSE}
knitr::opts_hooks$set(console = function(options) {
  if (isTRUE(options$console)) {
    options$comment <- ''; options$prompt <- TRUE
  }
  options
})
```

Default output:

```{r}
1 + 1
if (TRUE) {
  2 + 2
}
```

Output with `console = TRUE`:

```{r, console=TRUE}
1 + 1
if (TRUE) {
  2 + 2
}
```