Skip to content

Commit

Permalink
fix #386: use strrep() in base R to generate spaces, which is more ef…
Browse files Browse the repository at this point in the history
…ficient than the old knitr:::v_spaces()
  • Loading branch information
yihui committed May 30, 2023
1 parent 00b23ac commit ac81dd0
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 3 deletions.
4 changes: 2 additions & 2 deletions 12-output-hooks.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,10 @@ The full example is below:

`r import_example('hook-number.Rmd')`

The main trick in the above example is to determine the number of spaces needed before the comment on each line, so the comments can align to the right. The number depends on the widths of each line of code. We leave it to readers to digest the code in the hook function. Note that an internal function `knitr:::v_spaces()`\index{knitr!v\_spaces()} is used to generate spaces of specified lengths, e.g.,
The main trick in the above example is to determine the number of spaces needed before the comment on each line, so the comments can align to the right. The number depends on the widths of each line of code. We leave it to readers to digest the code in the hook function. Note that the function `strrep()` is used to generate spaces of specified lengths, e.g.,

```{r}
knitr:::v_spaces(c(1, 3, 6, 0))
strrep(' ', c(1, 3, 6, 0))
```

The method introduced in Section \@ref(number-lines) may be the actual way in which you want to add line numbers to source code. The syntax is cleaner, and it works for both source code and text output blocks. The above `source` hook trick mainly aims to show you one possibility of manipulating the source code with a custom function.
Expand Down
2 changes: 1 addition & 1 deletion examples/hook-number.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ local({
n <- nchar(x, 'width')
i <- seq_along(x) # line numbers
n <- n + nchar(i)
s <- knitr:::v_spaces(max(n) - n)
s <- strrep(' ', max(n) - n)
x <- paste(x, s, ' # ', i, sep = '', collapse = '\n')
hook_source(x, options)
})
Expand Down

0 comments on commit ac81dd0

Please sign in to comment.