Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add labels to the default progress bar and allow users to provide a custom progress bar #2196

Merged
merged 5 commits into from
Nov 24, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions R/output.R
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,9 @@ process_file = function(text, output) {
labels = unlist(lapply(groups, function(g) {
if (is.list(g$params)) g[[c('params', 'label')]] else ''
}))
pb = txtProgressBar(0, n, char = '.', style = 3)
on.exit(close(pb), add = TRUE)
pb_fun = getOption('knitr.progress.fun', txt_pb)
pb = if (is.function(pb_fun)) pb_fun(n, labels)
on.exit(if (!is.null(pb)) pb$done(), add = TRUE)
}
wd = getwd()
for (i in 1:n) {
Expand All @@ -302,7 +303,7 @@ process_file = function(text, output) {
}
break # must have called knit_exit(), so exit early
}
if (progress) setTxtProgressBar(pb, i)
if (progress && !is.null(pb)) pb$update(i)
group = groups[[i]]
res[i] = withCallingHandlers(
if (tangle) process_tangle(group) else process_group(group),
Expand Down
1 change: 0 additions & 1 deletion R/parser.R
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,6 @@ get_option_comment = function(engine) {

print.block = function(x, ...) {
params = x$params
cat(' chunk:', params$label, '\n')
if (opts_knit$get('verbose')) {
code = knit_code$get(params$label)
if (length(code) && !is_blank(code)) {
Expand Down
24 changes: 24 additions & 0 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -1085,3 +1085,27 @@ str_split = function(x, split, ...) {
y[x == ''] = list('')
y
}

# default progress bar function in knitr: create a text progress bar, and return
# methods to update/close it
txt_pb = function(total, labels) {
s = ifelse(labels == '', '', sprintf(' (%s)', labels)) # chunk labels in ()
w = nchar(s) # widths of labels
n = max(w)
# right-pad spaces for same width of all labels so a wider label of the
# progress bar in a previous step could be completely wiped (by spaces)
s = paste0(s, strrep(' ', n - w))
w2 = getOption('width')
pb = txtProgressBar(0, total, 0, '.', width = max(w2 - 10 - n, 10), style = 3)
list(
update = function(i) {
setTxtProgressBar(pb, i)
cat(s[i]) # append chunk label to the progress bar
},
done = function() {
# wipe the progress bar
cat(paste0('\r', strrep(' ', max(w2, 10) + 10 + n)))
close(pb)
}
)
}