From ac81dd085eca9e71365743518d8a6a1d56430a68 Mon Sep 17 00:00:00 2001 From: Yihui Xie Date: Mon, 29 May 2023 21:09:33 -0500 Subject: [PATCH] fix #386: use strrep() in base R to generate spaces, which is more efficient than the old knitr:::v_spaces() --- 12-output-hooks.Rmd | 4 ++-- examples/hook-number.Rmd | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/12-output-hooks.Rmd b/12-output-hooks.Rmd index bbb00b44..6637aded 100644 --- a/12-output-hooks.Rmd +++ b/12-output-hooks.Rmd @@ -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. diff --git a/examples/hook-number.Rmd b/examples/hook-number.Rmd index f6cc4503..6a801de1 100644 --- a/examples/hook-number.Rmd +++ b/examples/hook-number.Rmd @@ -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) })