1 |
## state completely sucks and I hate it, but |
|
2 |
## we need a pdf device open to calculate the |
|
3 |
## print width of strings, and we can't be opening |
|
4 |
## a new one every time we want to |
|
5 |
font_dev_state <- new.env() |
|
6 |
font_dev_state$open <- FALSE |
|
7 |
font_dev_state$fontspec <- list() |
|
8 |
font_dev_state$spacewidth <- NA_real_ |
|
9 |
font_dev_state$ismonospace <- NA |
|
10 |
font_dev_state$max_ratio <- NA_real_ |
|
11 |
font_dev_state$dev_num <- NA_integer_ |
|
12 |
font_dev_state$debug_active <- FALSE |
|
13 | ||
14 | ||
15 |
cwidth_inches_unsafe <- function(x) { |
|
16 | 1118x |
convertWidth(unit(1, "strwidth", x), "inches", valueOnly = TRUE) |
17 |
} |
|
18 | ||
19 |
## returns whether it opened a new device or not |
|
20 |
#' Activate font state |
|
21 |
#' |
|
22 |
#' @param fontspec (`font_spec`)\cr a font_spec object specifying the font information to use for |
|
23 |
#' calculating string widths and heights, as returned by [font_spec()]. |
|
24 |
#' @param silent (`logical(1)`)\cr If `FALSE`, the default, a warning will be |
|
25 |
#' emitted if this function switches away from an active graphics device. |
|
26 |
#' |
|
27 |
#' @details The font device state is an environment with |
|
28 |
#' four variables guaranteed to be set: |
|
29 |
#' |
|
30 |
#' \describe{ |
|
31 |
#' \item{`open`}{(`logical(1)`)\cr whether a device is already open with font info} |
|
32 |
#' \item{`fontspec`}{(`font_spec`)\cr the font specification, if any, that is currently active (`list()` if none is).} |
|
33 |
#' \item{`spacewidth`}{(`numeric(1)`)\cr the width of the space character in the currently active font.} |
|
34 |
#' \item{`ismonospace`}{(`logical(1)`)\cr whether the specified font is monospaced.} |
|
35 |
#' } |
|
36 |
#' |
|
37 |
#' `open_font_dev` opens a pdf device with the specified font |
|
38 |
#' only if there is not one currently open with the same font. |
|
39 |
#' If a new device is opened, it caches `spacewidth` and |
|
40 |
#' `ismonospace` for use in `nchar_ttype`). |
|
41 |
#' |
|
42 |
#' `close_font_dev` closes any open font state device |
|
43 |
#' and clears the cached values. |
|
44 |
#' |
|
45 |
#' `debug_font_dev` and `undebug_font_dev` activate and deactivate, respectively, |
|
46 |
#' logging of where in the call stack font devices are being opened. |
|
47 |
#' |
|
48 |
#' @return |
|
49 |
#' - `open_font_dev` returns a logical value indicating whether a *new* pdf device was opened. |
|
50 |
#' - `close_font_dev`, `debug_font_dev` and `undebug_font_dev` return `NULL`. |
|
51 |
#' |
|
52 |
#' In all cases the value is returned invisibly. |
|
53 |
#' |
|
54 |
#' @examples |
|
55 |
#' open_font_dev(font_spec("Times")) |
|
56 |
#' nchar_ttype("Hiya there", font_spec("Times")) |
|
57 |
#' close_font_dev() |
|
58 |
#' |
|
59 |
#' @export |
|
60 |
open_font_dev <- function(fontspec, silent = FALSE) { |
|
61 | 82190x |
if (is.null(fontspec)) { |
62 | 1x |
return(invisible(FALSE)) |
63 | 82188x |
} else if (font_dev_is_open()) { |
64 | 81687x |
if (identical(font_dev_state$fontspec, fontspec)) { |
65 | 81686x |
if (!silent && dev.cur() != font_dev_state$dev_num) { |
66 | 1x |
warning( |
67 | 1x |
"formatters is switching to the font state graphics device ", |
68 | 1x |
"to perform string width calculations. You may need to switch ", |
69 | 1x |
"to your currently open graphics device, depending on whether ", |
70 | 1x |
"the font device is closed and what other devices you have open." |
71 |
) |
|
72 | 1x |
dev.set(font_dev_state$dev_num) |
73 |
} |
|
74 | 81686x |
return(invisible(FALSE)) |
75 |
} else { |
|
76 | 1x |
close_font_dev() |
77 |
} |
|
78 |
} |
|
79 | 502x |
if (font_dev_state$debug_active && !font_dev_is_open()) { ## call debug_font_dev beforehand to get debugging info to helplocate places which aren't receiving/using the state properly # nolint |
80 |
## dump the call stack any time we have cache misses |
|
81 |
## and have to open a completely new font state device |
|
82 | 1x |
scalls <- sys.calls() |
83 | 1x |
msg <- sapply( |
84 | 1x |
scalls[2:length(scalls)], |
85 | 1x |
function(sci) { |
86 | 42x |
toret <- deparse(sci[[1]], nlines = 3) |
87 | 42x |
if (substr(toret[1], 1, 8) == "function") { |
88 | ! |
toret <- "anon function" |
89 |
} |
|
90 | 42x |
toret |
91 |
} |
|
92 |
) |
|
93 | 1x |
message(paste("\n***** START font dev debugging dump *****\n", |
94 | 1x |
paste(msg, collapse = " -> "), |
95 | 1x |
paste(capture.output(print(fontspec)), collapse = "\n"), |
96 | 1x |
sep = "\n" |
97 |
)) |
|
98 |
} |
|
99 | 502x |
tmppdf <- tempfile(fileext = ".pdf") |
100 | 502x |
pdf(tmppdf) |
101 | 502x |
grid.newpage() |
102 | 502x |
gp <- gpar_from_fspec(fontspec) |
103 | 502x |
pushViewport(plotViewport(gp = gp)) |
104 | 502x |
spcwidth <- cwidth_inches_unsafe(" ") |
105 | 502x |
assign("open", TRUE, envir = font_dev_state) |
106 | 502x |
assign("fontspec", fontspec, envir = font_dev_state) |
107 | 502x |
assign("spacewidth", spcwidth, envir = font_dev_state) |
108 | 502x |
assign("ismonospace", spcwidth == cwidth_inches_unsafe("W"), |
109 | 502x |
envir = font_dev_state |
110 |
) |
|
111 | 502x |
assign("dev_num", dev.cur(), |
112 | 502x |
envir = font_dev_state |
113 |
) |
|
114 | 502x |
invisible(TRUE) |
115 |
} |
|
116 | ||
117 |
#' @rdname open_font_dev |
|
118 |
#' @export |
|
119 |
close_font_dev <- function() { |
|
120 | 502x |
if (font_dev_state$open) { |
121 | 502x |
dev.off(font_dev_state$dev_num) |
122 | 502x |
assign("open", FALSE, envir = font_dev_state) |
123 | 502x |
assign("fontspec", list(), envir = font_dev_state) |
124 | 502x |
assign("spacewidth", NA_real_, envir = font_dev_state) |
125 | 502x |
assign("ismonospace", NA, envir = font_dev_state) |
126 | 502x |
assign("dev_num", NA_integer_, envir = font_dev_state) |
127 |
} |
|
128 | 502x |
invisible(NULL) |
129 |
} |
|
130 | ||
131 |
#' @rdname open_font_dev |
|
132 |
#' @export |
|
133 |
debug_font_dev <- function() { |
|
134 | 1x |
message("debugging font device swapping. call undebug_font_dev() to turn debugging back off.") |
135 | 1x |
font_dev_state$debug_active <- TRUE |
136 | 1x |
invisible(NULL) |
137 |
} |
|
138 | ||
139 |
#' @rdname open_font_dev |
|
140 |
#' @export |
|
141 |
undebug_font_dev <- function() { |
|
142 | 1x |
message("no longer debugging font device swapping.") |
143 | 1x |
font_dev_state$debug_active <- FALSE |
144 | 1x |
invisible(NULL) |
145 |
} |
|
146 | ||
147 | ||
148 |
## can only be called when font_dev_state$open is TRUE |
|
149 |
get_space_width <- function() { |
|
150 | 25x |
if (!font_dev_is_open()) { |
151 | 1x |
stop( |
152 | 1x |
"get_space_width called when font dev state is not open. ", |
153 | 1x |
"This shouldn't happen, please contact the maintainers." |
154 |
) |
|
155 |
} |
|
156 | 24x |
font_dev_state$spacewidth |
157 |
} |
|
158 | ||
159 |
.open_fdev_is_monospace <- function() { |
|
160 | 32643x |
if (!font_dev_is_open()) { |
161 | 2x |
stop( |
162 | 2x |
".open_fdev_is_monospace called when font dev state is not open. ", |
163 | 2x |
"This shouldn't happen, please contact the maintainers." |
164 |
) |
|
165 |
} |
|
166 | 32641x |
font_dev_state$ismonospace |
167 |
} |
|
168 | ||
169 |
## safe wrapper around .open_fdev_is_monospace |
|
170 |
is_monospace <- function(fontspec = font_spec(font_family, font_size, lineheight), |
|
171 |
font_family = "Courier", |
|
172 |
font_size = 8, |
|
173 |
lineheight = 1) { |
|
174 | 32642x |
if (is.null(fontspec)) { |
175 | 1x |
return(TRUE) |
176 |
} |
|
177 | 32641x |
new_dev <- open_font_dev(fontspec) |
178 | 32641x |
if (new_dev) { |
179 | 31x |
on.exit(close_font_dev()) |
180 |
} |
|
181 | 32641x |
.open_fdev_is_monospace() |
182 |
} |
|
183 | ||
184 |
## get_max_wratio <- function() { |
|
185 |
## if (!font_dev_state$open) { |
|
186 |
## stop( |
|
187 |
## "get_space_width called when font dev state is not open. ", |
|
188 |
## "This shouldn't happen, please contact the maintainers." |
|
189 |
## ) |
|
190 |
## } |
|
191 |
## if (.open_fdev_is_monospace()) { |
|
192 |
## 1 |
|
193 |
## } else { |
|
194 |
## font_dev_state$maxratio |
|
195 |
## } |
|
196 |
## } |
|
197 | ||
198 |
gpar_from_fspec <- function(fontspec) { |
|
199 | 508x |
gpar( |
200 | 508x |
fontfamily = fontspec$family, |
201 | 508x |
fontsize = fontspec$size, |
202 | 508x |
lineheight = fontspec$lineheight |
203 |
) |
|
204 |
} |
|
205 | ||
206 | 114857x |
font_dev_is_open <- function() font_dev_state$open |
207 | ||
208 |
#' Default horizontal separator |
|
209 |
#' |
|
210 |
#' The default horizontal separator character which can be displayed in the current |
|
211 |
#' charset for use in rendering table-like objects. |
|
212 |
#' |
|
213 |
#' @param hsep_char (`string`)\cr character that will be set in the R environment |
|
214 |
#' options as the default horizontal separator. Must be a single character. Use |
|
215 |
#' `getOption("formatters_default_hsep")` to get its current value (`NULL` if not set). |
|
216 |
#' |
|
217 |
#' @return unicode 2014 (long dash for generating solid horizontal line) if in a |
|
218 |
#' locale that uses a UTF character set, otherwise an ASCII hyphen with a |
|
219 |
#' once-per-session warning. |
|
220 |
#' |
|
221 |
#' @examples |
|
222 |
#' default_hsep() |
|
223 |
#' set_default_hsep("o") |
|
224 |
#' default_hsep() |
|
225 |
#' |
|
226 |
#' @name default_horizontal_sep |
|
227 |
#' @export |
|
228 |
default_hsep <- function() { |
|
229 |
system_default_hsep <- getOption("formatters_default_hsep") |
|
230 | ||
231 |
if (is.null(system_default_hsep)) { |
|
232 |
if (any(grepl("^UTF", utils::localeToCharset()))) { |
|
233 |
hsep <- "\u2014" |
|
234 |
} else { |
|
235 |
if (interactive()) { |
|
236 |
warning( |
|
237 |
"Detected non-UTF charset. Falling back to '-' ", |
|
238 |
"as default header/body separator. This warning ", |
|
239 |
"will only be shown once per R session." |
|
240 |
) # nocov |
|
241 |
} # nocov |
|
242 |
hsep <- "-" # nocov |
|
243 |
} |
|
244 |
} else { |
|
245 |
hsep <- system_default_hsep |
|
246 |
} |
|
247 |
hsep |
|
248 |
} |
|
249 | ||
250 |
#' @name default_horizontal_sep |
|
251 |
#' @export |
|
252 |
set_default_hsep <- function(hsep_char) { |
|
253 |
checkmate::assert_character(hsep_char, n.chars = 1, len = 1, null.ok = TRUE) |
|
254 |
options("formatters_default_hsep" = hsep_char) |
|
255 |
} |
|
256 | ||
257 |
.calc_cell_widths <- function(mat, colwidths, col_gap) { |
|
258 | 363x |
spans <- mat$spans |
259 | 363x |
keep_mat <- mat$display |
260 | 363x |
body <- mat$strings |
261 | ||
262 | 363x |
nr <- nrow(body) |
263 | ||
264 | 363x |
cell_widths_mat <- matrix(rep(colwidths, nr), nrow = nr, byrow = TRUE) |
265 | 363x |
nc <- ncol(cell_widths_mat) |
266 | ||
267 | 363x |
for (i in seq_len(nrow(body))) { |
268 | 6517x |
if (any(!keep_mat[i, ])) { # any spans? |
269 | 6x |
j <- 1 |
270 | 6x |
while (j <= nc) { |
271 | 10x |
nj <- spans[i, j] |
272 | 10x |
j <- if (nj > 1) { |
273 | 6x |
js <- seq(j, j + nj - 1) |
274 | 6x |
cell_widths_mat[i, js] <- sum(cell_widths_mat[i, js]) + col_gap * (nj - 1) |
275 | 6x |
j + nj |
276 |
} else { |
|
277 | 4x |
j + 1 |
278 |
} |
|
279 |
} |
|
280 |
} |
|
281 |
} |
|
282 | 363x |
cell_widths_mat |
283 |
} |
|
284 | ||
285 |
# Main function that does the wrapping |
|
286 |
do_cell_fnotes_wrap <- function(mat, widths, max_width, tf_wrap, fontspec, expand_newlines = TRUE) { |
|
287 | 210x |
col_gap <- mf_colgap(mat) |
288 | 210x |
ncchar <- sum(widths) + (length(widths) - as.integer(mf_has_rlabels(mat))) * col_gap |
289 | 210x |
inset <- table_inset(mat) |
290 | ||
291 |
## Text wrapping checks |
|
292 | 210x |
if (tf_wrap) { |
293 | 92x |
if (is.null(max_width)) { |
294 | 24x |
max_width <- getOption("width", 80L) |
295 | 68x |
} else if (is.character(max_width) && identical(max_width, "auto")) { |
296 | ! |
max_width <- ncchar + inset |
297 |
} |
|
298 | 92x |
assert_number(max_width, lower = 0) |
299 |
} |
|
300 | ||
301 |
## Check for having the right number of widths |
|
302 | 210x |
stopifnot(length(widths) == ncol(mat$strings)) |
303 | ||
304 |
## format the to ASCII |
|
305 | 210x |
cell_widths_mat <- .calc_cell_widths(mat, widths, col_gap) |
306 | ||
307 |
# Check that indentation is correct (it works only for body) |
|
308 | 210x |
.check_indentation(mat, row_col_width = cell_widths_mat[, 1, drop = TRUE]) |
309 | 207x |
mod_ind_list <- .modify_indentation(mat, cell_widths_mat, do_what = "remove") |
310 | 207x |
mfs <- mod_ind_list[["mfs"]] |
311 | 207x |
cell_widths_mat <- mod_ind_list[["cell_widths_mat"]] |
312 | ||
313 |
# Main wrapper |
|
314 | 207x |
mf_strings(mat) <- matrix( |
315 | 207x |
unlist(mapply(wrap_string, |
316 | 207x |
str = mfs, |
317 | 207x |
width = cell_widths_mat, |
318 | 207x |
collapse = "\n", |
319 | 207x |
MoreArgs = list(fontspec = fontspec) |
320 |
)), |
|
321 | 207x |
ncol = ncol(mfs) |
322 |
) |
|
323 | ||
324 | 207x |
if (expand_newlines) { |
325 |
## XXXXX this is wrong and will break for listings cause we don't know when |
|
326 |
## we need has_topleft to be FALSE!!!!!!!!!! |
|
327 | 207x |
mat <- mform_handle_newlines(mat) |
328 | ||
329 |
## this updates extents in rinfo AND nlines in ref_fnotes_df |
|
330 |
## mat already has fontspec on it so no need to pass that down |
|
331 | 207x |
mat <- update_mf_nlines(mat, max_width = max_width) |
332 | ||
333 |
# Re-indenting |
|
334 | 207x |
mf_strings(mat) <- .modify_indentation(mat, cell_widths_mat, do_what = "add")[["mfs"]] |
335 | 207x |
.check_indentation(mat) # all went well |
336 |
} |
|
337 | 207x |
mat |
338 |
} |
|
339 | ||
340 |
# Helper function to see if body indentation matches (minimum) |
|
341 |
# It sees if there is AT LEAST the indentation contained in rinfo |
|
342 |
.check_indentation <- function(mat, row_col_width = NULL) { |
|
343 |
# mf_nrheader(mat) # not useful |
|
344 | 418x |
mf_nlh <- mf_nlheader(mat) |
345 | 418x |
mf_lgrp <- mf_lgrouping(mat) |
346 | 418x |
mf_str <- mf_strings(mat) |
347 |
# we base everything on the groupings -> unique indentation identifiers |
|
348 | 418x |
if (!is.null(mf_rinfo(mat))) { # this happens in rare cases with rtables::rtable() |
349 | 418x |
mf_ind <- c(rep(0, mf_nrheader(mat)), mf_rinfo(mat)$indent) # XXX to fix with topleft |
350 |
} else { |
|
351 | ! |
mf_ind <- rep(0, mf_nrheader(mat)) |
352 |
} |
|
353 | 418x |
ind_std <- paste0(rep(" ", mat$indent_size), collapse = "") |
354 | ||
355 |
# Expected indent (-x negative numbers should not appear at this stage) |
|
356 | 418x |
stopifnot(all(mf_ind >= 0)) |
357 | 418x |
real_indent <- vapply(mf_ind, function(ii) { |
358 | 7821x |
paste0(rep(ind_std, ii), collapse = "") |
359 | 418x |
}, character(1)) |
360 | ||
361 | 418x |
if (!is.null(row_col_width) && any(row_col_width > 0) && !is.null(mf_rinfo(mat))) { # third is rare case |
362 |
# Self consistency test for row_col_width (same groups should have same width) |
|
363 |
# This should not be necessary (nocov) |
|
364 | 210x |
consistency_check <- vapply(unique(mf_lgrp), function(ii) { |
365 | 3929x |
width_per_grp <- row_col_width[which(mf_lgrp == ii)] |
366 | 3929x |
all(width_per_grp == width_per_grp[1]) |
367 | 210x |
}, logical(1)) |
368 | 210x |
stopifnot(all(consistency_check)) |
369 | ||
370 |
# Taking only one width for each indentation grouping |
|
371 | 210x |
unique_row_col_width <- row_col_width[match(unique(mf_lgrp), mf_lgrp)] |
372 | ||
373 |
# Exception for check: case with summarize_row_groups and (hence) content_rows |
|
374 | 210x |
nchar_real_indent <- nchar(real_indent) |
375 | 210x |
body_rows <- seq(mf_nrheader(mat) + 1, length(nchar_real_indent)) |
376 | 210x |
nchar_real_indent[body_rows] <- nchar_real_indent[body_rows] + |
377 | 210x |
as.numeric(mf_rinfo(mat)$node_class != "ContentRow") |
378 |
# xxx I think all of the above is a bit buggy honestly (check ContentRows!!!) |
|
379 | ||
380 | 210x |
if (any(nchar_real_indent > unique_row_col_width)) { |
381 | 2x |
stop( |
382 | 2x |
"Inserted width for row label column is not wide enough. ", |
383 | 2x |
"We found the following rows that do not have at least indentation * ind_size + 1", |
384 | 2x |
" characters to allow text to be shown after indentation: ", |
385 | 2x |
paste0(which(nchar(real_indent) + 1 > unique_row_col_width), collapse = " ") |
386 |
) |
|
387 |
} |
|
388 |
} |
|
389 | ||
390 |
# Main detector |
|
391 | 416x |
correct_indentation <- vapply(seq_along(mf_lgrp), function(xx) { |
392 | 8249x |
grouping <- mf_lgrp[xx] |
393 | 8249x |
if (nzchar(real_indent[grouping])) { |
394 | 33x |
has_correct_indentation <- stringi::stri_detect( |
395 | 33x |
mf_str[xx, 1], |
396 | 33x |
regex = paste0("^", real_indent[grouping]) |
397 |
) |
|
398 | 33x |
return(has_correct_indentation || !nzchar(mf_str[xx, 1])) # "" is still an ok indentation |
399 |
} |
|
400 |
# Cases where no indent are true by definition |
|
401 | 8216x |
return(TRUE) |
402 | 416x |
}, logical(1)) |
403 | ||
404 | 416x |
if (any(!correct_indentation)) { |
405 | 1x |
stop( |
406 | 1x |
"We discovered indentation mismatches between the matrix_form and the indentation", |
407 | 1x |
" predefined in mf_rinfo. This should not happen. Contact the maintainer." |
408 | 1x |
) # nocov |
409 |
} |
|
410 |
} |
|
411 | ||
412 |
# Helper function that takes out or adds the proper indentation |
|
413 |
.modify_indentation <- function(mat, cell_widths_mat, do_what = c("remove", "add")) { |
|
414 |
# Extract info |
|
415 | 414x |
mfs <- mf_strings(mat) # we work on mfs |
416 | 414x |
mf_nlh <- mf_nlheader(mat) |
417 | 414x |
mf_l <- mf_lgrouping(mat) |
418 | 414x |
if (!is.null(mf_rinfo(mat))) { # this happens in rare cases with rtables::rtable() |
419 | 414x |
mf_ind <- c(rep(0, mf_nrheader(mat)), mf_rinfo(mat)$indent) # XXX to fix with topleft |
420 |
} else { |
|
421 | ! |
mf_ind <- rep(0, mf_nrheader(mat)) |
422 |
} |
|
423 | 414x |
stopifnot(length(mf_ind) == length(unique(mf_l))) # Check for indentation and grouping |
424 | 414x |
ind_std <- paste0(rep(" ", mat$indent_size), collapse = "") # standard size of indent 1 |
425 | ||
426 |
# Create real indentation |
|
427 | 414x |
real_indent <- sapply(mf_ind, function(ii) paste0(rep(ind_std, ii), collapse = "")) |
428 | ||
429 |
# Use groupings to add or remove proper indentation |
|
430 | 414x |
lbl_row <- mfs[, 1, drop = TRUE] |
431 | 414x |
for (ii in seq_along(lbl_row)) { |
432 | 8240x |
grp <- mf_l[ii] |
433 | 8240x |
if (nzchar(real_indent[grp])) { |
434 |
# Update also the widths!! |
|
435 | 29x |
if (do_what[1] == "remove") { |
436 | 9x |
cell_widths_mat[ii, 1] <- cell_widths_mat[ii, 1] - nchar(real_indent[grp]) |
437 | 9x |
mfs[ii, 1] <- stringi::stri_replace(lbl_row[ii], "", regex = paste0("^", real_indent[grp])) |
438 | 20x |
} else if (do_what[1] == "add") { |
439 | 20x |
mfs[ii, 1] <- paste0(real_indent[grp], lbl_row[ii]) |
440 |
} else { |
|
441 |
stop("do_what needs to be remove or add.") # nocov |
|
442 |
} |
|
443 |
} else { |
|
444 | 8211x |
mfs[ii, 1] <- lbl_row[ii] |
445 |
} |
|
446 |
} |
|
447 |
# Final return |
|
448 | 414x |
return(list("mfs" = mfs, "cell_widths_mat" = cell_widths_mat)) |
449 |
} |
|
450 | ||
451 |
## take a character vector and return whether the value is |
|
452 |
## a string version of a number or not |
|
453 |
is_number_str <- function(vec) { |
|
454 | ! |
is.na(as.numeric(vec)) |
455 |
} |
|
456 | ||
457 |
is_dec_align <- function(vec) { |
|
458 |
# "c" is not an alignment method we define in `formatters`, |
|
459 |
# but the reverse dependency package `tables` will need |
|
460 | 595x |
sdiff <- setdiff(vec, c(list_valid_aligns(), "c")) |
461 | 595x |
if (length(sdiff) > 0) { |
462 | ! |
stop("Invalid text-alignment(s): ", paste(sdiff, collapse = ", ")) |
463 |
} |
|
464 | 595x |
grepl("dec", vec) |
465 |
} |
|
466 | ||
467 | 450x |
any_dec_align <- function(vec) any(is_dec_align(vec)) |
468 | ||
469 |
#' Decimal alignment |
|
470 |
#' |
|
471 |
#' Aligning decimal values of string matrix. Allowed alignments are: `dec_left`, `dec_right`, |
|
472 |
#' and `decimal`. |
|
473 |
#' |
|
474 |
#' @param string_mat (`character matrix`)\cr "string" matrix component of `MatrixPrintForm` object. |
|
475 |
#' @param align_mat (`character matrix`)\cr "aligns" matrix component of `MatrixPrintForm` object. |
|
476 |
#' Should contain either `dec_left`, `dec_right`, or `decimal` for values to be decimal aligned. |
|
477 |
#' |
|
478 |
#' @details Left and right decimal alignment (`dec_left` and `dec_right`) differ from center decimal |
|
479 |
#' alignment (`decimal`) only when there is padding present. This may occur if column widths are |
|
480 |
#' set wider via parameters `widths` in `toString` or `colwidths` in `paginate_*`. More commonly, |
|
481 |
#' it also occurs when column names are wider. Cell wrapping is not supported when decimal |
|
482 |
#' alignment is used. |
|
483 |
#' |
|
484 |
#' @return A processed string matrix of class `MatrixPrintForm` with decimal-aligned values. |
|
485 |
#' |
|
486 |
#' @seealso [toString()], [MatrixPrintForm()] |
|
487 |
#' |
|
488 |
#' @examples |
|
489 |
#' dfmf <- basic_matrix_form(mtcars[1:5, ]) |
|
490 |
#' aligns <- mf_aligns(dfmf) |
|
491 |
#' aligns[, -c(1)] <- "dec_left" |
|
492 |
#' decimal_align(mf_strings(dfmf), aligns) |
|
493 |
#' |
|
494 |
#' @export |
|
495 |
decimal_align <- function(string_mat, align_mat) { |
|
496 |
## Evaluate if any values are to be decimal aligned |
|
497 | 45x |
if (!any_dec_align(align_mat)) { |
498 | ! |
return(string_mat) |
499 |
} |
|
500 | 45x |
for (i in seq(1, ncol(string_mat))) { |
501 |
## Take a column and its decimal alignments |
|
502 | 145x |
col_i <- as.character(string_mat[, i]) |
503 | 145x |
align_col_i <- is_dec_align(align_mat[, i]) |
504 | ||
505 |
## !( A || B) -> !A && !B DeMorgan's Law |
|
506 |
## Are there any values to be decimal aligned? safe if |
|
507 | 145x |
if (any(align_col_i) && any(!grepl("^[0-9]\\.", col_i))) { |
508 |
## Extract values not to be aligned (NAs, non-numbers, |
|
509 |
## doesn't say "decimal" in alignment matrix) |
|
510 |
## XXX FIXME because this happens after formatting, we can't tell the difference between |
|
511 |
## non-number strings which come from na_str+ NA value and strings which just aren't numbers. |
|
512 |
## this is a problem that should eventually be fixed. |
|
513 | 82x |
nas <- vapply(col_i, is.na, FUN.VALUE = logical(1)) |
514 | 82x |
nonnum <- !grepl("[0-9]", col_i) |
515 |
## No grepl("[a-zA-Z]", col_i) because this excludes N=xx, e.g. |
|
516 | 82x |
nonalign <- nas | nonnum | !align_col_i |
517 | 82x |
col_ia <- col_i[!nonalign] |
518 | ||
519 |
## Do decimal alignment |
|
520 | 82x |
if (length(col_ia) > 0) { |
521 |
# Special case: scientific notation |
|
522 | 82x |
has_sc_not <- grepl("\\d+[e|E][\\+|\\-]\\d+", col_ia) |
523 | 82x |
if (any(has_sc_not)) { |
524 | 1x |
stop( |
525 | 1x |
"Found values using scientific notation between the ones that", |
526 | 1x |
" needs to be decimal aligned (aligns is decimal, dec_left or dec_right).", |
527 | 1x |
" Please consider using format functions to get a complete decimal ", |
528 | 1x |
"(e.g. formatC)." |
529 |
) |
|
530 |
} |
|
531 | ||
532 |
## Count the number of numbers in the string |
|
533 | 81x |
matches <- gregexpr("\\d+\\.\\d+|\\d+", col_ia) |
534 | 81x |
more_than_one <- vapply(matches, function(x) { |
535 | 692x |
sum(attr(x, "match.length") > 0) > 1 |
536 | 81x |
}, logical(1)) |
537 |
## Throw error in case any have more than 1 numbers |
|
538 | 81x |
if (any(more_than_one)) { |
539 | 2x |
stop( |
540 | 2x |
"Decimal alignment is not supported for multiple values. ", |
541 | 2x |
"Found the following string with multiple numbers ", |
542 | 2x |
"(first 3 selected from column ", col_i[1], "): '", |
543 | 2x |
paste0(col_ia[more_than_one][seq(1, 3)], collapse = "', '"), |
544 |
"'" |
|
545 |
) |
|
546 |
} |
|
547 |
## General split (only one match -> the first) |
|
548 | 79x |
main_regexp <- regexpr("\\d+", col_ia) |
549 | 79x |
left <- regmatches(col_ia, main_regexp, invert = FALSE) |
550 | 79x |
right <- regmatches(col_ia, main_regexp, invert = TRUE) |
551 | 79x |
right <- sapply(right, "[[", 2) |
552 | 79x |
something_left <- sapply(strsplit(col_ia, "\\d+"), "[[", 1) |
553 | 79x |
left <- paste0(something_left, left) |
554 | 79x |
if (!checkmate::test_set_equal(paste0(left, right), col_ia)) { |
555 | ! |
stop( |
556 | ! |
"Split string list lost some piece along the way. This ", |
557 | ! |
"should not have happened. Please contact the maintainer." |
558 |
) |
|
559 |
} # nocov |
|
560 | 79x |
separator <- sapply(right, function(x) { |
561 | 645x |
if (nzchar(x)) { |
562 | 349x |
substr(x, 1, 1) |
563 |
} else { |
|
564 | 296x |
c(" ") |
565 |
} |
|
566 | 79x |
}, USE.NAMES = FALSE) |
567 | 79x |
right <- sapply(right, function(x) { |
568 | 645x |
if (nchar(x) > 1) { |
569 | 317x |
substr(x, 2, nchar(x)) |
570 |
} else { |
|
571 | 328x |
c("") |
572 |
} |
|
573 | 79x |
}, USE.NAMES = FALSE) |
574 |
## figure out whether we need space separators (at least one had a "." or not) |
|
575 | 79x |
if (!any(grepl("[^[:space:]]", separator))) { |
576 | 26x |
separator <- gsub("[[:space:]]*", "", separator) |
577 |
} |
|
578 |
## modify the piece with spaces |
|
579 | 79x |
left_mod <- paste0(spaces(max(nchar(left), na.rm = TRUE) - nchar(left)), left) |
580 | 79x |
right_mod <- paste0(right, spaces(max(nchar(right), na.rm = TRUE) - nchar(right))) |
581 |
# Put everything together |
|
582 | 79x |
aligned <- paste(left_mod, separator, right_mod, sep = "") |
583 | 79x |
string_mat[!nonalign, i] <- aligned |
584 |
} |
|
585 |
} |
|
586 |
} |
|
587 | 42x |
string_mat |
588 |
} |
|
589 | ||
590 |
## this gives the conversion from number of spaces to number of characters |
|
591 |
## for use in, e.g., repping out divider lines. |
|
592 |
calc_str_adj <- function(str, fontspec) { |
|
593 | 157x |
if (nchar(str) == 0) { |
594 | ! |
return(0) |
595 |
} |
|
596 | 157x |
nchar(str) / nchar_ttype(str, fontspec, raw = TRUE) |
597 |
} |
|
598 | ||
599 |
# toString --------------------------------------------------------------------- |
|
600 |
# main printing code for MatrixPrintForm |
|
601 | ||
602 |
#' @description |
|
603 |
#' All objects that are printed to console pass via `toString`. This function allows |
|
604 |
#' fundamental formatting specifications to be applied to final output, like column widths |
|
605 |
#' and relative wrapping (`width`), title and footer wrapping (`tf_wrap = TRUE` and |
|
606 |
#' `max_width`), and horizontal separator character (e.g. `hsep = "+"`). |
|
607 |
#' |
|
608 |
#' @inheritParams MatrixPrintForm |
|
609 |
#' @inheritParams open_font_dev |
|
610 |
#' @param widths (`numeric` or `NULL`)\cr Proposed widths for the columns of `x`. The expected |
|
611 |
#' length of this numeric vector can be retrieved with `ncol(x) + 1` as the column of row names |
|
612 |
#' must also be considered. |
|
613 |
#' @param hsep (`string`)\cr character to repeat to create header/body separator line. If |
|
614 |
#' `NULL`, the object value will be used. If `" "`, an empty separator will be printed. See |
|
615 |
#' [default_hsep()] for more information. |
|
616 |
#' @param tf_wrap (`flag`)\cr whether the text for title, subtitles, and footnotes should be wrapped. |
|
617 |
#' @param max_width (`integer(1)`, `string` or `NULL`)\cr width that title and footer (including |
|
618 |
#' footnotes) materials should be word-wrapped to. If `NULL`, it is set to the current print width of the |
|
619 |
#' session (`getOption("width")`). If set to `"auto"`, the width of the table (plus any table inset) is |
|
620 |
#' used. Parameter is ignored if `tf_wrap = FALSE`. |
|
621 |
#' @param ttype_ok (`logical(1)`)\cr should truetype (non-monospace) fonts be |
|
622 |
#' allowed via `fontspec`. Defaults to `FALSE`. This parameter is primarily |
|
623 |
#' for internal testing and generally should not be set by end users. |
|
624 |
#' |
|
625 |
#' @details |
|
626 |
#' Manual insertion of newlines is not supported when `tf_wrap = TRUE` and will result in a warning and |
|
627 |
#' undefined wrapping behavior. Passing vectors of already split strings remains supported, however in this |
|
628 |
#' case each string is word-wrapped separately with the behavior described above. |
|
629 |
#' |
|
630 |
#' @return A character string containing the ASCII rendering of the table-like object represented by `x`. |
|
631 |
#' |
|
632 |
#' @seealso [wrap_string()] |
|
633 |
#' |
|
634 |
#' @examples |
|
635 |
#' mform <- basic_matrix_form(mtcars) |
|
636 |
#' cat(toString(mform)) |
|
637 |
#' |
|
638 |
#' @rdname tostring |
|
639 |
#' @exportMethod toString |
|
640 |
setMethod("toString", "MatrixPrintForm", function(x, |
|
641 |
widths = NULL, |
|
642 |
tf_wrap = FALSE, |
|
643 |
max_width = NULL, |
|
644 |
col_gap = mf_colgap(x), |
|
645 |
hsep = NULL, |
|
646 |
fontspec = font_spec(), |
|
647 |
ttype_ok = FALSE) { |
|
648 | 160x |
checkmate::assert_flag(tf_wrap) |
649 | ||
650 |
## we are going to use the pdf device and grid to understand the actual |
|
651 |
## print width of things given our font family and font size |
|
652 | 160x |
new_dev <- open_font_dev(fontspec) |
653 | 160x |
if (new_dev) { |
654 | 150x |
on.exit(close_font_dev()) |
655 |
} |
|
656 | ||
657 | 160x |
if (!is_monospace(fontspec = fontspec) && !ttype_ok) { |
658 | ! |
stop( |
659 | ! |
"non-monospace font specified in toString call; this would result in cells contents not lining up exactly. ", |
660 | ! |
"If you truly want this behavior please set ttype_ok = TRUE in the call to toString/export_as_txt/export_as_pdf" |
661 |
) |
|
662 |
} |
|
663 | 160x |
mat <- matrix_form(x, indent_rownames = TRUE, fontspec = fontspec) |
664 | ||
665 |
# Check for \n in mat strings -> if there are any, matrix_form did not work |
|
666 | 160x |
if (any(grepl("\n", mf_strings(mat)))) { |
667 | ! |
stop( |
668 | ! |
"Found newline characters (\\n) in string matrix produced by matrix_form. ", |
669 | ! |
"This is not supported and implies missbehavior on the first parsing (in matrix_form). ", |
670 | ! |
"Please contact the maintainer or file an issue." |
671 | ! |
) # nocov |
672 |
} |
|
673 | 160x |
if (any(grepl("\r", mf_strings(mat)))) { |
674 | ! |
stop( |
675 | ! |
"Found recursive special characters (\\r) in string matrix produced by matrix_form. ", |
676 | ! |
"This special character is not supported and should be removed." |
677 | ! |
) # nocov |
678 |
} |
|
679 | ||
680 |
# Check that expansion worked for header -> should not happen |
|
681 | 160x |
if (!is.null(mf_rinfo(mat)) && # rare case of rtables::rtable() |
682 | 160x |
(length(mf_lgrouping(mat)) != nrow(mf_strings(mat)) || # non-unique grouping test # nolint |
683 | 160x |
mf_nrheader(mat) + nrow(mf_rinfo(mat)) != length(unique(mf_lgrouping(mat))))) { # nolint |
684 | ! |
stop( |
685 | ! |
"The sum of the expected nrows header and nrows of content table does ", |
686 | ! |
"not match the number of rows in the string matrix. To our knowledge, ", |
687 | ! |
"this is usually of a problem in solving newline characters (\\n) in the header. ", |
688 | ! |
"Please contact the maintaner or file an issue." |
689 | ! |
) # nocov |
690 |
} |
|
691 | ||
692 | 160x |
inset <- table_inset(mat) |
693 | ||
694 |
# if cells are decimal aligned, run propose column widths |
|
695 |
# if the provided widths is less than proposed width, return an error |
|
696 | 160x |
if (any_dec_align(mf_aligns(mat))) { |
697 | 22x |
aligned <- propose_column_widths(x, fontspec = fontspec) |
698 | ||
699 |
# catch any columns that require widths more than what is provided |
|
700 | 20x |
if (!is.null(widths)) { |
701 | 9x |
how_wide <- sapply(seq_along(widths), function(i) c(widths[i] - aligned[i])) |
702 | 9x |
too_wide <- how_wide < 0 |
703 | 9x |
if (any(too_wide)) { |
704 | 2x |
desc_width <- paste(paste( |
705 | 2x |
names(which(too_wide)), |
706 | 2x |
paste0("(", how_wide[too_wide], ")") |
707 | 2x |
), collapse = ", ") |
708 | 2x |
stop( |
709 | 2x |
"Inserted width(s) for column(s) ", desc_width, |
710 | 2x |
" is(are) not wide enough for the desired alignment." |
711 |
) |
|
712 |
} |
|
713 |
} |
|
714 |
} |
|
715 | ||
716 |
# Column widths are fixed here |
|
717 | 156x |
if (is.null(widths)) { |
718 |
# if mf does not have widths -> propose them |
|
719 | 130x |
widths <- mf_col_widths(x) %||% propose_column_widths(x, fontspec = fontspec) |
720 |
} else { |
|
721 | 26x |
mf_col_widths(x) <- widths |
722 |
} |
|
723 | ||
724 |
## Total number of characters for the table |
|
725 |
## col_gap (and table inset) are in number of spaces |
|
726 |
## so we're ok here even in the truetype case |
|
727 | 156x |
ncchar <- sum(widths) + (length(widths) - 1) * col_gap |
728 | ||
729 |
## max_width for wrapping titles and footers (not related to ncchar if not indirectly) |
|
730 | 156x |
max_width <- .handle_max_width( |
731 | 156x |
tf_wrap = tf_wrap, |
732 | 156x |
max_width = max_width, |
733 | 156x |
colwidths = widths, |
734 | 156x |
col_gap = col_gap, |
735 | 156x |
inset = inset |
736 |
) |
|
737 | ||
738 |
# Main wrapper function for table core |
|
739 | 156x |
mat <- do_cell_fnotes_wrap(mat, widths, max_width = max_width, tf_wrap = tf_wrap, fontspec = fontspec) |
740 | ||
741 | 153x |
body <- mf_strings(mat) |
742 | 153x |
aligns <- mf_aligns(mat) |
743 | 153x |
keep_mat <- mf_display(mat) |
744 |
## spans <- mat$spans |
|
745 | 153x |
mf_ri <- mf_rinfo(mat) |
746 | 153x |
ref_fnotes <- mf_rfnotes(mat) |
747 | 153x |
nl_header <- mf_nlheader(mat) |
748 | ||
749 | 153x |
cell_widths_mat <- .calc_cell_widths(mat, widths, col_gap) |
750 | ||
751 |
# decimal alignment |
|
752 | 153x |
if (any_dec_align(aligns)) { |
753 | 18x |
body <- decimal_align(body, aligns) |
754 |
} |
|
755 | ||
756 |
# Content is a matrix of cells with the right amount of spaces |
|
757 | 153x |
content <- matrix( |
758 | 153x |
mapply(padstr, body, cell_widths_mat, aligns, MoreArgs = list(fontspec = fontspec)), |
759 | 153x |
ncol = ncol(body) |
760 |
) |
|
761 | 153x |
content[!keep_mat] <- NA |
762 | ||
763 |
# Define gap string and divisor string |
|
764 | 153x |
gap_str <- strrep(" ", col_gap) |
765 | 153x |
if (is.null(hsep)) { |
766 | 121x |
hsep <- horizontal_sep(mat) |
767 |
} |
|
768 | 153x |
adj_hsep <- calc_str_adj(hsep, fontspec) |
769 | 153x |
div <- substr(strrep(hsep, ceiling(ncchar * adj_hsep)), 1, ceiling(ncchar * adj_hsep)) |
770 | 153x |
hsd <- header_section_div(mat) |
771 | 153x |
if (!is.na(hsd)) { |
772 | ! |
adj_hsd <- calc_str_adj(hsd, fontspec) |
773 | ! |
hsd <- substr(strrep(hsd, ceiling(ncchar * adj_hsd)), 1, ceiling(ncchar * adj_hsd)) |
774 |
} else { |
|
775 | 153x |
hsd <- NULL # no divisor |
776 |
} |
|
777 | ||
778 |
# text head (paste w/o NA content header and gap string) |
|
779 | 153x |
txt_head <- apply(head(content, nl_header), 1, .paste_no_na, collapse = gap_str) |
780 | ||
781 |
# txt body |
|
782 | 153x |
sec_seps_df <- mf_ri[, c("abs_rownumber", "trailing_sep"), drop = FALSE] |
783 | 153x |
if (!is.null(sec_seps_df) && any(!is.na(sec_seps_df$trailing_sep))) { |
784 | 2x |
bdy_cont <- tail(content, -nl_header) |
785 |
## unfortunately we count "header rows" wrt line grouping so it |
|
786 |
## doesn't match the real (i.e. body) rows as is |
|
787 | 2x |
row_grouping <- tail(mf_lgrouping(mat), -nl_header) - mf_nrheader(mat) |
788 | 2x |
nrbody <- NROW(bdy_cont) |
789 | 2x |
stopifnot(length(row_grouping) == nrbody) |
790 |
## all rows with non-NA section divs and the final row (regardless of NA status) |
|
791 |
## fixes #77 |
|
792 | 2x |
sec_seps_df <- sec_seps_df[unique(c( |
793 | 2x |
which(!is.na(sec_seps_df$trailing_sep)), |
794 | 2x |
NROW(sec_seps_df) |
795 |
)), ] |
|
796 | 2x |
txt_body <- character() |
797 | 2x |
sec_strt <- 1 |
798 | 2x |
section_rws <- sec_seps_df$abs_rownumber |
799 | 2x |
for (i in seq_len(NROW(section_rws))) { |
800 | 6x |
cur_rownum <- section_rws[i] |
801 | 6x |
sec_end <- max(which(row_grouping == cur_rownum)) |
802 | 6x |
txt_body <- c( |
803 | 6x |
txt_body, |
804 | 6x |
apply(bdy_cont[seq(sec_strt, sec_end), , drop = FALSE], |
805 | 6x |
1, |
806 | 6x |
.paste_no_na, |
807 | 6x |
collapse = gap_str |
808 |
), |
|
809 |
## don't print section dividers if they would be the last thing before the |
|
810 |
## footer divider |
|
811 |
## this also ensures an extraneous sec div won't be printed if we have non-sec-div |
|
812 |
## rows after the last sec div row (#77) |
|
813 | 6x |
if (sec_end < nrbody) { |
814 | 4x |
adj_i <- calc_str_adj(sec_seps_df$trailing_sep[i], fontspec) |
815 | 4x |
substr( |
816 | 4x |
strrep(sec_seps_df$trailing_sep[i], ceiling(ncchar * adj_i)), 1, |
817 | 4x |
ceiling((ncchar - inset) * adj_i) |
818 |
) |
|
819 |
} |
|
820 |
) |
|
821 | 6x |
sec_strt <- sec_end + 1 |
822 |
} |
|
823 |
} else { |
|
824 |
# This is the usual default pasting |
|
825 | 151x |
txt_body <- apply(tail(content, -nl_header), 1, .paste_no_na, collapse = gap_str) |
826 |
} |
|
827 | ||
828 |
# retrieving titles and footers |
|
829 | 153x |
allts <- all_titles(mat) |
830 | ||
831 | 153x |
ref_fnotes <- reorder_ref_fnotes(ref_fnotes) |
832 |
# Fix for ref_fnotes with \n characters XXX this does not count in the pagination |
|
833 | 153x |
if (any(grepl("\\n", ref_fnotes))) { |
834 | 2x |
ref_fnotes <- unlist(strsplit(ref_fnotes, "\n", fixed = TRUE)) |
835 |
} |
|
836 | ||
837 | 153x |
allfoots <- list( |
838 | 153x |
"main_footer" = main_footer(mat), |
839 | 153x |
"prov_footer" = prov_footer(mat), |
840 | 153x |
"ref_footnotes" = ref_fnotes |
841 |
) |
|
842 | 153x |
allfoots <- allfoots[!sapply(allfoots, is.null)] |
843 | ||
844 |
## Wrapping titles if they go beyond the horizontally allowed space |
|
845 | 153x |
if (tf_wrap) { |
846 | 68x |
new_line_warning(allts) |
847 | 68x |
allts <- wrap_txt(allts, max_width, fontspec = fontspec) |
848 |
} |
|
849 | 153x |
titles_txt <- if (any(nzchar(allts))) c(allts, "", .do_inset(div, inset)) else NULL |
850 | ||
851 |
# Wrapping footers if they go beyond the horizontally allowed space |
|
852 | 153x |
if (tf_wrap) { |
853 | 68x |
new_line_warning(allfoots) |
854 | 68x |
allfoots$main_footer <- wrap_txt(allfoots$main_footer, max_width - inset, fontspec = fontspec) |
855 | 68x |
allfoots$ref_footnotes <- wrap_txt(allfoots$ref_footnotes, max_width - inset, fontspec = fontspec) |
856 |
## no - inset here because the prov_footer is not inset |
|
857 | 68x |
allfoots$prov_footer <- wrap_txt(allfoots$prov_footer, max_width, fontspec = fontspec) |
858 |
} |
|
859 | ||
860 |
# Final return |
|
861 | 153x |
paste0( |
862 | 153x |
paste(c( |
863 | 153x |
titles_txt, # .do_inset(div, inset) happens if there are any titles |
864 | 153x |
.do_inset(txt_head, inset), |
865 | 153x |
.do_inset(div, inset), |
866 | 153x |
.do_inset(hsd, inset), # header_section_div if present |
867 | 153x |
.do_inset(txt_body, inset), |
868 | 153x |
.footer_inset_helper(allfoots, div, inset) |
869 | 153x |
), collapse = "\n"), |
870 | 153x |
"\n" |
871 |
) |
|
872 |
}) |
|
873 | ||
874 |
# Switcher for the 3 options for max_width (NULL, numeric, "auto")) |
|
875 |
.handle_max_width <- function(tf_wrap, max_width, |
|
876 |
cpp = NULL, # Defaults to getOption("width", 80L) |
|
877 |
# Things for auto |
|
878 |
inset = NULL, colwidths = NULL, col_gap = NULL) { |
|
879 | 234x |
max_width <- if (!tf_wrap) { |
880 | 114x |
if (!is.null(max_width)) { |
881 | 1x |
warning("tf_wrap is FALSE - ignoring non-null max_width value.") |
882 |
} |
|
883 | 114x |
NULL |
884 | 234x |
} else if (tf_wrap) { |
885 | 120x |
if (is.null(max_width)) { |
886 | 36x |
if (is.null(cpp) || is.na(cpp)) { |
887 | 7x |
getOption("width", 80L) |
888 |
} else { |
|
889 | 29x |
cpp |
890 |
} |
|
891 | 84x |
} else if (is.numeric(max_width)) { |
892 | 79x |
max_width |
893 | 5x |
} else if (is.character(max_width) && identical(max_width, "auto")) { |
894 |
# This should not happen, but just in case |
|
895 | 4x |
if (any(sapply(list(inset, colwidths, col_gap), is.null))) { |
896 | 1x |
stop("inset, colwidths, and col_gap must all be non-null when max_width is \"auto\".") |
897 |
} |
|
898 | 3x |
inset + sum(colwidths) + (length(colwidths) - 1) * col_gap |
899 |
} else { |
|
900 | 1x |
stop("max_width must be NULL, a numeric value, or \"auto\".") |
901 |
} |
|
902 |
} |
|
903 | 232x |
return(max_width) |
904 |
} |
|
905 | ||
906 |
.do_inset <- function(x, inset) { |
|
907 | 1038x |
if (inset == 0 || !any(nzchar(x))) { |
908 | 1019x |
return(x) |
909 |
} |
|
910 | 19x |
padding <- strrep(" ", inset) |
911 | 19x |
if (is.character(x)) { |
912 | 19x |
x <- paste0(padding, x) |
913 | ! |
} else if (is(x, "matrix")) { |
914 | ! |
x[, 1] <- .do_inset(x[, 1, drop = TRUE], inset) |
915 |
} |
|
916 | 19x |
x |
917 |
} |
|
918 | ||
919 |
.inset_div <- function(txt, div, inset) { |
|
920 | 105x |
c(.do_inset(div, inset), "", txt) |
921 |
} |
|
922 | ||
923 |
.footer_inset_helper <- function(footers_v, div, inset) { |
|
924 | 153x |
div_done <- FALSE # nolint |
925 | 153x |
fter <- footers_v$main_footer |
926 | 153x |
prvf <- footers_v$prov_footer |
927 | 153x |
rfn <- footers_v$ref_footnotes |
928 | 153x |
footer_txt <- .do_inset(rfn, inset) |
929 | 153x |
if (any(nzchar(footer_txt))) { |
930 | 14x |
footer_txt <- .inset_div(footer_txt, div, inset) |
931 |
} |
|
932 | 153x |
if (any(vapply( |
933 | 153x |
footers_v, function(x) any(nzchar(x)), |
934 | 153x |
TRUE |
935 |
))) { |
|
936 | 91x |
if (any(nzchar(prvf))) { |
937 | 89x |
provtxt <- c( |
938 | 89x |
if (any(nzchar(fter))) "", |
939 | 89x |
prvf |
940 |
) |
|
941 |
} else { |
|
942 | 2x |
provtxt <- character() |
943 |
} |
|
944 | 91x |
footer_txt <- c( |
945 | 91x |
footer_txt, |
946 | 91x |
.inset_div( |
947 | 91x |
c( |
948 | 91x |
.do_inset(fter, inset), |
949 | 91x |
provtxt |
950 |
), |
|
951 | 91x |
div, |
952 | 91x |
inset |
953 |
) |
|
954 |
) |
|
955 |
} |
|
956 | 153x |
footer_txt |
957 |
} |
|
958 | ||
959 |
reorder_ref_fnotes <- function(fns) { |
|
960 | 156x |
ind <- gsub("\\{(.*)\\}.*", "\\1", fns) |
961 | 156x |
ind_num <- suppressWarnings(as.numeric(ind)) |
962 | 156x |
is_num <- !is.na(ind_num) |
963 | 156x |
is_asis <- ind == fns |
964 | ||
965 | 156x |
if (all(is_num)) { |
966 | 140x |
ord_num <- order(ind_num) |
967 | 140x |
ord_char <- NULL |
968 | 140x |
ord_other <- NULL |
969 |
} else { |
|
970 | 16x |
ord_num <- order(ind_num[is_num]) |
971 | 16x |
ord_char <- order(ind[!is_num & !is_asis]) |
972 | 16x |
ord_other <- order(ind[is_asis]) |
973 |
} |
|
974 | 156x |
c(fns[is_num][ord_num], fns[!is_num & !is_asis][ord_char], ind[is_asis][ord_other]) |
975 |
} |
|
976 | ||
977 |
new_line_warning <- function(str_v) { |
|
978 | 136x |
if (any(unlist(sapply(str_v, grepl, pattern = "\n")))) { |
979 | ! |
msg <- c( |
980 | ! |
"Detected manual newlines when automatic title/footer word-wrapping is on.", |
981 | ! |
"This is unsupported and will result in undefined behavior. Please either ", |
982 | ! |
"utilize automatic word-wrapping with newline characters inserted, or ", |
983 | ! |
"turn off automatic wrapping and wordwrap all contents manually by inserting ", |
984 | ! |
"newlines." |
985 |
) |
|
986 | ! |
warning(paste0(msg, collapse = "")) |
987 |
} |
|
988 |
} |
|
989 | ||
990 |
#' Wrap a string to a precise width |
|
991 |
#' |
|
992 |
#' Core wrapping functionality that preserves whitespace. Newline character `"\n"` is not supported |
|
993 |
#' by core functionality [stringi::stri_wrap()]. This is usually solved beforehand by [matrix_form()]. |
|
994 |
#' If the width is smaller than any large word, these will be truncated after `width` characters. If |
|
995 |
#' the split leaves trailing groups of empty spaces, they will be dropped. |
|
996 |
#' |
|
997 |
#' @inheritParams open_font_dev |
|
998 |
#' @param str (`string`, `character`, or `list`)\cr string to be wrapped. If it is a `vector` or |
|
999 |
#' a `list`, it will be looped as a `list` and returned with `unlist(use.names = FALSE)`. |
|
1000 |
#' @param width (`numeric(1)`)\cr width, in characters, that the text should be wrapped to. |
|
1001 |
#' @param collapse (`string` or `NULL`)\cr collapse character used to separate segments of words that |
|
1002 |
#' have been split and should be pasted together. This is usually done internally with `"\n"` to update |
|
1003 |
#' the wrapping along with other internal values. |
|
1004 |
#' |
|
1005 |
#' @details Word wrapping happens similarly to [stringi::stri_wrap()] with the following difference: individual |
|
1006 |
#' words which are longer than `max_width` are broken up in a way that fits with other word wrapping. |
|
1007 |
#' |
|
1008 |
#' @return A string if `str` is one element and if `collapse = NULL`. Otherwise, a list of elements |
|
1009 |
#' (if `length(str) > 1`) that can contain strings or vectors of characters (if `collapse = NULL`). |
|
1010 |
#' |
|
1011 |
#' @examples |
|
1012 |
#' str <- list( |
|
1013 |
#' " , something really \\tnot very good", # \t needs to be escaped |
|
1014 |
#' " but I keep it12 " |
|
1015 |
#' ) |
|
1016 |
#' wrap_string(str, 5, collapse = "\n") |
|
1017 |
#' |
|
1018 |
#' @export |
|
1019 |
wrap_string <- function(str, width, collapse = NULL, fontspec = font_spec()) { |
|
1020 | 36446x |
if (length(str) > 1) { |
1021 | 114x |
return( |
1022 | 114x |
unlist( |
1023 | 114x |
lapply(str, wrap_string, width = width, collapse = collapse, fontspec = fontspec), |
1024 | 114x |
use.names = FALSE |
1025 |
) |
|
1026 |
) |
|
1027 |
} |
|
1028 | 36332x |
str <- unlist(str, use.names = FALSE) # it happens is one list element |
1029 | 36332x |
if (!length(str) || !nzchar(str) || is.na(str)) { |
1030 | 3855x |
return(str) |
1031 |
} |
|
1032 | 32477x |
checkmate::assert_character(str) |
1033 | 32477x |
checkmate::assert_int(width, lower = 1) |
1034 | ||
1035 | 32477x |
if (any(grepl("\\n", str))) { |
1036 | ! |
stop( |
1037 | ! |
"Found \\n in a string that was meant to be wrapped. This should not happen ", |
1038 | ! |
"because matrix_form should take care of them before this step (toString, ", |
1039 | ! |
"i.e. the printing machinery). Please contact the maintaner or file an issue." |
1040 |
) |
|
1041 |
} |
|
1042 | ||
1043 | 32477x |
if (!is_monospace(fontspec)) { |
1044 | 3x |
return(wrap_string_ttype(str, width, fontspec, collapse = collapse)) |
1045 |
} |
|
1046 | ||
1047 |
# str can be also a vector or list. In this case simplify manages the output |
|
1048 | 32474x |
ret <- .go_stri_wrap(str, width) |
1049 | ||
1050 |
# Check if it went fine |
|
1051 | 32474x |
if (any(nchar_ttype(ret, fontspec) > width)) { |
1052 | 68x |
which_exceeded <- which(nchar_ttype(ret, fontspec) > width) |
1053 | ||
1054 |
# Recursive for loop to take word interval |
|
1055 | 68x |
while (length(which_exceeded) > 0) { |
1056 | 75x |
we_i <- which_exceeded[1] |
1057 |
# Is there space for some part of the next word? |
|
1058 | 75x |
char_threshold <- width * (2 / 3) + 0.01 # if too little space -> no previous word |
1059 | 75x |
smart_condition <- nchar_ttype(ret[we_i - 1], fontspec) + 1 < char_threshold # +1 is for spaces |
1060 | 75x |
if (we_i - 1 > 0 && smart_condition) { |
1061 | 6x |
we_interval <- unique(c(we_i - 1, we_i)) |
1062 | 6x |
we_interval <- we_interval[ |
1063 | 6x |
(we_interval < (length(ret) + 1)) & |
1064 | 6x |
(we_interval > 0) |
1065 |
] |
|
1066 |
} else { |
|
1067 | 69x |
we_interval <- we_i |
1068 |
} |
|
1069 |
# Split words and collapse (needs unique afterwards) |
|
1070 | 75x |
ret[we_interval] <- split_words_by( |
1071 | 75x |
paste0(ret[we_interval], collapse = " "), |
1072 | 75x |
width |
1073 |
) |
|
1074 |
# Taking out repetitions if there are more than one |
|
1075 | 75x |
if (length(we_interval) > 1) { |
1076 | 6x |
ret <- ret[-we_interval[-1]] |
1077 | 6x |
we_interval <- we_interval[1] |
1078 |
} |
|
1079 |
# Paste together and rerun if it is not the same as original ret |
|
1080 | 75x |
ret_collapse <- paste0(ret, collapse = " ") |
1081 | ||
1082 |
# Checking if we are stuck in a loop |
|
1083 | 75x |
ori_wrapped_txt_v <- .go_stri_wrap(str, width) |
1084 | 75x |
cur_wrapped_txt_v <- .go_stri_wrap(ret_collapse, width) |
1085 | 75x |
broken_char_ori <- sum(nchar_ttype(ori_wrapped_txt_v, fontspec) > width) # how many issues there were |
1086 | 75x |
broken_char_cur <- sum(nchar_ttype(cur_wrapped_txt_v, fontspec) > width) # how many issues there are |
1087 | ||
1088 |
# if still broken, we did not solve the current issue! |
|
1089 | 75x |
if (setequal(ori_wrapped_txt_v, cur_wrapped_txt_v) || broken_char_cur >= broken_char_ori) { |
1090 |
# help function: Very rare case where the recursion is stuck in a loop |
|
1091 | 14x |
ret_tmp <- force_split_words_by(ret[we_interval], width) # here we_interval is only one ind |
1092 | 14x |
ret <- append(ret, ret_tmp, we_interval)[-we_interval] |
1093 | 14x |
which_exceeded <- which(nchar_ttype(ret, fontspec) > width) |
1094 |
} else { |
|
1095 | 61x |
return(wrap_string(str = ret_collapse, width = width, collapse = collapse)) |
1096 |
} |
|
1097 |
} |
|
1098 |
} |
|
1099 | ||
1100 | 32413x |
if (!is.null(collapse)) { |
1101 | 31962x |
return(paste0(ret, collapse = collapse)) |
1102 |
} |
|
1103 | ||
1104 | 451x |
return(ret) |
1105 |
} |
|
1106 | ||
1107 |
.go_stri_wrap <- function(str, w) { |
|
1108 | 32624x |
if (w < 1) { |
1109 | ! |
return(str) |
1110 |
} |
|
1111 | 32624x |
stringi::stri_wrap(str, |
1112 | 32624x |
width = w, |
1113 | 32624x |
normalize = FALSE, # keeps spaces |
1114 | 32624x |
simplify = TRUE, # If FALSE makes it a list with str elements |
1115 | 32624x |
indent = 0, |
1116 | 32624x |
use_length = FALSE # incase the defaul changes, use actual char widths |
1117 |
) |
|
1118 |
} |
|
1119 | ||
1120 |
#' @rdname wrap_string_ttype |
|
1121 |
#' @export |
|
1122 |
split_word_ttype <- function(str, width, fontspec, min_ok_chars) { |
|
1123 | 11x |
chrs <- strsplit(str, "")[[1]] |
1124 | 11x |
nctt_chars <- nchar_ttype(chrs, fontspec, raw = TRUE) |
1125 | 11x |
ok <- which(cumsum(nctt_chars) <= width) |
1126 | 11x |
if (length(ok) < min_ok_chars || length(chrs) - length(ok) < min_ok_chars) { |
1127 | 3x |
list( |
1128 | 3x |
ok = character(), |
1129 | 3x |
remainder = str |
1130 |
) |
|
1131 |
} else { |
|
1132 | 8x |
list( |
1133 | 8x |
ok = substr(str, 1, length(ok)), |
1134 | 8x |
remainder = substr(str, length(ok) + 1, nchar(str)) |
1135 |
) |
|
1136 |
} |
|
1137 |
} |
|
1138 | ||
1139 |
## need a separate path here because **the number of characters** |
|
1140 |
## in each part is no longer going to be constant the way it |
|
1141 |
## was for monospace |
|
1142 |
## this is much slower but still shouldn't be a bottleneck, if it is we'll |
|
1143 |
## have to do something else |
|
1144 |
#' wrap string given a Truetype font |
|
1145 |
#' |
|
1146 |
#' @inheritParams wrap_string |
|
1147 |
#' @param min_ok_chars (`numeric(1)`)\cr number of minimum characters that remain |
|
1148 |
#' on either side when a word is split. |
|
1149 |
#' @param wordbreak_ok (`logical(1)`)\cr should breaking within a word be allowed? If, `FALSE`, |
|
1150 |
#' attempts to wrap a string to a width narrower than its widest word will result |
|
1151 |
#' in an error. |
|
1152 |
#' @return `str`, broken up into a word-wrapped vector |
|
1153 |
#' @export |
|
1154 |
wrap_string_ttype <- function(str, |
|
1155 |
width, |
|
1156 |
fontspec, |
|
1157 |
collapse = NULL, |
|
1158 |
min_ok_chars = min(floor(nchar(str) / 2), 4, floor(width / 2)), |
|
1159 |
wordbreak_ok = TRUE) { |
|
1160 | 12x |
newdev <- open_font_dev(fontspec) |
1161 | 11x |
if (newdev) { |
1162 | ! |
on.exit(close_font_dev()) |
1163 |
} |
|
1164 | ||
1165 | 11x |
rawspls <- strsplit(str, "[[:space:]](?=[^[:space:]])", perl = TRUE)[[1]] # preserve all but one space |
1166 | 11x |
nctt <- nchar_ttype(rawspls, fontspec, raw = TRUE) |
1167 | 11x |
pts <- which(cumsum(nctt) <= width) |
1168 | 11x |
if (length(pts) == length(rawspls)) { ## no splitting needed |
1169 | 3x |
return(str) |
1170 | 8x |
} else if (length(pts) == 0) { ## no spaces, all one word, split it and keep going |
1171 | 7x |
if (wordbreak_ok) { |
1172 | 7x |
inner_res <- list() |
1173 | 7x |
min_ok_inner <- min_ok_chars |
1174 | 7x |
while (length(inner_res$ok) == 0) { |
1175 | 10x |
inner_res <- split_word_ttype(rawspls[1], width, fontspec, min_ok_inner) # min_ok_chars) |
1176 | 10x |
min_ok_inner <- floor(min_ok_inner / 2) |
1177 |
} |
|
1178 | 7x |
done <- inner_res$ok |
1179 | 7x |
remainder <- paste(c(inner_res$remainder, rawspls[-1]), collapse = " ") |
1180 |
} else { |
|
1181 | ! |
stop( |
1182 | ! |
"Unable to find word wrapping solution without breaking word: ", |
1183 | ! |
rawspls[[1]], " [requires ", nchar_ttype(rawspls[[1]], fontspec), " spaces of width, out of ", |
1184 | ! |
width, " available]." |
1185 |
) |
|
1186 |
} |
|
1187 |
} else { ## some words fit, and some words don't |
|
1188 | 1x |
done_tmp <- paste(rawspls[pts], collapse = " ") |
1189 | 1x |
tospl_tmp <- rawspls[length(pts) + 1] |
1190 | 1x |
width_tmp <- width - sum(nctt[pts]) |
1191 | 1x |
if (wordbreak_ok && width_tmp / width > .33) { |
1192 | 1x |
inner_res <- split_word_ttype(tospl_tmp, width_tmp, fontspec, |
1193 | 1x |
min_ok_chars = min_ok_chars |
1194 |
) |
|
1195 |
} else { |
|
1196 | ! |
inner_res <- list(done = "", remainder = tospl_tmp) |
1197 |
} |
|
1198 | 1x |
done <- paste(c(rawspls[pts], inner_res$ok), |
1199 | 1x |
collapse = " " |
1200 |
) |
|
1201 | 1x |
remainder <- paste( |
1202 | 1x |
c( |
1203 | 1x |
inner_res$remainder, |
1204 | 1x |
if (length(rawspls) > length(pts) + 1) tail(rawspls, -(length(pts) + 1)) |
1205 |
), |
|
1206 | 1x |
collapse = " " |
1207 |
) |
|
1208 |
} |
|
1209 | 8x |
ret <- c( |
1210 | 8x |
done, |
1211 | 8x |
wrap_string_ttype(remainder, width, fontspec) |
1212 |
) |
|
1213 | 8x |
if (!is.null(collapse)) { |
1214 | ! |
ret <- paste(ret, collapse = collapse) |
1215 |
} |
|
1216 | 8x |
ret |
1217 |
} |
|
1218 | ||
1219 |
# help function: Very rare case where the recursion is stuck in a loop |
|
1220 |
force_split_words_by <- function(ret, width) { |
|
1221 | 14x |
which_exceeded <- which(nchar(ret) > width) |
1222 | 14x |
ret_tmp <- NULL |
1223 | 14x |
for (ii in seq_along(ret)) { |
1224 | 14x |
if (ii %in% which_exceeded) { |
1225 | 14x |
wrd_i <- ret[ii] |
1226 | 14x |
init_v <- seq(1, nchar(wrd_i), by = width) |
1227 | 14x |
end_v <- c(init_v[-1] - 1, nchar(wrd_i)) |
1228 | 14x |
str_v_tmp <- stringi::stri_sub(wrd_i, from = init_v, to = end_v) |
1229 | 14x |
ret_tmp <- c(ret_tmp, str_v_tmp[!grepl("^\\s+$", str_v_tmp) & nzchar(str_v_tmp)]) |
1230 |
} else { |
|
1231 | ! |
ret_tmp <- c(ret_tmp, ret[ii]) |
1232 |
} |
|
1233 |
} |
|
1234 | 14x |
ret_tmp |
1235 |
} |
|
1236 | ||
1237 |
# Helper fnc to split the words and collapse them with space |
|
1238 |
split_words_by <- function(wrd, width) { |
|
1239 | 75x |
vapply(wrd, function(wrd_i) { |
1240 | 75x |
init_v <- seq(1, nchar(wrd_i), by = width) |
1241 | 75x |
end_v <- c(init_v[-1] - 1, nchar(wrd_i)) |
1242 | 75x |
fin_str_v <- substring(wrd_i, init_v, end_v) |
1243 | 75x |
is_only_spaces <- grepl("^\\s+$", fin_str_v) |
1244 |
# We pop only spaces at this point |
|
1245 | 75x |
if (all(is_only_spaces)) { |
1246 | ! |
fin_str_v <- fin_str_v[1] # keep only one width-sized empty |
1247 |
} else { |
|
1248 | 75x |
fin_str_v <- fin_str_v[!is_only_spaces] # hybrid text + \s |
1249 |
} |
|
1250 | ||
1251 |
# Collapse the string |
|
1252 | 75x |
paste0(fin_str_v, collapse = " ") |
1253 | 75x |
}, character(1), USE.NAMES = FALSE) |
1254 |
} |
|
1255 | ||
1256 |
#' @describeIn wrap_string Deprecated function. Please use [wrap_string()] instead. |
|
1257 |
#' |
|
1258 |
#' @examples |
|
1259 |
#' wrap_txt(str, 5, collapse = NULL) |
|
1260 |
#' |
|
1261 |
#' @export |
|
1262 |
wrap_txt <- function(str, width, collapse = NULL, fontspec = font_spec()) { |
|
1263 | 396x |
new_dev <- open_font_dev(fontspec) |
1264 | 396x |
if (new_dev) { |
1265 | 2x |
on.exit(close_font_dev()) |
1266 |
} |
|
1267 | ||
1268 | 396x |
unlist(wrap_string(str, width, collapse, fontspec = fontspec), use.names = FALSE) |
1269 |
} |
|
1270 | ||
1271 |
pad_vert_top <- function(x, len, default = "") { |
|
1272 | 5510x |
c(x, rep(default, len - length(x))) |
1273 |
} |
|
1274 | ||
1275 |
pad_vert_bottom <- function(x, len, default = "") { |
|
1276 | 326x |
c(rep(default, len - length(x)), x) |
1277 |
} |
|
1278 | ||
1279 |
pad_vec_to_len <- function(vec, len, cpadder = pad_vert_top, rlpadder = cpadder) { |
|
1280 | 711x |
dat <- unlist(lapply(vec[-1], cpadder, len = len)) |
1281 | 711x |
dat <- c(rlpadder(vec[[1]], len = len), dat) |
1282 | 711x |
matrix(dat, nrow = len) |
1283 |
} |
|
1284 | ||
1285 |
rep_vec_to_len <- function(vec, len, ...) { |
|
1286 | 674x |
matrix(unlist(lapply(vec, rep, times = len)), |
1287 | 674x |
nrow = len |
1288 |
) |
|
1289 |
} |
|
1290 | ||
1291 |
safe_strsplit <- function(x, split, ...) { |
|
1292 | 948x |
ret <- strsplit(x, split, ...) |
1293 | 948x |
lapply(ret, function(reti) if (length(reti) == 0) "" else reti) |
1294 |
} |
|
1295 | ||
1296 |
.expand_mat_rows_inner <- function(i, mat, row_nlines, expfun, ...) { |
|
1297 | 1385x |
leni <- row_nlines[i] |
1298 | 1385x |
rw <- mat[i, ] |
1299 | 1385x |
if (is.character(rw)) { |
1300 | 948x |
rw <- safe_strsplit(rw, "\n", fixed = TRUE) |
1301 |
} |
|
1302 | 1385x |
expfun(rw, len = leni, ...) |
1303 |
} |
|
1304 | ||
1305 |
expand_mat_rows <- function(mat, row_nlines = apply(mat, 1, nlines), expfun = pad_vec_to_len, ...) { |
|
1306 | 238x |
rinds <- seq_len(nrow(mat)) |
1307 | 238x |
exprows <- lapply(rinds, .expand_mat_rows_inner, |
1308 | 238x |
mat = mat, |
1309 | 238x |
row_nlines = row_nlines, |
1310 | 238x |
expfun = expfun, |
1311 |
... |
|
1312 |
) |
|
1313 | 238x |
do.call(rbind, exprows) |
1314 |
} |
|
1315 | ||
1316 |
#' Transform a vector of spans (with duplication) into a visibility vector |
|
1317 |
#' |
|
1318 |
#' @param spans (`numeric`)\cr a vector of spans, with each span value repeated |
|
1319 |
#' for the cells it covers. |
|
1320 |
#' |
|
1321 |
#' @details |
|
1322 |
#' The values of `spans` are assumed to be repeated such that each individual position covered by the |
|
1323 |
#' span has the repeated value. |
|
1324 |
#' |
|
1325 |
#' This means that each block of values in `spans` must be of a length at least equal to its value |
|
1326 |
#' (i.e. two 2s, three 3s, etc). |
|
1327 |
#' |
|
1328 |
#' This function correctly handles cases where two spans of the same size are next to each other; |
|
1329 |
#' i.e., a block of four 2s represents two large cells each of which spans two individual cells. |
|
1330 |
#' |
|
1331 |
#' @return A logical vector the same length as `spans` indicating whether the contents of a string vector |
|
1332 |
#' with those spans is valid. |
|
1333 |
#' |
|
1334 |
#' @note |
|
1335 |
#' Currently no checking or enforcement is done to verify that the vector of spans is valid according to |
|
1336 |
#' the specifications described in the Details section above. |
|
1337 |
#' |
|
1338 |
#' @examples |
|
1339 |
#' spans_to_viscell(c(2, 2, 2, 2, 1, 3, 3, 3)) |
|
1340 |
#' |
|
1341 |
#' @export |
|
1342 |
spans_to_viscell <- function(spans) { |
|
1343 | 2x |
if (!is.vector(spans)) { |
1344 | ! |
spans <- as.vector(spans) |
1345 |
} |
|
1346 | 2x |
myrle <- rle(spans) |
1347 | 2x |
unlist( |
1348 | 2x |
mapply( |
1349 | 2x |
function(vl, ln) { |
1350 | 4x |
rep(c(TRUE, rep(FALSE, vl - 1L)), times = ln / vl) |
1351 |
}, |
|
1352 | 2x |
SIMPLIFY = FALSE, |
1353 | 2x |
vl = myrle$values, |
1354 | 2x |
ln = myrle$lengths |
1355 |
), |
|
1356 | 2x |
recursive = FALSE |
1357 |
) |
|
1358 |
} |
|
1359 | ||
1360 |
#' Propose column widths based on the `MatrixPrintForm` of an object |
|
1361 |
#' |
|
1362 |
#' Row names are also considered a column for the output. |
|
1363 |
#' |
|
1364 |
#' @inheritParams open_font_dev |
|
1365 |
#' @param x (`ANY`)\cr a `MatrixPrintForm` object, or an object with a `matrix_form` method. |
|
1366 |
#' @param indent_size (`numeric(1)`)\cr indent size, in characters. Ignored when `x` is already |
|
1367 |
#' a `MatrixPrintForm` object in favor of information there. |
|
1368 |
#' |
|
1369 |
#' @return A vector of column widths based on the content of `x` for use in printing and pagination. |
|
1370 |
#' |
|
1371 |
#' @examples |
|
1372 |
#' mf <- basic_matrix_form(mtcars) |
|
1373 |
#' propose_column_widths(mf) |
|
1374 |
#' |
|
1375 |
#' @export |
|
1376 |
propose_column_widths <- function(x, |
|
1377 |
indent_size = 2, |
|
1378 |
fontspec = font_spec()) { |
|
1379 | 92x |
new_dev <- open_font_dev(fontspec) |
1380 | 92x |
if (new_dev) { |
1381 | 62x |
on.exit(close_font_dev()) |
1382 |
} |
|
1383 | ||
1384 | 92x |
if (!is(x, "MatrixPrintForm")) { |
1385 | ! |
x <- matrix_form(x, indent_rownames = TRUE, indent_size = indent_size, fontspec = fontspec) |
1386 |
} |
|
1387 | 92x |
body <- mf_strings(x) |
1388 | 92x |
spans <- mf_spans(x) |
1389 | 92x |
aligns <- mf_aligns(x) |
1390 | 92x |
display <- mf_display(x) |
1391 | ||
1392 |
# compute decimal alignment if asked in alignment matrix |
|
1393 | 92x |
if (any_dec_align(aligns)) { |
1394 | 27x |
body <- decimal_align(body, aligns) |
1395 |
} |
|
1396 | ||
1397 |
## chars <- nchar(body) #old monospace assumption |
|
1398 |
## we now use widths in terms of the printwidth of the space (" ") |
|
1399 |
## character. This collapses to the same thing in the monospace |
|
1400 |
## case but allows us to reasonably support truetype fonts |
|
1401 | 89x |
chars <- nchar_ttype(body, fontspec) |
1402 | ||
1403 |
# first check column widths without colspan |
|
1404 | 89x |
has_spans <- spans != 1 |
1405 | 89x |
chars_ns <- chars |
1406 | 89x |
chars_ns[has_spans] <- 0 |
1407 | 89x |
widths <- apply(chars_ns, 2, max) |
1408 | ||
1409 |
# now check if the colspans require extra width |
|
1410 | 89x |
if (any(has_spans)) { |
1411 | 1x |
has_row_spans <- apply(has_spans, 1, any) |
1412 | ||
1413 | 1x |
chars_sp <- chars[has_row_spans, , drop = FALSE] |
1414 | 1x |
spans_sp <- spans[has_row_spans, , drop = FALSE] |
1415 | 1x |
disp_sp <- display[has_row_spans, , drop = FALSE] |
1416 | ||
1417 | 1x |
nc <- ncol(spans) |
1418 | 1x |
for (i in seq_len(nrow(chars_sp))) { |
1419 | 1x |
for (j in seq_len(nc)) { |
1420 | 2x |
if (disp_sp[i, j] && spans_sp[i, j] != 1) { |
1421 | 1x |
i_cols <- seq(j, j + spans_sp[i, j] - 1) |
1422 | ||
1423 | 1x |
nchar_i <- chars_sp[i, j] |
1424 | 1x |
cw_i <- widths[i_cols] |
1425 | 1x |
available_width <- sum(cw_i) |
1426 | ||
1427 | 1x |
if (nchar_i > available_width) { |
1428 |
# need to update widths to fit content with colspans |
|
1429 |
# spread width among columns |
|
1430 | ! |
widths[i_cols] <- cw_i + spread_integer(nchar_i - available_width, length(cw_i)) |
1431 |
} |
|
1432 |
} |
|
1433 |
} |
|
1434 |
} |
|
1435 |
} |
|
1436 | 89x |
widths |
1437 |
} |
|
1438 | ||
1439 |
## "number of characters" width in terms of |
|
1440 |
## width of " " for the chosen font family |
|
1441 | ||
1442 |
## pdf device with font specification MUST already be open |
|
1443 | ||
1444 |
#' Calculate font-specific string width |
|
1445 |
#' |
|
1446 |
#' This function returns the width of each element `x` |
|
1447 |
#' *as a multiple of the width of the space character |
|
1448 |
#' for in declared font*, rounded up to the nearest |
|
1449 |
#' integer. This is used extensively in the text rendering |
|
1450 |
#' ([toString()]) and pagination machinery for |
|
1451 |
#' calculating word wrapping, default column widths, |
|
1452 |
#' lines per page, etc. |
|
1453 |
#' |
|
1454 |
#' @param x (`character`)\cr the string(s) to calculate width(s) for. |
|
1455 |
#' @param fontspec (`font_spec` or `NULL`)\cr if non-NULL, the font to use for |
|
1456 |
#' the calculations (as returned by [font_spec()]). Defaults to "Courier", |
|
1457 |
#' which is a monospace font. If NULL, the width will be returned |
|
1458 |
#' in number of characters by calling `nchar` directly. |
|
1459 |
#' @param tol (`numeric(1)`)\cr the tolerance to use when determining |
|
1460 |
#' if a multiple needs to be rounded up to the next integer. See |
|
1461 |
#' Details. |
|
1462 |
#' @param raw (`logical(1)`)\cr whether unrounded widths should be returned. Defaults to `FALSE`. |
|
1463 |
#' |
|
1464 |
#' @details String width is defined in terms of spaces within |
|
1465 |
#' the specified font. For monospace fonts, this definition |
|
1466 |
#' collapses to the number of characters in the string |
|
1467 |
#' ([nchar()]), but for truetype fonts it does not. |
|
1468 |
#' |
|
1469 |
#' For `raw = FALSE`, non-integer values (the norm in a truetype |
|
1470 |
#' setting) for the number of spaces a string takes up is rounded |
|
1471 |
#' up, *unless the multiple is less than `tol` above the last integer |
|
1472 |
#' before it*. E.g., if `k - num_spaces < tol` for an integer |
|
1473 |
#' `k`, `k` is returned instead of `k+1`. |
|
1474 |
#' |
|
1475 |
#' @seealso [font_spec()] |
|
1476 |
#' |
|
1477 |
#' @examples |
|
1478 |
#' nchar_ttype("hi there!") |
|
1479 |
#' |
|
1480 |
#' nchar_ttype("hi there!", font_spec("Times")) |
|
1481 |
#' |
|
1482 |
#' @export |
|
1483 |
nchar_ttype <- function(x, fontspec = font_spec(), tol = sqrt(.Machine$double.eps), raw = FALSE) { |
|
1484 |
## escape hatch because sometimes we need to call, e.g. make_row_df |
|
1485 |
## but we dont' care about getting the word wrapping right and the |
|
1486 |
## performance penalty was KILLING us. Looking at you |
|
1487 |
## rtables::update_ref_indexing @.@ |
|
1488 | 48657x |
if (is.null(fontspec)) { |
1489 | 1x |
return(nchar(x)) |
1490 |
} |
|
1491 | 48656x |
new_dev <- open_font_dev(fontspec) |
1492 | 48656x |
if (new_dev) { |
1493 | 149x |
on.exit(close_font_dev()) |
1494 |
} |
|
1495 | 48656x |
if (font_dev_state$ismonospace) { ## WAY faster if we can do it |
1496 | 48632x |
return(nchar(x)) |
1497 |
} |
|
1498 | 24x |
space_width <- get_space_width() |
1499 |
## cwidth_inches_unsafe is ok here because if we don't |
|
1500 |
## have a successfully opened state (somehow), get_space_width |
|
1501 |
## above will error. |
|
1502 | 24x |
num_inches_raw <- vapply(x, cwidth_inches_unsafe, 1.0) |
1503 | 24x |
num_spaces_raw <- num_inches_raw / space_width |
1504 | 24x |
if (!raw) { |
1505 | 1x |
num_spaces_ceil <- ceiling(num_spaces_raw) |
1506 |
## we don't want to add one when the answer is e.g, 3.0000000000000953 |
|
1507 | 1x |
within_tol <- which(num_spaces_raw + 1 - num_spaces_ceil <= tol) |
1508 | 1x |
ret <- num_spaces_ceil |
1509 | 1x |
if (length(within_tol) == 0L) { |
1510 | 1x |
ret[within_tol] <- floor(num_spaces_raw[within_tol]) |
1511 |
} |
|
1512 |
} else { |
|
1513 | 23x |
ret <- num_spaces_raw |
1514 |
} |
|
1515 | 24x |
if (!is.null(dim(x))) { |
1516 | ! |
dim(ret) <- dim(x) |
1517 |
} else { |
|
1518 | 24x |
names(ret) <- NULL |
1519 |
} |
|
1520 | 24x |
ret |
1521 |
} |
|
1522 | ||
1523 |
#' Pad a string and align within string |
|
1524 |
#' |
|
1525 |
#' @inheritParams open_font_dev |
|
1526 |
#' @param x (`string`)\cr a string. |
|
1527 |
#' @param n (`integer(1)`)\cr number of characters in the output string. If `n < nchar(x)`, an error is thrown. |
|
1528 |
#' @param just (`string`)\cr text alignment justification to use. Defaults to `"center"`. Must be one of |
|
1529 |
#' `"center"`, `"right"`, `"left"`, `"dec_right"`, `"dec_left"`, or `"decimal"`. |
|
1530 |
#' |
|
1531 |
#' @return `x`, padded to be a string of length `n`. |
|
1532 |
#' |
|
1533 |
#' @examples |
|
1534 |
#' padstr("abc", 3) |
|
1535 |
#' padstr("abc", 4) |
|
1536 |
#' padstr("abc", 5) |
|
1537 |
#' padstr("abc", 5, "left") |
|
1538 |
#' padstr("abc", 5, "right") |
|
1539 |
#' |
|
1540 |
#' \dontrun{ |
|
1541 |
#' # Expect error: "abc" has more than 1 characters |
|
1542 |
#' padstr("abc", 1) |
|
1543 |
#' } |
|
1544 |
#' |
|
1545 |
#' @export |
|
1546 |
padstr <- function(x, n, just = list_valid_aligns(), fontspec = font_spec()) { |
|
1547 | 15607x |
just <- match.arg(just) |
1548 | ||
1549 | 1x |
if (length(x) != 1) stop("length of x needs to be 1 and not", length(x)) |
1550 | 1x |
if (is.na(n) || !is.numeric(n) || n < 0) stop("n needs to be numeric and > 0") |
1551 | ||
1552 | 2x |
if (is.na(x)) x <- "<NA>" |
1553 | ||
1554 | 15605x |
nc <- nchar_ttype(x, fontspec) |
1555 | ! |
if (n < nc) stop("\"", x, "\" has more than ", n, " characters") |
1556 | ||
1557 | 15605x |
switch(just, |
1558 |
center = { |
|
1559 | 13706x |
pad <- (n - nc) / 2 |
1560 | 13706x |
paste0(spaces(floor(pad)), x, spaces(ceiling(pad))) |
1561 |
}, |
|
1562 | 1748x |
left = paste0(x, spaces(n - nc)), |
1563 | 10x |
right = paste0(spaces(n - nc), x), |
1564 |
decimal = { |
|
1565 | 61x |
pad <- (n - nc) / 2 |
1566 | 61x |
paste0(spaces(floor(pad)), x, spaces(ceiling(pad))) |
1567 |
}, |
|
1568 | 45x |
dec_left = paste0(x, spaces(n - nc)), |
1569 | 35x |
dec_right = paste0(spaces(n - nc), x) |
1570 |
) |
|
1571 |
} |
|
1572 | ||
1573 |
spaces <- function(n) { |
|
1574 | 29530x |
strrep(" ", n) |
1575 |
} |
|
1576 | ||
1577 |
.paste_no_na <- function(x, ...) { |
|
1578 | 2394x |
paste(na.omit(x), ...) |
1579 |
} |
|
1580 | ||
1581 |
#' Spread an integer to a given length |
|
1582 |
#' |
|
1583 |
#' @param x (`integer(1)`)\cr number to spread. |
|
1584 |
#' @param len (`integer(1)`)\cr number of times to repeat `x`. |
|
1585 |
#' |
|
1586 |
#' @return If `x` is a scalar whole number value (see [is.wholenumber()]), the value `x` is repeated `len` times. |
|
1587 |
#' Otherwise, an error is thrown. |
|
1588 |
#' |
|
1589 |
#' @examples |
|
1590 |
#' spread_integer(3, 1) |
|
1591 |
#' spread_integer(0, 3) |
|
1592 |
#' spread_integer(1, 3) |
|
1593 |
#' spread_integer(2, 3) |
|
1594 |
#' spread_integer(3, 3) |
|
1595 |
#' spread_integer(4, 3) |
|
1596 |
#' spread_integer(5, 3) |
|
1597 |
#' spread_integer(6, 3) |
|
1598 |
#' spread_integer(7, 3) |
|
1599 |
#' |
|
1600 |
#' @export |
|
1601 |
spread_integer <- function(x, len) { |
|
1602 | 2x |
stopifnot( |
1603 | 2x |
is.wholenumber(x), length(x) == 1, x >= 0, |
1604 | 2x |
is.wholenumber(len), length(len) == 1, len >= 0, |
1605 | 2x |
!(len == 0 && x > 0) |
1606 |
) |
|
1607 | ||
1608 | 1x |
if (len == 0) { |
1609 | ! |
integer(0) |
1610 |
} else { |
|
1611 | 1x |
y <- rep(floor(x / len), len) |
1612 | 1x |
i <- 1 |
1613 | 1x |
while (sum(y) < x) { |
1614 | 1x |
y[i] <- y[i] + 1 |
1615 | 1x |
if (i == len) { |
1616 | ! |
i <- 1 |
1617 |
} else { |
|
1618 | 1x |
i <- i + 1 |
1619 |
} |
|
1620 |
} |
|
1621 | 1x |
y |
1622 |
} |
|
1623 |
} |
|
1624 | ||
1625 |
#' Check if a value is a whole number |
|
1626 |
#' |
|
1627 |
#' @param x (`numeric(1)`)\cr a numeric value. |
|
1628 |
#' @param tol (`numeric(1)`)\cr a precision tolerance. |
|
1629 |
#' |
|
1630 |
#' @return `TRUE` if `x` is within `tol` of zero, `FALSE` otherwise. |
|
1631 |
#' |
|
1632 |
#' @examples |
|
1633 |
#' is.wholenumber(5) |
|
1634 |
#' is.wholenumber(5.00000000000000001) |
|
1635 |
#' is.wholenumber(.5) |
|
1636 |
#' |
|
1637 |
#' @export |
|
1638 |
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) { |
|
1639 | 3x |
abs(x - round(x)) < tol |
1640 |
} |
1 |
## #' Page Dimensions |
|
2 |
## #' |
|
3 |
## #' Dimensions for mapping page dimensions to text dimensions |
|
4 |
## #' @references https://www.ietf.org/rfc/rfc0678.txt |
|
5 |
## #' @export |
|
6 |
## #' @rdname pagedims |
|
7 |
## lpi_vert <- 6 |
|
8 |
## #' @export |
|
9 |
## #' @rdname pagedims |
|
10 |
## cpi_horiz <- 10 |
|
11 |
## #' @export |
|
12 |
## #' @rdname pagedims |
|
13 |
## horiz_margin_chars <- 13 |
|
14 |
## #' @export |
|
15 |
## #' @rdname pagedims |
|
16 |
## horiz_margin_inches <- horiz_margin_chars / cpi_horiz |
|
17 |
## #' @export |
|
18 |
## #' @rdname pagedims |
|
19 |
## vert_margin_lines <- 6 |
|
20 |
## #' @export |
|
21 |
## #' @rdname pagedims |
|
22 |
## vert_margin_inches <- vert_margin_lines / lpi_vert |
|
23 | ||
24 |
## #' Physical Page dimensions to chars x lines |
|
25 |
## #' |
|
26 |
## #' Calculate number of lines long and characters wide a page size is, |
|
27 |
## #' after excluding margins |
|
28 |
## #' @export |
|
29 |
## #' @examples |
|
30 |
## #' phys_page_to_lc() |
|
31 |
## phys_page_to_lc <- function(width = 8.5, len = 11, |
|
32 |
## h_margin = horiz_margin_inches, |
|
33 |
## v_margin = vert_margin_inches) { |
|
34 |
## lgl_width <- width - h_margin |
|
35 |
## lgl_len <- len - v_margin |
|
36 |
## c(chars_wide = floor(lgl_width * cpi_horiz), |
|
37 |
## lines_long = floor(lgl_len * lpi_vert)) |
|
38 |
## } |
|
39 | ||
40 |
#' Pagination |
|
41 |
#' |
|
42 |
#' @section Pagination Algorithm: |
|
43 |
#' |
|
44 |
#' Pagination is performed independently in the vertical and horizontal |
|
45 |
#' directions based solely on a *pagination data frame*, which includes the |
|
46 |
#' following information for each row/column: |
|
47 |
#' |
|
48 |
#' - Number of lines/characters rendering the row will take **after |
|
49 |
#' word-wrapping** (`self_extent`) |
|
50 |
#' - The indices (`reprint_inds`) and number of lines (`par_extent`) |
|
51 |
#' of the rows which act as **context** for the row |
|
52 |
#' - The row's number of siblings and position within its siblings |
|
53 |
#' |
|
54 |
#' Given `lpp` (`cpp`) is already adjusted for rendered elements which |
|
55 |
#' are not rows/columns and a data frame of pagination information, |
|
56 |
#' pagination is performed via the following algorithm with `start = 1`. |
|
57 |
#' |
|
58 |
#' Core Pagination Algorithm: |
|
59 |
#' |
|
60 |
#' 1. Initial guess for pagination position is `start + lpp` (`start + cpp`) |
|
61 |
#' 2. While the guess is not a valid pagination position, and `guess > start`, |
|
62 |
#' decrement guess and repeat. |
|
63 |
#' - An error is thrown if all possible pagination positions between |
|
64 |
#' `start` and `start + lpp` (`start + cpp`) would be `< start` |
|
65 |
#' after decrementing |
|
66 |
#' 3. Retain pagination index |
|
67 |
#' 4. If pagination point was less than `NROW(tt)` (`ncol(tt)`), set |
|
68 |
#' `start` to `pos + 1`, and repeat steps (1) - (4). |
|
69 |
#' |
|
70 |
#' Validating Pagination Position: |
|
71 |
#' |
|
72 |
#' Given an (already adjusted) `lpp` or `cpp` value, a pagination is invalid if: |
|
73 |
#' |
|
74 |
#' - The rows/columns on the page would take more than (adjusted) `lpp` lines/`cpp` |
|
75 |
#' characters to render **including**: |
|
76 |
#' - word-wrapping |
|
77 |
#' - (vertical only) context repetition |
|
78 |
#' - (vertical only) footnote messages and/or section divider lines |
|
79 |
#' take up too many lines after rendering rows |
|
80 |
#' - (vertical only) row is a label or content (row-group summary) row |
|
81 |
#' - (vertical only) row at the pagination point has siblings, and |
|
82 |
#' it has less than `min_siblings` preceding or following siblings |
|
83 |
#' - pagination would occur within a sub-table listed in `nosplitin` |
|
84 |
#' |
|
85 |
#' @name pagination_algo |
|
86 |
NULL |
|
87 | ||
88 |
#' Create a row of a pagination data frame |
|
89 |
#' |
|
90 |
#' @inheritParams open_font_dev |
|
91 |
#' @param nm (`string`)\cr name. |
|
92 |
#' @param lab (`string`)\cr label. |
|
93 |
#' @param rnum (`numeric(1)`)\cr absolute row number. |
|
94 |
#' @param pth (`character` or `NULL`)\cr path within larger table. |
|
95 |
#' @param sibpos (`integer(1)`)\cr position among sibling rows. |
|
96 |
#' @param nsibs (`integer(1)`)\cr number of siblings (including self). |
|
97 |
#' @param extent (`numeric(1)`)\cr number of lines required to print the row. |
|
98 |
#' @param colwidths (`numeric`)\cr column widths. |
|
99 |
#' @param repext (`integer(1)`)\cr number of lines required to reprint all context for this row if it appears directly |
|
100 |
#' after pagination. |
|
101 |
#' @param repind (`integer`)\cr vector of row numbers to be reprinted if this row appears directly after pagination. |
|
102 |
#' @param indent (`integer`)\cr indent. |
|
103 |
#' @param rclass (`string`)\cr class of row object. |
|
104 |
#' @param nrowrefs (`integer(1)`)\cr number of row referential footnotes for this row. |
|
105 |
#' @param ncellrefs (`integer(1)`)\cr number of cell referential footnotes for the cells in this row. |
|
106 |
#' @param nreflines (`integer(1)`)\cr total number of lines required by all referential footnotes. |
|
107 |
#' @param force_page (`flag`)\cr currently ignored. |
|
108 |
#' @param page_title (`flag`)\cr currently ignored. |
|
109 |
#' @param trailing_sep (`string`)\cr the string to use as a separator below this row during printing. |
|
110 |
#' If `NA_character_`, no separator is used. |
|
111 |
#' @param row (`ANY`)\cr object representing the row, which is used for default values of `nm`, `lab`, |
|
112 |
#' `extent`, and `rclass` if provided. Must have methods for `obj_name`, `obj_label`, and `nlines`, to retrieve |
|
113 |
#' default values of `nm`, `lab`, and `extent`, respectively. |
|
114 |
#' |
|
115 |
#' @return A single row `data.frame` with the appropriate columns for a pagination info data frame. |
|
116 |
#' |
|
117 |
#' @export |
|
118 |
pagdfrow <- function(row, |
|
119 |
nm = obj_name(row), |
|
120 |
lab = obj_label(row), |
|
121 |
rnum, |
|
122 |
pth, |
|
123 |
sibpos = NA_integer_, |
|
124 |
nsibs = NA_integer_, |
|
125 |
extent = nlines(row, colwidths, fontspec = fontspec), |
|
126 |
colwidths = NULL, |
|
127 |
repext = 0L, |
|
128 |
repind = integer(), |
|
129 |
indent = 0L, |
|
130 |
rclass = class(row), |
|
131 |
nrowrefs = 0L, |
|
132 |
ncellrefs = 0L, |
|
133 |
nreflines = 0L, |
|
134 |
# ref_df = .make_ref_df(NULL, NULL), |
|
135 |
force_page = FALSE, |
|
136 |
page_title = NA_character_, |
|
137 |
trailing_sep = NA_character_, |
|
138 |
fontspec) { |
|
139 | 1430x |
data.frame( |
140 | 1430x |
label = lab, |
141 | 1430x |
name = nm, |
142 | 1430x |
abs_rownumber = rnum, |
143 | 1430x |
path = I(list(pth)), |
144 | 1430x |
pos_in_siblings = sibpos, |
145 | 1430x |
n_siblings = nsibs, |
146 | 1430x |
self_extent = extent, |
147 | 1430x |
par_extent = repext, |
148 | 1430x |
reprint_inds = I(rep(list(unlist(repind)), length.out = length(nm))), |
149 | 1430x |
node_class = rclass, |
150 | 1430x |
indent = max(0L, indent), |
151 | 1430x |
nrowrefs = nrowrefs, |
152 | 1430x |
ncellrefs = ncellrefs, |
153 | 1430x |
nreflines = nreflines, |
154 |
# ref_info_df = I(list(ref_df)), |
|
155 | 1430x |
force_page = force_page, |
156 | 1430x |
page_title = page_title, |
157 | 1430x |
trailing_sep = trailing_sep, |
158 | 1430x |
stringsAsFactors = FALSE, |
159 | 1430x |
row.names = NULL, |
160 | 1430x |
check.names = FALSE, |
161 | 1430x |
fix.empty.names = FALSE |
162 |
) |
|
163 |
} |
|
164 | ||
165 |
calc_ref_nlines_df <- function(pagdf) { |
|
166 |
## XXX XXX XXX this is dangerous and wrong!!! |
|
167 | 628x |
if (is.null(pagdf$ref_info_df) && sum(pagdf$nreflines) == 0) { |
168 | 221x |
return(ref_df_row()[0, ]) |
169 |
} |
|
170 | 407x |
refdf <- do.call(rbind.data.frame, pagdf$ref_info_df) |
171 | 407x |
if (NROW(refdf) == 0) { |
172 | 375x |
return(ref_df_row()[0, ]) |
173 |
} |
|
174 | 32x |
unqsyms <- !duplicated(refdf$symbol) |
175 | 32x |
refdf[unqsyms, , drop = FALSE] |
176 |
} |
|
177 | ||
178 |
build_fail_msg <- function(row, lines, raw_rowlines, |
|
179 |
allowed_lines, lpp, decoration_lines, |
|
180 |
start, guess, rep_ext, n_reprint, |
|
181 |
reflines, n_refs, sectlines) { |
|
182 | 254x |
if (row) { |
183 | 104x |
spacetype <- "lines" |
184 | 104x |
spacetype_abr <- "lns" |
185 | 104x |
structtype_abr <- "rws" |
186 | 104x |
sprintf( |
187 | 104x |
paste0( |
188 | 104x |
" FAIL: rows selected for pagination require %d %s while only %d are available from ", |
189 | 104x |
"lpp = %d and %d header/footers lines.\n", |
190 | 104x |
" details: [raw: %d %s (%d %s), rep. context: %d %s (%d %s), ", |
191 | 104x |
"refs: %d %s (%d) sect. divs: %d %s]." |
192 |
), |
|
193 | 104x |
lines, |
194 | 104x |
spacetype, |
195 | 104x |
allowed_lines, |
196 | 104x |
lpp, |
197 | 104x |
decoration_lines, # header + footers |
198 | 104x |
raw_rowlines, |
199 | 104x |
spacetype_abr, |
200 | 104x |
guess - start + 1, # because it includes both start and guess |
201 | 104x |
structtype_abr, |
202 | 104x |
rep_ext, |
203 | 104x |
spacetype_abr, |
204 | 104x |
n_reprint, |
205 | 104x |
structtype_abr, |
206 | 104x |
reflines, |
207 | 104x |
spacetype_abr, |
208 | 104x |
n_refs, |
209 | 104x |
sectlines, |
210 | 104x |
spacetype_abr |
211 |
) |
|
212 |
} else { ## !row |
|
213 | 150x |
spacetype <- "chars" |
214 | 150x |
spacetype_abr <- "chars" |
215 | 150x |
structtype_abr <- "cols" |
216 | 150x |
raw_ncol <- guess - start + 1 |
217 | 150x |
tot_ncol <- raw_ncol + n_reprint |
218 | 150x |
rep_ext <- rep_ext |
219 | 150x |
sprintf( |
220 | 150x |
paste0( |
221 | 150x |
" FAIL: selected %d columns require %d %s, while only %d are available. \n", |
222 | 150x |
" details: [raw: %d %s (%d %s), rep. cols: %d %s (%d %s), tot. colgap: %d %s]." |
223 |
), |
|
224 | 150x |
guess - start + 1, |
225 | 150x |
lines + rep_ext + sectlines, |
226 | 150x |
spacetype, |
227 | 150x |
lpp, |
228 | 150x |
lines, |
229 | 150x |
spacetype_abr, |
230 | 150x |
raw_ncol, |
231 | 150x |
structtype_abr, |
232 | 150x |
rep_ext, |
233 | 150x |
spacetype_abr, |
234 | 150x |
n_reprint, |
235 | 150x |
structtype_abr, |
236 | 150x |
sectlines, |
237 | 150x |
spacetype |
238 |
) |
|
239 |
} |
|
240 |
} |
|
241 | ||
242 |
valid_pag <- function(pagdf, |
|
243 |
guess, |
|
244 |
start, |
|
245 |
rlpp, |
|
246 |
lpp, # for informational purposes only |
|
247 |
context_lpp, # for informational purposes only (headers/footers) |
|
248 |
min_sibs, |
|
249 |
nosplit = NULL, |
|
250 |
div_height = 1L, |
|
251 |
verbose = FALSE, |
|
252 |
row = TRUE, |
|
253 |
have_col_fnotes = FALSE, |
|
254 |
col_gap, |
|
255 |
has_rowlabels) { |
|
256 |
# FALSE output from this function means that another guess is taken till success or failure |
|
257 | 628x |
rw <- pagdf[guess, ] |
258 | ||
259 | 628x |
if (verbose) { |
260 | 382x |
message( |
261 | 382x |
"-> Attempting pagination between ", start, " and ", guess, " ", |
262 | 382x |
paste(ifelse(row, "row", "column")) |
263 |
) |
|
264 |
} |
|
265 | ||
266 |
# Fix for counting the right number of lines when there is wrapping on a keycols |
|
267 | 628x |
if (.is_listing_mf(pagdf) && !is.null(pagdf$self_extent_page_break)) { |
268 | 28x |
pagdf$self_extent[start] <- pagdf$self_extent_page_break[start] |
269 |
} |
|
270 | ||
271 | 628x |
raw_rowlines <- sum(pagdf[start:guess, "self_extent"] - pagdf[start:guess, "nreflines"]) |
272 | ||
273 | 628x |
refdf_ii <- calc_ref_nlines_df(pagdf[start:guess, ]) |
274 | 628x |
reflines <- if (row) sum(refdf_ii$nlines, 0L) else 0L |
275 | 628x |
if (reflines > 0 && !have_col_fnotes) { |
276 | 32x |
reflines <- reflines + div_height + 1L |
277 |
} |
|
278 | ||
279 | ||
280 | 628x |
rowlines <- raw_rowlines + reflines ## sum(pagdf[start:guess, "self_extent"]) - reflines |
281 |
## self extent includes reflines |
|
282 |
## self extent does ***not*** currently include trailing sep for rows |
|
283 |
## self extent does ***not*** currently include col_gap for columns |
|
284 |
## we don't include the trailing_sep for guess because if we paginate here it won't be printed |
|
285 | 628x |
ncols <- 0L |
286 | 628x |
if (row) { |
287 | 257x |
sectlines <- if (start == guess) 0L else sum(!is.na(pagdf[start:(guess - 1), "trailing_sep"])) |
288 |
} else { ## columns |
|
289 | 371x |
ncols <- guess - start + 1 + length(pagdf$reprint_inds[[start]]) ## +1 because its inclusive, 5-6 is 2 columns |
290 | 371x |
sectlines <- col_gap * (ncols - as.integer(!has_rowlabels)) ## -1 if no row labels |
291 |
} |
|
292 | 628x |
lines <- rowlines + sectlines |
293 | 628x |
rep_ext <- pagdf$par_extent[start] |
294 | 628x |
if (lines > rlpp) { |
295 | 382x |
if (verbose) { |
296 | 254x |
structtype <- ifelse(row, "rows", "columns") |
297 | 254x |
structtype_abr <- ifelse(row, "rows", "cols") |
298 | 254x |
spacetype <- ifelse(row, "lines", "chars") |
299 | 254x |
spacetype_abr <- ifelse(row, "lns", "chrs") |
300 | 254x |
msg <- build_fail_msg( |
301 | 254x |
row, lines, raw_rowlines, |
302 | 254x |
allowed_lines = rlpp, lpp = lpp, decoration_lines = context_lpp, |
303 | 254x |
start, guess, rep_ext, length(pagdf$reprint_inds[[start]]), |
304 | 254x |
reflines, NROW(refdf_ii), sectlines |
305 |
) |
|
306 | 254x |
message(msg) |
307 |
} |
|
308 | 382x |
return(FALSE) |
309 |
} |
|
310 | ||
311 |
# Special cases: is it a label or content row? |
|
312 | 246x |
if (rw[["node_class"]] %in% c("LabelRow", "ContentRow")) { |
313 |
# check if it has children; if no children then valid |
|
314 | 7x |
has_children <- rw$abs_rownumber %in% unlist(pagdf$reprint_inds) |
315 | 7x |
if (rw$abs_rownumber == nrow(pagdf)) { |
316 | 1x |
if (verbose) { |
317 | 1x |
message(" EXCEPTION: last row is a label or content row but in lpp") |
318 |
} |
|
319 | 6x |
} else if (!any(has_children)) { |
320 | 6x |
if (verbose) { |
321 | 6x |
message( |
322 | 6x |
" EXCEPTION: last row is a label or content row\n", |
323 | 6x |
"but does not have rows and row groups depending on it" |
324 |
) |
|
325 |
} |
|
326 |
} else { |
|
327 | ! |
if (verbose) { |
328 | ! |
message(" FAIL: last row is a label or content row") |
329 |
} |
|
330 | ! |
return(FALSE) |
331 |
} |
|
332 |
} |
|
333 | ||
334 |
# Siblings handling |
|
335 | 246x |
sibpos <- rw[["pos_in_siblings"]] |
336 | 246x |
nsib <- rw[["n_siblings"]] |
337 |
# okpos <- min(min_sibs + 1, rw[["n_siblings"]]) |
|
338 | 246x |
if (sibpos != nsib) { |
339 | 99x |
retfalse <- FALSE |
340 | 99x |
if (sibpos < min_sibs + 1) { |
341 | 25x |
retfalse <- TRUE |
342 | 25x |
if (verbose) { |
343 | 25x |
message( |
344 | 25x |
" FAIL: last row had only ", sibpos - 1, |
345 | 25x |
" preceding siblings, needed ", min_sibs |
346 |
) |
|
347 |
} |
|
348 | 74x |
} else if (nsib - sibpos < min_sibs + 1) { |
349 | 7x |
retfalse <- TRUE |
350 | 7x |
if (verbose) { |
351 | 4x |
message( |
352 | 4x |
" FAIL: last row had only ", nsib - sibpos - 1, |
353 | 4x |
" following siblings, needed ", min_sibs |
354 |
) |
|
355 |
} |
|
356 |
} |
|
357 | 99x |
if (retfalse) { |
358 | 32x |
return(FALSE) |
359 |
} |
|
360 |
} |
|
361 | 214x |
if (guess < nrow(pagdf) && length(nosplit > 0)) { |
362 |
## paths end at the leaf name which is *always* different |
|
363 | 16x |
curpth <- head(unlist(rw$path), -1) |
364 | 16x |
nxtpth <- head(unlist(pagdf$path[[guess + 1]]), -1) |
365 | ||
366 | 16x |
inplay <- nosplit[(nosplit %in% intersect(curpth, nxtpth))] |
367 | 16x |
if (length(inplay) > 0) { |
368 | 16x |
ok_split <- vapply(inplay, function(var) { |
369 | 16x |
!identical(curpth[match(var, curpth) + 1], nxtpth[match(var, nxtpth) + 1]) |
370 | 16x |
}, TRUE) |
371 | ||
372 | 16x |
curvals <- curpth[match(inplay, curpth) + 1] |
373 | 16x |
nxtvals <- nxtpth[match(inplay, nxtpth) + 1] |
374 | 16x |
if (!all(ok_split)) { |
375 | 16x |
if (verbose) { |
376 | 16x |
message( |
377 | 16x |
" FAIL: nosplit variable [", |
378 | 16x |
inplay[min(which(!ok_split))], "] would be constant [", |
379 | 16x |
curvals, "] across this pagebreak." |
380 |
) |
|
381 |
} |
|
382 | 16x |
return(FALSE) |
383 |
} |
|
384 |
} |
|
385 |
} |
|
386 | ||
387 |
# Usual output when found |
|
388 | 198x |
if (verbose) { |
389 | 83x |
message(" OK [", lines + rep_ext, if (row) " lines]" else " chars]") |
390 |
} |
|
391 | 198x |
TRUE |
392 |
} |
|
393 | ||
394 |
find_pag <- function(pagdf, |
|
395 |
current_page, |
|
396 |
start, |
|
397 |
guess, |
|
398 |
rlpp, |
|
399 |
lpp_or_cpp, |
|
400 |
context_lpp_or_cpp, |
|
401 |
min_siblings, |
|
402 |
nosplitin = character(), |
|
403 |
verbose = FALSE, |
|
404 |
row = TRUE, |
|
405 |
have_col_fnotes = FALSE, |
|
406 |
div_height = 1L, |
|
407 |
do_error = FALSE, |
|
408 |
col_gap, |
|
409 |
has_rowlabels) { |
|
410 | 204x |
if (verbose) { |
411 | 89x |
if (row) { |
412 | 44x |
message("--------- ROW-WISE: Checking possible pagination for page ", current_page) |
413 |
} else { |
|
414 | 45x |
message("========= COLUMN-WISE: Checking possible pagination for page ", current_page) |
415 |
} |
|
416 |
} |
|
417 | ||
418 | 204x |
origuess <- guess |
419 | 204x |
while (guess >= start && !valid_pag( |
420 | 204x |
pagdf, guess, |
421 | 204x |
start = start, |
422 | 204x |
rlpp = rlpp, lpp = lpp_or_cpp, context_lpp = context_lpp_or_cpp, # only lpp goes to row pagination |
423 | 204x |
min_sibs = min_siblings, |
424 | 204x |
nosplit = nosplitin, verbose, row = row, |
425 | 204x |
have_col_fnotes = have_col_fnotes, |
426 | 204x |
div_height = div_height, |
427 | 204x |
col_gap = col_gap, |
428 | 204x |
has_rowlabels = has_rowlabels |
429 |
)) { |
|
430 | 430x |
guess <- guess - 1 |
431 |
} |
|
432 | 204x |
if (guess < start) { |
433 |
# Repeat pagination process to see what went wrong with verbose on |
|
434 | 6x |
if (isFALSE(do_error) && isFALSE(verbose)) { |
435 | ! |
find_pag( |
436 | ! |
pagdf = pagdf, |
437 | ! |
current_page = current_page, |
438 | ! |
start = start, |
439 | ! |
guess = origuess, |
440 | ! |
rlpp = rlpp, lpp_or_cpp = lpp_or_cpp, context_lpp_or_cpp = context_lpp_or_cpp, |
441 | ! |
min_siblings = min_siblings, |
442 | ! |
nosplitin = nosplitin, |
443 | ! |
verbose = TRUE, |
444 | ! |
row = row, |
445 | ! |
have_col_fnotes = have_col_fnotes, |
446 | ! |
div_height = div_height, |
447 | ! |
do_error = TRUE, # only used to avoid loop |
448 | ! |
col_gap = col_gap, |
449 | ! |
has_rowlabels = has_rowlabels |
450 |
) |
|
451 |
} |
|
452 | 6x |
stop( |
453 | 6x |
"-------------------------------------- Error Summary ----------------------------------------\n", |
454 | 6x |
"Unable to find any valid pagination split for page ", current_page, " between ", |
455 | 6x |
ifelse(row, "rows ", "columns "), start, " and ", origuess, ". \n", |
456 | 6x |
"Inserted ", ifelse(row, "lpp (row-space, lines per page) ", "cpp (column-space, content per page) "), |
457 | 6x |
": ", lpp_or_cpp, "\n", |
458 | 6x |
"Context-relevant additional ", ifelse(row, "header/footers lines", "fixed column characters"), |
459 | 6x |
": ", context_lpp_or_cpp, "\n", |
460 | 6x |
ifelse(row, |
461 | 6x |
paste("Limit of allowed row lines per page:", rlpp, "\n"), |
462 | 6x |
paste("Check the minimum allowed column characters per page in the last FAIL(ed) attempt. \n") |
463 |
), |
|
464 | 6x |
"Note: take a look at the last FAIL(ed) attempt above to see what went wrong. It could be, for example, ", |
465 | 6x |
"that the inserted column width induces some wrapping, hence the inserted number of lines (lpp) is not enough." |
466 |
) |
|
467 |
} |
|
468 | 198x |
guess |
469 |
} |
|
470 | ||
471 |
#' Find pagination indices from pagination info data frame |
|
472 |
#' |
|
473 |
#' Pagination methods should typically call the `make_row_df` method |
|
474 |
#' for their object and then call this function on the resulting |
|
475 |
#' pagination info `data.frame`. |
|
476 |
#' |
|
477 |
#' @param pagdf (`data.frame`)\cr a pagination info `data.frame` as created by |
|
478 |
#' either `make_rows_df` or `make_cols_df`. |
|
479 |
#' @param rlpp (`numeric`)\cr maximum number of *row* lines per page (not including header materials), including |
|
480 |
#' (re)printed header and context rows. |
|
481 |
#' @param lpp_or_cpp (`numeric`)\cr total maximum number of *row* lines or content (column-wise characters) per page |
|
482 |
#' (including header materials and context rows). This is only for informative results with `verbose = TRUE`. |
|
483 |
#' It will print `NA` if not specified by the pagination machinery. |
|
484 |
#' @param context_lpp_or_cpp (`numeric`)\cr total number of context *row* lines or content (column-wise characters) |
|
485 |
#' per page (including header materials). Uses `NA` if not specified by the pagination machinery and is only |
|
486 |
#' for informative results with `verbose = TRUE`. |
|
487 |
#' @param min_siblings (`numeric`)\cr minimum sibling rows which must appear on either side of pagination row for a |
|
488 |
#' mid-subtable split to be valid. Defaults to 2 for tables. It is automatically turned off (set to 0) for listings. |
|
489 |
#' @param nosplitin (`character`)\cr list of names of subtables where page breaks are not allowed, regardless of other |
|
490 |
#' considerations. Defaults to none. |
|
491 |
#' @param verbose (`flag`)\cr whether additional informative messages about the search for |
|
492 |
#' pagination breaks should be shown. Defaults to `FALSE`. |
|
493 |
#' @param row (`flag`)\cr whether pagination is happening in row space (`TRUE`, the default) or column |
|
494 |
#' space (`FALSE`). |
|
495 |
#' @param have_col_fnotes (`flag`)\cr whether the table-like object being rendered has column-associated |
|
496 |
#' referential footnotes. |
|
497 |
#' @param div_height (`numeric(1)`)\cr the height of the divider line when the associated object is rendered. |
|
498 |
#' Defaults to `1`. |
|
499 |
#' @param col_gap (`numeric(1)`)\cr width of gap between columns, in same units as extent in `pagdf` (spaces |
|
500 |
#' under a particular font specification). |
|
501 |
#' @param has_rowlabels (`logical(1)`)\cr whether the object being paginated has row labels. |
|
502 |
#' |
|
503 |
#' @details `pab_indices_inner` implements the core pagination algorithm (see below) |
|
504 |
#' for a single direction (vertical if `row = TRUE` (the default), horizontal otherwise) |
|
505 |
#' based on the pagination data frame and (already adjusted for non-body rows/columns) |
|
506 |
#' lines (or characters) per page. |
|
507 |
#' |
|
508 |
#' @inheritSection pagination_algo Pagination Algorithm |
|
509 |
#' |
|
510 |
#' @return A `list` containing a vector of row numbers, broken up by page. |
|
511 |
#' |
|
512 |
#' @examples |
|
513 |
#' mypgdf <- basic_pagdf(row.names(mtcars)) |
|
514 |
#' |
|
515 |
#' paginds <- pag_indices_inner(mypgdf, rlpp = 15, min_siblings = 0) |
|
516 |
#' lapply(paginds, function(x) mtcars[x, ]) |
|
517 |
#' |
|
518 |
#' @export |
|
519 |
pag_indices_inner <- function(pagdf, |
|
520 |
rlpp, |
|
521 |
lpp_or_cpp = NA_integer_, context_lpp_or_cpp = NA_integer_, # Context number of lines |
|
522 |
min_siblings, |
|
523 |
nosplitin = character(), |
|
524 |
verbose = FALSE, |
|
525 |
row = TRUE, |
|
526 |
have_col_fnotes = FALSE, |
|
527 |
div_height = 1L, |
|
528 |
col_gap = 3L, |
|
529 |
has_rowlabels) { |
|
530 | 95x |
start <- 1 |
531 | 95x |
current_page <- 1 |
532 | 95x |
nr <- nrow(pagdf) |
533 | 95x |
ret <- list() |
534 | 95x |
while (start <= nr) { |
535 | 205x |
adjrlpp <- rlpp - pagdf$par_extent[start] |
536 | 205x |
if (adjrlpp <= 0) { |
537 | 1x |
if (row) { |
538 | 1x |
stop("Lines of repeated context (plus header materials) larger than specified lines per page") |
539 |
} else { |
|
540 | ! |
stop("Width of row labels equal to or larger than specified characters per page.") |
541 |
} |
|
542 |
} |
|
543 | 204x |
guess <- min(nr, start + adjrlpp - 1) |
544 | 204x |
end <- find_pag( |
545 | 204x |
pagdf = pagdf, |
546 | 204x |
current_page = current_page, start = start, guess = guess, |
547 | 204x |
rlpp = adjrlpp, lpp_or_cpp = lpp_or_cpp, context_lpp_or_cpp = context_lpp_or_cpp, |
548 | 204x |
min_siblings = min_siblings, |
549 | 204x |
nosplitin = nosplitin, |
550 | 204x |
verbose = verbose, |
551 | 204x |
row = row, |
552 | 204x |
have_col_fnotes = have_col_fnotes, |
553 | 204x |
div_height = div_height, |
554 | 204x |
col_gap = col_gap, |
555 | 204x |
has_rowlabels = has_rowlabels |
556 |
) |
|
557 | 198x |
ret <- c(ret, list(c( |
558 | 198x |
pagdf$reprint_inds[[start]], |
559 | 198x |
start:end |
560 |
))) |
|
561 | 198x |
start <- end + 1 |
562 | 198x |
current_page <- current_page + 1 |
563 |
} |
|
564 | 88x |
ret |
565 |
} |
|
566 | ||
567 |
#' Find column indices for vertical pagination |
|
568 |
#' |
|
569 |
#' @inheritParams pag_indices_inner |
|
570 |
#' @inheritParams open_font_dev |
|
571 |
#' @param obj (`ANY`)\cr object to be paginated. Must have a [matrix_form()] method. |
|
572 |
#' @param cpp (`numeric(1)`)\cr number of characters per page (width). |
|
573 |
#' @param colwidths (`numeric`)\cr vector of column widths (in characters) for use in vertical pagination. |
|
574 |
#' @param rep_cols (`numeric(1)`)\cr number of *columns* (not including row labels) to be repeated on every page. |
|
575 |
#' Defaults to 0. |
|
576 |
#' |
|
577 |
#' @return A `list` partitioning the vector of column indices into subsets for 1 or more horizontally paginated pages. |
|
578 |
#' |
|
579 |
#' @examples |
|
580 |
#' mf <- basic_matrix_form(df = mtcars) |
|
581 |
#' colpaginds <- vert_pag_indices(mf, fontspec = font_spec()) |
|
582 |
#' lapply(colpaginds, function(j) mtcars[, j, drop = FALSE]) |
|
583 |
#' |
|
584 |
#' @export |
|
585 |
vert_pag_indices <- function(obj, |
|
586 |
cpp = 40, |
|
587 |
colwidths = NULL, |
|
588 |
verbose = FALSE, |
|
589 |
rep_cols = 0L, |
|
590 |
fontspec, |
|
591 |
nosplitin = character()) { |
|
592 | 45x |
if (is.list(nosplitin)) { |
593 | ! |
nosplitin <- nosplitin[["cols"]] |
594 |
} |
|
595 | 45x |
mf <- matrix_form(obj, indent_rownames = TRUE, fontspec = fontspec) |
596 | 45x |
clwds <- colwidths %||% propose_column_widths(mf, fontspec = fontspec) |
597 | 45x |
if (is.null(mf_cinfo(mf))) { ## like always, ugh. |
598 | ! |
mf <- mpf_infer_cinfo(mf, colwidths = clwds, rep_cols = rep_cols, fontspec = fontspec) |
599 |
} |
|
600 | ||
601 | 45x |
num_rep_cols(mf) <- rep_cols |
602 | ||
603 | 45x |
has_rlabs <- mf_has_rlabels(mf) |
604 | 45x |
rlabs_flag <- as.integer(has_rlabs) |
605 | 45x |
rlab_extent <- if (has_rlabs) clwds[1] else 0L |
606 | ||
607 |
# rep_extent <- pdf$par_extent[nrow(pdf)] |
|
608 | 45x |
rcpp <- cpp - table_inset(mf) - rlab_extent # rep_extent - table_inset(mf) - rlab_extent |
609 | 45x |
if (verbose) { |
610 | 14x |
message( |
611 | 14x |
"Adjusted characters per page: ", rcpp, |
612 | 14x |
" [original: ", cpp, |
613 | 14x |
", table inset: ", table_inset(mf), if (has_rlabs) paste0(", row labels: ", clwds[1]), |
614 |
"]" |
|
615 |
) |
|
616 |
} |
|
617 | 45x |
res <- pag_indices_inner(mf_cinfo(mf), |
618 | 45x |
rlpp = rcpp, lpp_or_cpp = cpp, context_lpp_or_cpp = cpp - rcpp, |
619 |
# cpp - sum(clwds[seq_len(rep_cols)]), |
|
620 | 45x |
verbose = verbose, |
621 | 45x |
min_siblings = 1, |
622 | 45x |
nosplitin = nosplitin, |
623 | 45x |
row = FALSE, |
624 | 45x |
col_gap = mf_colgap(mf), |
625 | 45x |
has_rowlabels = mf_has_rlabels(mf) |
626 |
) |
|
627 | 44x |
res |
628 |
} |
|
629 | ||
630 |
mpf_infer_cinfo <- function(mf, colwidths = NULL, rep_cols = num_rep_cols(mf), fontspec, colpaths = NULL) { |
|
631 | 55x |
if (!is.null(mf_cinfo(mf))) { |
632 | 5x |
return(mf_update_cinfo(mf, colwidths = colwidths)) |
633 |
} |
|
634 | 50x |
new_dev <- open_font_dev(fontspec) |
635 | 50x |
if (new_dev) { |
636 | 50x |
on.exit(close_font_dev()) |
637 |
} |
|
638 | 50x |
if (!is(rep_cols, "numeric") || is.na(rep_cols) || rep_cols < 0) { |
639 | ! |
stop("got invalid number of columns to be repeated: ", rep_cols) |
640 |
} |
|
641 | 50x |
clwds <- (colwidths %||% mf_col_widths(mf)) %||% propose_column_widths(mf, fontspec = fontspec) |
642 | 50x |
has_rlabs <- mf_has_rlabels(mf) |
643 | 50x |
rlabs_flag <- as.integer(has_rlabs) |
644 | 50x |
rlab_extent <- if (has_rlabs) clwds[1] else 0L |
645 | 50x |
sqstart <- rlabs_flag + 1L # rep_cols + 1L |
646 | ||
647 | 50x |
pdfrows <- lapply( |
648 | 50x |
(sqstart):ncol(mf$strings), |
649 | 50x |
function(i) { |
650 | 292x |
rownum <- i - rlabs_flag |
651 | 292x |
rep_inds <- seq_len(rep_cols)[seq_len(rep_cols) < rownum] |
652 | 292x |
rep_extent_i <- sum( |
653 | 292x |
0L, |
654 | 292x |
clwds[rlabs_flag + rep_inds] |
655 | 292x |
) ## colwidths |
656 | 292x |
pagdfrow( |
657 | 292x |
row = NA, |
658 | 292x |
nm = rownum, |
659 | 292x |
lab = rownum, |
660 | 292x |
rnum = rownum, |
661 | 292x |
pth = NA, |
662 | 292x |
extent = clwds[i], |
663 | 292x |
repext = rep_extent_i, # sum(clwds[rep_cols]) + mf$col_gap * max(0, (length(rep_cols) - 1)), |
664 | 292x |
repind = rep_inds, # rep_cols, |
665 | 292x |
rclass = "stuff", |
666 | 292x |
sibpos = 1 - 1, |
667 | 292x |
nsibs = 1 - 1, |
668 | 292x |
fontspec = fontspec |
669 |
) |
|
670 |
} |
|
671 |
) |
|
672 | 50x |
pdf <- do.call(rbind, pdfrows) |
673 | ||
674 | 50x |
refdf <- mf_fnote_df(mf) |
675 | 50x |
pdf <- splice_fnote_info_in(pdf, refdf, row = FALSE) |
676 | 50x |
if (!is.null(colpaths)) { |
677 | ! |
if (length(colpaths) != NROW(pdf)) { |
678 |
## nocov start |
|
679 |
stop( |
|
680 |
"Got non-null colpaths with length not equal to number of columns (", |
|
681 |
length(colpaths), |
|
682 |
"!=", |
|
683 |
NROW(pdf), |
|
684 |
") during MatrixPrintForm construction. Please contact the maintainers." |
|
685 |
) |
|
686 |
## nocov end |
|
687 |
} |
|
688 | ! |
pdf[["path"]] <- colpaths |
689 |
} |
|
690 | 50x |
mf_cinfo(mf) <- pdf |
691 | 50x |
mf |
692 |
} |
|
693 | ||
694 |
#' Basic/spoof pagination info data frame |
|
695 |
#' |
|
696 |
#' Returns a minimal pagination info `data.frame` (with no info on siblings, footnotes, etc.). |
|
697 |
#' |
|
698 |
#' @inheritParams test_matrix_form |
|
699 |
#' @inheritParams open_font_dev |
|
700 |
#' @param rnames (`character`)\cr vector of row names. |
|
701 |
#' @param labs (`character`)\cr vector of row labels. Defaults to `rnames`. |
|
702 |
#' @param rnums (`integer`)\cr vector of row numbers. Defaults to `seq_along(rnames)`. |
|
703 |
#' @param extents (`integer`)\cr number of lines each row requires to print. Defaults to 1 for all rows. |
|
704 |
#' @param rclass (`character`)\cr class(es) for the rows. Defaults to `"DataRow"`. |
|
705 |
#' @param paths (`list`)\cr list of paths to the rows. Defaults to `lapply(rnames, function(x) c(parent_path, x))`. |
|
706 |
#' |
|
707 |
#' @return A `data.frame` suitable for use in both the `MatrixPrintForm` constructor and the pagination machinery. |
|
708 |
#' |
|
709 |
#' @examples |
|
710 |
#' basic_pagdf(c("hi", "there")) |
|
711 |
#' |
|
712 |
#' @export |
|
713 |
basic_pagdf <- function(rnames, |
|
714 |
labs = rnames, |
|
715 |
rnums = seq_along(rnames), |
|
716 |
extents = 1L, |
|
717 |
rclass = "DataRow", |
|
718 |
parent_path = NULL, |
|
719 |
paths = lapply(rnames, function(x) c(parent_path, x)), |
|
720 |
fontspec = font_spec()) { |
|
721 | 49x |
rws <- mapply(pagdfrow, |
722 | 49x |
nm = rnames, lab = labs, extent = extents, |
723 | 49x |
rclass = rclass, rnum = rnums, pth = paths, |
724 | 49x |
MoreArgs = list(fontspec = fontspec), |
725 | 49x |
SIMPLIFY = FALSE, nsibs = 1, sibpos = 1 |
726 |
) |
|
727 | 49x |
res <- do.call(rbind.data.frame, rws) |
728 | 49x |
res$n_siblings <- nrow(res) |
729 | 49x |
res$pos_in_siblings <- seq_along(res$n_siblings) |
730 | ||
731 | 49x |
if (!all(rclass == "DataRow")) { |
732 |
# These things are used in the simple case of a split, hence having labels. |
|
733 |
# To improve and extend to other cases |
|
734 | 4x |
res$pos_in_siblings <- NA |
735 | 4x |
res$pos_in_siblings[rclass == "DataRow"] <- 1 |
736 | 4x |
res$par_extent[rclass == "DataRow"] <- 1 # the rest is 0 |
737 | 4x |
res$n_siblings <- res$pos_in_siblings |
738 | 4x |
res$reprint_inds[which(rclass == "DataRow")] <- res$abs_rownumber[which(rclass == "DataRow") - 1] |
739 |
} |
|
740 | 49x |
res |
741 |
} |
|
742 | ||
743 |
## write paginate() which operates **solely** on a MatrixPrintForm obj |
|
744 | ||
745 |
page_size_spec <- function(lpp, cpp, max_width, |
|
746 |
font_family, |
|
747 |
font_size, |
|
748 |
lineheight, |
|
749 |
fontspec = font_spec( |
|
750 |
font_family = font_family, |
|
751 |
font_size = font_size, |
|
752 |
lineheight = lineheight |
|
753 |
)) { |
|
754 | 50x |
structure(list( |
755 | 50x |
lpp = lpp, |
756 | 50x |
cpp = cpp, |
757 | 50x |
max_width = max_width, |
758 | 50x |
font_spec = fontspec |
759 | 50x |
), class = "page_size_spec") |
760 |
} |
|
761 | ||
762 |
get_font_spec <- function(obj) { |
|
763 | 48x |
if (!is(obj, "page_size_spec")) { |
764 | ! |
stop("get_font_spec is only currently defined for page_size_spec objects") |
765 |
} |
|
766 | 48x |
obj$font_spec |
767 |
} |
|
768 | ||
769 | 100x |
non_null_na <- function(x) !is.null(x) && is.na(x) |
770 | ||
771 |
calc_lcpp <- function(page_type = NULL, |
|
772 |
landscape = FALSE, |
|
773 |
pg_width = page_dim(page_type)[if (landscape) 2 else 1], |
|
774 |
pg_height = page_dim(page_type)[if (landscape) 1 else 2], |
|
775 |
fontspec = font_spec(), |
|
776 |
## font_family = "Courier", |
|
777 |
## font_size = 8, # grid parameters |
|
778 |
cpp = NA_integer_, |
|
779 |
lpp = NA_integer_, |
|
780 |
tf_wrap = TRUE, |
|
781 |
max_width = NULL, |
|
782 |
## lineheight = 1, |
|
783 |
margins = c(bottom = .5, left = .75, top = .5, right = .75), |
|
784 |
colwidths, |
|
785 |
col_gap, |
|
786 |
inset) { |
|
787 | 50x |
pg_lcpp <- page_lcpp( |
788 | 50x |
page_type = page_type, |
789 | 50x |
landscape = landscape, |
790 |
## font_family = font_family, |
|
791 |
## font_size = font_size, |
|
792 |
## lineheight = lineheight, |
|
793 | 50x |
fontspec = fontspec, |
794 | 50x |
margins = margins, |
795 | 50x |
pg_width = pg_width, |
796 | 50x |
pg_height = pg_height |
797 |
) |
|
798 | ||
799 | 50x |
if (non_null_na(lpp)) { |
800 | 29x |
lpp <- pg_lcpp$lpp |
801 |
} |
|
802 | 50x |
if (non_null_na(cpp)) { |
803 | 22x |
cpp <- pg_lcpp$cpp |
804 |
} |
|
805 | 50x |
stopifnot(!is.na(cpp)) |
806 | ||
807 | 50x |
max_width <- .handle_max_width(tf_wrap, max_width, cpp, colwidths, col_gap, inset) |
808 | ||
809 | 50x |
page_size_spec( |
810 | 50x |
lpp = lpp, cpp = cpp, max_width = max_width, |
811 |
## font_family = font_family, |
|
812 |
## font_size = font_size, |
|
813 |
## lineheight = lineheight |
|
814 | 50x |
fontspec = fontspec |
815 |
) |
|
816 |
} |
|
817 | ||
818 |
calc_rlpp <- function(pg_size_spec, mf, colwidths, tf_wrap, verbose) { |
|
819 | 48x |
lpp <- pg_size_spec$lpp |
820 | 48x |
max_width <- pg_size_spec$max_width |
821 | 48x |
fontspec <- get_font_spec(pg_size_spec) |
822 | 48x |
dh <- divider_height(mf) |
823 | 48x |
if (any(nzchar(all_titles(mf)))) { |
824 |
## +1 is for blank line between subtitles and divider |
|
825 |
## dh is for divider line **between subtitles and column labels** |
|
826 |
## other divider line is accounted for in cinfo_lines |
|
827 | 24x |
if (!tf_wrap) { |
828 | 12x |
tlines <- length(all_titles(mf)) |
829 |
} else { |
|
830 | 12x |
tlines <- sum(nlines(all_titles(mf), colwidths = colwidths, max_width = max_width, fontspec = fontspec)) |
831 |
} |
|
832 | 24x |
tlines <- tlines + dh + 1L |
833 |
} else { |
|
834 | 24x |
tlines <- 0 |
835 |
} |
|
836 | ||
837 |
## dh for divider line between column labels and table body |
|
838 | 48x |
cinfo_lines <- mf_nlheader(mf) + dh |
839 | ||
840 | 48x |
if (verbose) { |
841 | 17x |
message( |
842 | 17x |
"Determining lines required for header content: ", |
843 | 17x |
tlines, " title and ", cinfo_lines, " table header lines" |
844 |
) |
|
845 |
} |
|
846 | ||
847 | 48x |
refdf <- mf_fnote_df(mf) |
848 | 48x |
cfn_df <- refdf[is.na(refdf$row) & !is.na(refdf$col), ] |
849 | ||
850 | 48x |
flines <- 0L |
851 | 48x |
mnfoot <- main_footer(mf) |
852 | 48x |
havemn <- length(mnfoot) && any(nzchar(mnfoot)) |
853 | 48x |
if (havemn) { |
854 | 25x |
flines <- nlines( |
855 | 25x |
mnfoot, |
856 | 25x |
colwidths = colwidths, |
857 | 25x |
max_width = max_width - table_inset(mf), |
858 | 25x |
fontspec = fontspec |
859 |
) |
|
860 |
} |
|
861 | 48x |
prfoot <- prov_footer(mf) |
862 | 48x |
if (length(prfoot) && any(nzchar(prfoot))) { |
863 | 31x |
flines <- flines + nlines(prov_footer(mf), colwidths = colwidths, max_width = max_width, fontspec = fontspec) |
864 | 31x |
if (havemn) { |
865 | 24x |
flines <- flines + 1L |
866 |
} ## space between main and prov footer. |
|
867 |
} |
|
868 |
## this time its for the divider between the footers and whatever is above them |
|
869 |
## (either table body or referential footnotes) |
|
870 | 48x |
if (flines > 0) { |
871 | 32x |
flines <- flines + dh + 1L |
872 |
} |
|
873 |
## this time its for the divider between the referential footnotes and |
|
874 |
## the table body IFF we have any, otherwise that divider+blanks pace doesn't get drawn |
|
875 | 48x |
if (NROW(cfn_df) > 0) { |
876 | ! |
cinfo_lines <- cinfo_lines + sum(cfn_df$nlines) |
877 | ! |
flines <- flines + dh + 1L |
878 |
} |
|
879 | ||
880 | 48x |
if (verbose) { |
881 | 17x |
message( |
882 | 17x |
"Determining lines required for footer content", |
883 | 17x |
if (NROW(cfn_df) > 0) " [column fnotes present]", |
884 | 17x |
": ", flines, " lines" |
885 |
) |
|
886 |
} |
|
887 | ||
888 | 48x |
ret <- lpp - flines - tlines - cinfo_lines |
889 | ||
890 | 48x |
if (verbose) { |
891 | 17x |
message("Lines per page available for tables rows: ", ret, " (original: ", lpp, ")") |
892 |
} |
|
893 | 48x |
ret |
894 |
} |
|
895 | ||
896 |
## this is ok to be unchanged because by this point |
|
897 |
## all of these are in terms of space widths |
|
898 |
calc_rcpp <- function(pg_size_spec, mf, colwidths) { |
|
899 | ! |
cpp <- pg_size_spec$cpp |
900 | ||
901 | ! |
cpp - table_inset(mf) - colwidths[1] - mf_colgap(mf) |
902 |
} |
|
903 | ||
904 |
splice_idx_lists <- function(lsts) { |
|
905 | ! |
list( |
906 | ! |
pag_row_indices = do.call(c, lapply(lsts, function(xi) xi$pag_row_indices)), |
907 | ! |
pag_col_indices = do.call(c, lapply(lsts, function(yi) yi$pag_col_indices)) |
908 |
) |
|
909 |
} |
|
910 | ||
911 |
#' Paginate a table-like object for rendering |
|
912 |
#' |
|
913 |
#' These functions perform or diagnose bi-directional pagination on an object. |
|
914 |
#' |
|
915 |
#' `paginate_indices` renders `obj` into a `MatrixPrintForm` (MPF), then uses that representation to |
|
916 |
#' calculate the rows and columns of `obj` corresponding to each page of the pagination of `obj`, but |
|
917 |
#' simply returns these indices rather than paginating `obj` itself (see Details for an important caveat). |
|
918 |
#' |
|
919 |
#' `paginate_to_mpfs` renders `obj` into its MPF intermediate representation, then paginates that MPF into |
|
920 |
#' component MPFs each corresponding to an individual page and returns those in a `list`. |
|
921 |
#' |
|
922 |
#' `diagnose_pagination` attempts pagination via `paginate_to_mpfs`, then returns diagnostic information |
|
923 |
#' which explains why page breaks were positioned where they were, or alternatively why no valid pagination |
|
924 |
#' could be found. |
|
925 |
#' |
|
926 |
#' @details |
|
927 |
#' All three of these functions generally support all classes which have a corresponding [matrix_form()] |
|
928 |
#' method which returns a valid `MatrixPrintForm` object (including `MatrixPrintForm` objects themselves). |
|
929 |
#' |
|
930 |
#' `paginate_indices` is directly called by `paginate_to_mpfs` (and thus `diagnose_pagination`). For most |
|
931 |
#' classes, and most tables represented by supported classes, calling `paginate_to_mpfs` is equivalent to a |
|
932 |
#' manual `paginate_indices -> subset obj into pages -> matrix_form` workflow. |
|
933 |
#' |
|
934 |
#' The exception to this equivalence is objects which support "forced pagination", or pagination logic which |
|
935 |
#' is built into the object itself rather than being a function of space on a page. Forced pagination |
|
936 |
#' generally involves the creation of, e.g., page-specific titles which apply to these forced paginations. |
|
937 |
#' `paginate_to_mpfs` and `diagnose_pagination` support forced pagination by automatically calling the |
|
938 |
#' [do_forced_paginate()] generic on the object and then paginating each object returned by that generic |
|
939 |
#' separately. The assumption here, then, is that page-specific titles and such are handled by the class' |
|
940 |
#' [do_forced_paginate()] method. |
|
941 |
#' |
|
942 |
#' `paginate_indices`, on the other hand, *does not support forced pagination*, because it returns only a |
|
943 |
#' set of indices for row and column subsetting for each page, and thus cannot retain any changes, e.g., |
|
944 |
#' to titles, done within [do_forced_paginate()]. `paginate_indices` does call [do_forced_paginate()], but |
|
945 |
#' instead of continuing it throws an error in the case that the result is larger than a single "page". |
|
946 |
#' |
|
947 |
#' @inheritParams vert_pag_indices |
|
948 |
#' @inheritParams pag_indices_inner |
|
949 |
#' @inheritParams page_lcpp |
|
950 |
#' @inheritParams toString |
|
951 |
#' @inheritParams propose_column_widths |
|
952 |
#' @param lpp (`numeric(1)` or `NULL`)\cr lines per page. If `NA` (the default), this is calculated automatically |
|
953 |
#' based on the specified page size). `NULL` indicates no vertical pagination should occur. |
|
954 |
#' @param cpp (`numeric(1)` or `NULL`)\cr width (in characters) per page. If `NA` (the default), this is calculated |
|
955 |
#' automatically based on the specified page size). `NULL` indicates no horizontal pagination should occur. |
|
956 |
#' @param pg_size_spec (`page_size_spec`)\cr. a pre-calculated page size specification. Typically this is not set by |
|
957 |
#' end users. |
|
958 |
#' @param col_gap (`numeric(1)`)\cr The number of spaces to be placed between columns |
|
959 |
#' in the rendered table (and assumed for horizontal pagination). |
|
960 |
#' @param page_num (`string`)\cr placeholder string for page numbers. See [default_page_number] for more |
|
961 |
#' information. Defaults to `NULL`. |
|
962 |
#' |
|
963 |
#' @return |
|
964 |
#' * `paginate_indices` returns a `list` with two elements of the same length: `pag_row_indices` and `pag_col_indices`. |
|
965 |
#' * `paginate_to_mpfs` returns a `list` of `MatrixPrintForm` objects representing each individual page after |
|
966 |
#' pagination (including forced pagination if necessary). |
|
967 |
#' |
|
968 |
#' @examples |
|
969 |
#' mpf <- basic_matrix_form(mtcars) |
|
970 |
#' |
|
971 |
#' paginate_indices(mpf, pg_width = 5, pg_height = 3) |
|
972 |
#' |
|
973 |
#' paginate_to_mpfs(mpf, pg_width = 5, pg_height = 3) |
|
974 |
#' |
|
975 |
#' @aliases paginate pagination |
|
976 |
#' @export |
|
977 |
paginate_indices <- function(obj, |
|
978 |
page_type = "letter", |
|
979 |
font_family = "Courier", |
|
980 |
font_size = 8, |
|
981 |
lineheight = 1, |
|
982 |
landscape = FALSE, |
|
983 |
pg_width = NULL, |
|
984 |
pg_height = NULL, |
|
985 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
986 |
lpp = NA_integer_, |
|
987 |
cpp = NA_integer_, |
|
988 |
min_siblings = 2, |
|
989 |
nosplitin = list( |
|
990 |
rows = character(), |
|
991 |
cols = character() |
|
992 |
), |
|
993 |
colwidths = NULL, |
|
994 |
tf_wrap = FALSE, |
|
995 |
max_width = NULL, |
|
996 |
indent_size = 2, |
|
997 |
pg_size_spec = NULL, |
|
998 |
rep_cols = num_rep_cols(obj), |
|
999 |
col_gap = 3, |
|
1000 |
fontspec = font_spec(font_family, font_size, lineheight), |
|
1001 |
verbose = FALSE) { |
|
1002 |
## this preserves backwards compatibility |
|
1003 |
## could start deprecation cycle of char input |
|
1004 | 50x |
if (is.character(nosplitin)) { |
1005 | 47x |
nosplitin <- list( |
1006 | 47x |
rows = nosplitin, |
1007 | 47x |
cols = character() |
1008 |
) |
|
1009 |
} |
|
1010 | 50x |
newdev <- open_font_dev(fontspec) |
1011 | 50x |
if (newdev) { |
1012 | 3x |
on.exit(close_font_dev()) |
1013 |
} |
|
1014 |
## this MUST alsways return a list, inluding list(obj) when |
|
1015 |
## no forced pagination is needed! otherwise stuff breaks for things |
|
1016 |
## based on s3 classes that are lists underneath!!! |
|
1017 | 50x |
fpags <- do_forced_paginate(obj) |
1018 |
## if we have more than one forced "page", |
|
1019 |
## paginate each of them individually and return the result. |
|
1020 |
## forced pagination is ***currently*** only vertical, so |
|
1021 |
## we don't have to worry about divying up colwidths here, |
|
1022 |
## but we will if we ever allow force_paginate to do horiz |
|
1023 |
## pagination. |
|
1024 | 50x |
if (length(fpags) > 1) { |
1025 | 1x |
stop( |
1026 | 1x |
"forced pagination is required for this object (class: ", class(obj)[1], |
1027 | 1x |
") this is not supported in paginate_indices. Use paginate_to_mpfs or call ", |
1028 | 1x |
"do_forced_paginate on your object and paginate each returned section separately." |
1029 |
) |
|
1030 |
} |
|
1031 | ||
1032 |
## order is annoying here, since we won't actually need the mpf if |
|
1033 |
## we run into forced pagination, but life is short and this should work fine. |
|
1034 | 49x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size, fontspec = fontspec) |
1035 | 49x |
if (is.null(colwidths)) { |
1036 | 2x |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf, fontspec = fontspec) |
1037 |
} else { |
|
1038 | 47x |
mf_col_widths(mpf) <- colwidths |
1039 |
} |
|
1040 | ||
1041 | 49x |
mf_colgap(mpf) <- col_gap |
1042 | 49x |
if (!is.null(rep_cols) && rep_cols != num_rep_cols(obj)) { |
1043 | 3x |
num_rep_cols(mpf) <- rep_cols |
1044 |
} |
|
1045 | 49x |
if (NROW(mf_cinfo(mpf)) == 0) { |
1046 | ! |
mpf <- mpf_infer_cinfo(mpf, colwidths, rep_cols, fontspec = fontspec) |
1047 |
} |
|
1048 | ||
1049 | 49x |
if (is.null(pg_size_spec)) { |
1050 | 2x |
pg_size_spec <- calc_lcpp( |
1051 | 2x |
page_type = page_type, |
1052 |
## font_family = font_family, |
|
1053 |
## font_size = font_size, |
|
1054 |
## lineheight = lineheight, |
|
1055 | 2x |
fontspec = fontspec, |
1056 | 2x |
landscape = landscape, |
1057 | 2x |
pg_width = pg_width, |
1058 | 2x |
pg_height = pg_height, |
1059 | 2x |
margins = margins, |
1060 | 2x |
lpp = lpp, |
1061 | 2x |
cpp = cpp, |
1062 | 2x |
tf_wrap = tf_wrap, |
1063 | 2x |
max_width = max_width, |
1064 | 2x |
colwidths = colwidths, |
1065 | 2x |
inset = table_inset(mpf), |
1066 | 2x |
col_gap = col_gap |
1067 |
) |
|
1068 |
} |
|
1069 | ||
1070 |
## we can't support forced pagination in paginate_indices because |
|
1071 |
## forced pagination is generally going to set page titles, which |
|
1072 |
## we can't preserve when just returning lists of indices. |
|
1073 |
## Instead we make a hard assumption here that any forced pagination |
|
1074 |
## has already occurred. |
|
1075 | ||
1076 |
## this wraps the cell contents AND shoves referential footnote |
|
1077 |
## info into mf_rinfo(mpf) |
|
1078 | 49x |
mpf <- do_cell_fnotes_wrap(mpf, colwidths, max_width, tf_wrap = tf_wrap, fontspec = fontspec) |
1079 | ||
1080 |
# rlistings note: if there is a wrapping in a keycol, it is not calculated correctly |
|
1081 |
# in the above call, so we need to keep this information in mf_rinfo |
|
1082 |
# and use it here. |
|
1083 | 49x |
mfri <- mf_rinfo(mpf) |
1084 | 49x |
keycols <- .get_keycols_from_listing(obj) |
1085 | 49x |
if (NROW(mfri) > 1 && .is_listing_mf(mpf) && length(keycols) > 0) { |
1086 |
# Lets determine the groupings created by keycols |
|
1087 | 12x |
keycols_grouping_df <- NULL |
1088 | 12x |
for (i in seq_along(keycols)) { |
1089 | 24x |
kcol <- keycols[i] |
1090 | 24x |
if (is(obj, "MatrixPrintForm")) { |
1091 |
# This makes the function work also in the case we have only matrix form (mainly for testing purposes) |
|
1092 | 24x |
kcolvec <- mf_strings(obj)[, mf_strings(obj)[1, , drop = TRUE] == kcol][-1] |
1093 | 24x |
while (any(kcolvec == "")) { |
1094 | 284x |
kcolvec[which(kcolvec == "")] <- kcolvec[which(kcolvec == "") - 1] |
1095 |
} |
|
1096 |
} else { |
|
1097 | ! |
kcolvec <- obj[[kcol]] |
1098 | ! |
kcolvec <- vapply(kcolvec, format_value, "", format = obj_format(kcolvec), na_str = obj_na_str(kcolvec)) |
1099 |
} |
|
1100 | 24x |
groupings <- as.numeric(factor(kcolvec, levels = unique(kcolvec))) |
1101 | 24x |
where_they_start <- which(c(1, diff(groupings)) > 0) |
1102 | 24x |
keycols_grouping_df <- cbind( |
1103 | 24x |
keycols_grouping_df, |
1104 | 24x |
where_they_start[groupings] |
1105 | 24x |
) # take the groupings |
1106 |
} |
|
1107 | ||
1108 |
# Creating the real self_extend for mf_rinfo (if the line is chosen for pagination start) |
|
1109 | 12x |
self_extent_df <- apply(keycols_grouping_df, 2, function(x) mfri$self_extent[x]) |
1110 | 12x |
mf_rinfo(mpf) <- cbind(mfri, "self_extent_page_break" = apply(self_extent_df, 1, max)) |
1111 |
} |
|
1112 | ||
1113 | 49x |
if (is.null(pg_size_spec$lpp)) { |
1114 | 1x |
pag_row_indices <- list(seq_len(mf_nrow(mpf))) |
1115 |
} else { |
|
1116 | 48x |
rlpp <- calc_rlpp( |
1117 | 48x |
pg_size_spec, mpf, |
1118 | 48x |
colwidths = colwidths, |
1119 | 48x |
tf_wrap = tf_wrap, verbose = verbose |
1120 |
) |
|
1121 | 48x |
pag_row_indices <- pag_indices_inner( |
1122 | 48x |
pagdf = mf_rinfo(mpf), |
1123 | 48x |
rlpp = rlpp, |
1124 | 48x |
lpp_or_cpp = pg_size_spec$lpp, |
1125 | 48x |
context_lpp_or_cpp = pg_size_spec$lpp - rlpp, |
1126 | 48x |
verbose = verbose, |
1127 | 48x |
min_siblings = min_siblings, |
1128 | 48x |
nosplitin = nosplitin[["rows"]], |
1129 | 48x |
col_gap = col_gap, |
1130 | 48x |
has_rowlabels = mf_has_rlabels(mpf) |
1131 |
) |
|
1132 |
} |
|
1133 | ||
1134 | 44x |
if (is.null(pg_size_spec$cpp)) { |
1135 | 1x |
pag_col_indices <- list(seq_len(mf_ncol(mpf))) |
1136 |
} else { |
|
1137 | 43x |
pag_col_indices <- vert_pag_indices( |
1138 | 43x |
mpf, |
1139 | 43x |
cpp = pg_size_spec$cpp, colwidths = colwidths, |
1140 | 43x |
rep_cols = rep_cols, fontspec = fontspec, |
1141 | 43x |
nosplitin = nosplitin[["cols"]], |
1142 | 43x |
verbose = verbose |
1143 |
) |
|
1144 |
} |
|
1145 | ||
1146 | 43x |
list(pag_row_indices = pag_row_indices, pag_col_indices = pag_col_indices) |
1147 |
} |
|
1148 | ||
1149 | 47x |
setGeneric("has_page_title", function(obj) standardGeneric("has_page_title")) |
1150 | ||
1151 | 47x |
setMethod("has_page_title", "ANY", function(obj) length(page_titles(obj)) > 0) |
1152 | ||
1153 |
#' @rdname paginate_indices |
|
1154 |
#' @export |
|
1155 |
paginate_to_mpfs <- function(obj, |
|
1156 |
page_type = "letter", |
|
1157 |
font_family = "Courier", |
|
1158 |
font_size = 8, |
|
1159 |
lineheight = 1, |
|
1160 |
landscape = FALSE, |
|
1161 |
pg_width = NULL, |
|
1162 |
pg_height = NULL, |
|
1163 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
1164 |
lpp = NA_integer_, |
|
1165 |
cpp = NA_integer_, |
|
1166 |
min_siblings = 2, |
|
1167 |
nosplitin = character(), |
|
1168 |
colwidths = NULL, |
|
1169 |
tf_wrap = FALSE, |
|
1170 |
max_width = NULL, |
|
1171 |
indent_size = 2, |
|
1172 |
pg_size_spec = NULL, |
|
1173 |
page_num = default_page_number(), |
|
1174 |
rep_cols = NULL, |
|
1175 |
# rep_cols = num_rep_cols(obj), |
|
1176 |
# col_gap = 3, # this could be change in default - breaking change |
|
1177 |
col_gap = 3, |
|
1178 |
fontspec = font_spec(font_family, font_size, lineheight), |
|
1179 |
verbose = FALSE) { |
|
1180 | 57x |
newdev <- open_font_dev(fontspec) |
1181 | 57x |
if (newdev) { |
1182 | 32x |
on.exit(close_font_dev()) |
1183 |
} |
|
1184 | ||
1185 | 57x |
if (isTRUE(page_num)) { |
1186 | 1x |
page_num <- "page {i}/{n}" |
1187 |
} |
|
1188 | 57x |
checkmate::assert_string(page_num, null.ok = TRUE, min.chars = 1) |
1189 | ||
1190 |
# We can return a list of paginated tables and listings |
|
1191 | 57x |
if (.is_list_of_tables_or_listings(obj)) { |
1192 | 8x |
cur_call <- match.call(expand.dots = FALSE) |
1193 | 8x |
mpfs <- unlist( |
1194 | 8x |
lapply(obj, function(obj_i) { |
1195 | 15x |
cur_call[["obj"]] <- obj_i |
1196 | 15x |
eval(cur_call, envir = parent.frame(3L)) |
1197 |
}), |
|
1198 | 8x |
recursive = FALSE |
1199 |
) |
|
1200 | ||
1201 | 7x |
if (!is.null(page_num)) { |
1202 | 3x |
extracted_cpp <- max( |
1203 | 3x |
sapply(mpfs, function(mpf) { |
1204 | 12x |
pf <- prov_footer(mpf) |
1205 | 12x |
nchar(pf[length(pf)]) |
1206 |
}) |
|
1207 |
) |
|
1208 | 3x |
mpfs <- .modify_footer_for_page_nums(mpfs, page_num, extracted_cpp) |
1209 |
} |
|
1210 | ||
1211 | 7x |
return(mpfs) |
1212 |
} |
|
1213 | ||
1214 | 49x |
if (!is.null(page_num)) { |
1215 |
# Only adding a line for pagination -> lpp - 1 would have worked too |
|
1216 | 14x |
prov_footer(obj) <- c(prov_footer(obj), page_num) |
1217 |
} |
|
1218 | ||
1219 | 49x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size, fontspec = fontspec) |
1220 |
# For listings, keycols are mandatory rep_num_cols |
|
1221 | 49x |
if (is.null(rep_cols)) { |
1222 | 44x |
rep_cols <- num_rep_cols(obj) |
1223 |
} |
|
1224 | 49x |
num_rep_cols(mpf) <- rep_cols |
1225 | ||
1226 |
# Turning off min_siblings for listings |
|
1227 | 49x |
if (.is_listing_mf(mpf)) { |
1228 | 13x |
min_siblings <- 0 |
1229 |
} |
|
1230 | ||
1231 |
# Checking colwidths |
|
1232 | 49x |
if (is.null(colwidths)) { |
1233 | 33x |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf, fontspec = fontspec) |
1234 |
} else { |
|
1235 | 16x |
cur_ncol <- ncol(mpf) |
1236 | 16x |
if (!.is_listing_mf(mpf)) { |
1237 | 10x |
cur_ncol <- cur_ncol + as.numeric(mf_has_rlabels(mpf)) |
1238 |
} |
|
1239 | 16x |
if (length(colwidths) != cur_ncol) { |
1240 | 1x |
stop( |
1241 | 1x |
"non-null colwidths argument must have length ncol(x) (+ 1 if row labels are present and if it is a table) [", |
1242 | 1x |
cur_ncol, "], got length ", length(colwidths) |
1243 |
) |
|
1244 |
} |
|
1245 | 15x |
mf_col_widths(mpf) <- colwidths |
1246 |
} |
|
1247 | ||
1248 | 48x |
if (NROW(mf_cinfo(mpf)) == 0) { |
1249 | ! |
mpf <- mpf_infer_cinfo(mpf, colwidths, rep_cols, fontspec = fontspec) |
1250 |
} |
|
1251 | ||
1252 | 48x |
if (is.null(pg_size_spec)) { |
1253 | 46x |
pg_size_spec <- calc_lcpp( |
1254 | 46x |
page_type = page_type, |
1255 |
## font_family = font_family, |
|
1256 |
## font_size = font_size, |
|
1257 |
## lineheight = lineheight, |
|
1258 | 46x |
fontspec = fontspec, |
1259 | 46x |
landscape = landscape, |
1260 | 46x |
pg_width = pg_width, |
1261 | 46x |
pg_height = pg_height, |
1262 | 46x |
margins = margins, |
1263 | 46x |
lpp = lpp, |
1264 | 46x |
cpp = cpp, |
1265 | 46x |
tf_wrap = tf_wrap, |
1266 | 46x |
max_width = max_width, |
1267 | 46x |
colwidths = colwidths, |
1268 | 46x |
inset = table_inset(mpf), |
1269 | 46x |
col_gap = col_gap |
1270 |
) |
|
1271 |
} |
|
1272 |
## this MUST always return a list, including list(obj) when |
|
1273 |
## no forced pagination is needed! otherwise stuff breaks for things |
|
1274 |
## based on s3 classes that are lists underneath!!! |
|
1275 | 48x |
fpags <- do_forced_paginate(obj) |
1276 | ||
1277 |
## if we have more than one forced "page", |
|
1278 |
## paginate each of them individually and return the result. |
|
1279 |
## forced pagination is ***currently*** only vertical, so |
|
1280 |
## we don't have to worry about divying up colwidths here, |
|
1281 |
## but we will if we ever allow force_paginate to do horiz |
|
1282 |
## pagination. |
|
1283 | 48x |
if (length(fpags) > 1) { |
1284 |
# Correction for case we are entering here (page_by) |
|
1285 | 1x |
if (!is.null(page_num)) { |
1286 | ! |
prov_footer(obj) <- head(prov_footer(obj), -1) |
1287 | ! |
fpags <- lapply(fpags, function(x) { |
1288 | ! |
prov_footer(x) <- head(prov_footer(x), -1) |
1289 | ! |
x |
1290 |
}) |
|
1291 |
} |
|
1292 |
# XXX to merge with listings and avoid recursive (after PR #296) |
|
1293 | 1x |
deep_pag <- paginate_to_mpfs( # what about the other parameters? |
1294 | 1x |
fpags, |
1295 | 1x |
pg_size_spec = pg_size_spec, |
1296 | 1x |
colwidths = colwidths, |
1297 | 1x |
min_siblings = min_siblings, |
1298 | 1x |
nosplitin = nosplitin, |
1299 | 1x |
fontspec = fontspec, |
1300 | 1x |
verbose = verbose, |
1301 | 1x |
rep_cols = rep_cols, |
1302 | 1x |
page_num = page_num |
1303 |
) |
|
1304 | 1x |
return(deep_pag) |
1305 | 47x |
} else if (has_page_title(fpags[[1]])) { |
1306 | ! |
obj <- fpags[[1]] |
1307 |
} |
|
1308 | ||
1309 |
## we run into forced pagination, but life is short and this should work fine. |
|
1310 | 47x |
mpf <- matrix_form(obj, TRUE, TRUE, indent_size = indent_size, fontspec = fontspec) |
1311 | 47x |
num_rep_cols(mpf) <- rep_cols |
1312 | 47x |
if (is.null(colwidths)) { |
1313 | ! |
colwidths <- mf_col_widths(mpf) %||% propose_column_widths(mpf, fontspec = fontspec) |
1314 |
} |
|
1315 | 47x |
mf_col_widths(mpf) <- colwidths |
1316 | 47x |
mf_colgap(mpf) <- col_gap |
1317 | ||
1318 | 47x |
page_indices <- paginate_indices( |
1319 | 47x |
obj = obj, |
1320 |
## page_type = page_type, |
|
1321 |
## font_family = font_family, |
|
1322 |
## font_size = font_size, |
|
1323 |
## lineheight = lineheight, |
|
1324 |
## landscape = landscape, |
|
1325 |
## pg_width = pg_width, |
|
1326 |
## pg_height = pg_height, |
|
1327 |
## margins = margins, |
|
1328 | 47x |
pg_size_spec = pg_size_spec, |
1329 |
## lpp = lpp, |
|
1330 |
## cpp = cpp, |
|
1331 | 47x |
min_siblings = min_siblings, |
1332 | 47x |
nosplitin = nosplitin, |
1333 | 47x |
colwidths = colwidths, |
1334 | 47x |
tf_wrap = tf_wrap, |
1335 |
## max_width = max_width, |
|
1336 | 47x |
rep_cols = rep_cols, |
1337 | 47x |
verbose = verbose, |
1338 | 47x |
col_gap = col_gap, |
1339 | 47x |
fontspec = fontspec |
1340 |
) |
|
1341 | ||
1342 | 43x |
pagmats <- lapply(page_indices$pag_row_indices, function(ii) { |
1343 | 89x |
mpf_subset_rows(mpf, ii, keycols = .get_keycols_from_listing(obj)) |
1344 |
}) |
|
1345 |
## these chunks now carry around their (correctly subset) col widths... |
|
1346 | 43x |
res <- lapply(pagmats, function(matii) { |
1347 | 89x |
lapply(page_indices$pag_col_indices, function(jj) { |
1348 | 220x |
mpf_subset_cols(matii, jj, keycols = .get_keycols_from_listing(obj)) |
1349 |
}) |
|
1350 |
}) |
|
1351 | ||
1352 | 43x |
res <- unlist(res, recursive = FALSE) |
1353 | ||
1354 |
# Adding page numbers if needed |
|
1355 | 43x |
if (!is.null(page_num)) { |
1356 | 14x |
res <- .modify_footer_for_page_nums( |
1357 | 14x |
mf_list = res, |
1358 | 14x |
page_num_format = page_num, |
1359 | 14x |
current_cpp = pg_size_spec$cpp |
1360 |
) |
|
1361 |
} |
|
1362 | ||
1363 | 42x |
res |
1364 |
} |
|
1365 | ||
1366 |
.modify_footer_for_page_nums <- function(mf_list, page_num_format, current_cpp) { |
|
1367 | 17x |
total_pages <- length(mf_list) |
1368 | 17x |
page_str <- gsub("\\{n\\}", total_pages, page_num_format) |
1369 | 17x |
page_nums <- vapply( |
1370 | 17x |
seq_len(total_pages), |
1371 | 17x |
function(x) { |
1372 | 135x |
gsub("\\{i\\}", x, page_str) |
1373 |
}, |
|
1374 | 17x |
FUN.VALUE = character(1) |
1375 |
) |
|
1376 | 17x |
page_footer <- sprintf(paste0("%", current_cpp, "s"), page_nums) |
1377 | 17x |
if (any(nchar(page_footer) > current_cpp)) { |
1378 | 1x |
stop("Page numbering string (page_num) is too wide to fit the desired page size width (cpp).") |
1379 |
} |
|
1380 | ||
1381 | 16x |
lapply(seq_along(mf_list), function(pg_i) { |
1382 | 69x |
prov_footer(mf_list[[pg_i]]) <- c(head(prov_footer(mf_list[[pg_i]]), -1), page_footer[pg_i]) |
1383 | 69x |
mf_list[[pg_i]] |
1384 |
}) |
|
1385 |
} |
|
1386 | ||
1387 |
# This works only with matrix_form objects |
|
1388 |
.is_listing_mf <- function(mf) { |
|
1389 | 1143x |
all(mf_rinfo(mf)$node_class == "listing_df") |
1390 |
} |
|
1391 | ||
1392 |
# Extended copy of get_keycols |
|
1393 |
.get_keycols_from_listing <- function(obj) { |
|
1394 | 88x |
if (is(obj, "listing_df")) { |
1395 | ! |
names(which(sapply(obj, is, class2 = "listing_keycol"))) |
1396 | 88x |
} else if (is(obj, "MatrixPrintForm") && .is_listing_mf(obj)) { |
1397 | 52x |
obj$listing_keycols |
1398 |
} else { |
|
1399 | 36x |
NULL # table case |
1400 |
} |
|
1401 |
} |
|
1402 | ||
1403 |
#' @importFrom utils capture.output |
|
1404 |
#' @details |
|
1405 |
#' `diagnose_pagination` attempts pagination and then, regardless of success or failure, returns diagnostic |
|
1406 |
#' information about pagination attempts (if any) after each row and column. |
|
1407 |
#' |
|
1408 |
#' The diagnostics data reflects the final time the pagination algorithm evaluated a page break at the |
|
1409 |
#' specified location, regardless of how many times the position was assessed in total. |
|
1410 |
#' |
|
1411 |
#' To get information about intermediate attempts, perform pagination with `verbose = TRUE` and inspect |
|
1412 |
#' the messages in order. |
|
1413 |
#' |
|
1414 |
#' @importFrom utils capture.output |
|
1415 |
#' |
|
1416 |
#' @return |
|
1417 |
#' * `diagnose_pagination` returns a `list` containing: |
|
1418 |
#' |
|
1419 |
#' \describe{ |
|
1420 |
#' \item{`lpp_diagnostics`}{Diagnostic information regarding lines per page.} |
|
1421 |
#' \item{`row_diagnostics`}{Basic information about rows, whether pagination was attempted |
|
1422 |
#' after each row, and the final result of such an attempt, if made.} |
|
1423 |
#' \item{`cpp_diagnostics`}{Diagnostic information regarding columns per page.} |
|
1424 |
#' \item{`col_diagnostics`}{Very basic information about leaf columns, whether pagination |
|
1425 |
#' was attempted after each leaf column, ad the final result of such attempts, if made.} |
|
1426 |
#' } |
|
1427 |
#' |
|
1428 |
#' @note |
|
1429 |
#' For `diagnose_pagination`, the column labels are not displayed in the `col_diagnostics` element |
|
1430 |
#' due to certain internal implementation details; rather the diagnostics are reported in terms of |
|
1431 |
#' absolute (leaf) column position. This is a known limitation, and may eventually be changed, but the |
|
1432 |
#' information remains useful as it is currently reported. |
|
1433 |
#' |
|
1434 |
#' `diagnose_pagination` is intended for interactive debugging use and *should not be programmed against*, |
|
1435 |
#' as the exact content and form of the verbose messages it captures and returns is subject to change. |
|
1436 |
#' |
|
1437 |
#' Because `diagnose_pagination` relies on `capture.output(type = "message")`, it cannot be used within the |
|
1438 |
#' `testthat` (and likely other) testing frameworks, and likely cannot be used within `knitr`/`rmarkdown` |
|
1439 |
#' contexts either, as this clashes with those systems' capture of messages. |
|
1440 |
#' |
|
1441 |
#' @examples |
|
1442 |
#' diagnose_pagination(mpf, pg_width = 5, pg_height = 3) |
|
1443 |
#' clws <- propose_column_widths(mpf) |
|
1444 |
#' clws[1] <- floor(clws[1] / 3) |
|
1445 |
#' dgnost <- diagnose_pagination(mpf, pg_width = 5, pg_height = 3, colwidths = clws) |
|
1446 |
#' try(diagnose_pagination(mpf, pg_width = 1)) # fails |
|
1447 |
#' |
|
1448 |
#' @rdname paginate_indices |
|
1449 |
#' @export |
|
1450 |
diagnose_pagination <- function(obj, |
|
1451 |
page_type = "letter", |
|
1452 |
font_family = "Courier", |
|
1453 |
font_size = 8, |
|
1454 |
lineheight = 1, |
|
1455 |
landscape = FALSE, |
|
1456 |
pg_width = NULL, |
|
1457 |
pg_height = NULL, |
|
1458 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
1459 |
lpp = NA_integer_, |
|
1460 |
cpp = NA_integer_, |
|
1461 |
min_siblings = 2, |
|
1462 |
nosplitin = character(), |
|
1463 |
colwidths = propose_column_widths(matrix_form(obj, TRUE), fontspec = fontspec), |
|
1464 |
tf_wrap = FALSE, |
|
1465 |
max_width = NULL, |
|
1466 |
indent_size = 2, |
|
1467 |
pg_size_spec = NULL, |
|
1468 |
rep_cols = num_rep_cols(obj), |
|
1469 |
col_gap = 3, |
|
1470 |
verbose = FALSE, |
|
1471 |
fontspec = font_spec( |
|
1472 |
font_family, |
|
1473 |
font_size, |
|
1474 |
lineheight |
|
1475 |
), |
|
1476 |
...) { |
|
1477 | 6x |
new_dev <- open_font_dev(fontspec) |
1478 | 6x |
if (new_dev) { |
1479 | 4x |
on.exit(close_font_dev()) |
1480 |
} |
|
1481 | 6x |
fpag <- do_forced_paginate(obj) |
1482 | 6x |
if (length(fpag) > 1) { |
1483 | 1x |
return(lapply( |
1484 | 1x |
fpag, |
1485 | 1x |
diagnose_pagination, |
1486 | 1x |
page_type = page_type, |
1487 | 1x |
landscape = landscape, |
1488 | 1x |
pg_width = pg_width, |
1489 | 1x |
pg_height = pg_height, |
1490 | 1x |
margins = margins, |
1491 | 1x |
lpp = lpp, |
1492 | 1x |
cpp = cpp, |
1493 | 1x |
tf_wrap = tf_wrap, |
1494 | 1x |
max_width = max_width, |
1495 | 1x |
colwidths = colwidths, |
1496 | 1x |
col_gap = col_gap, |
1497 | 1x |
min_siblings = min_siblings, |
1498 | 1x |
nosplitin = nosplitin, |
1499 | 1x |
fontspec = fontspec |
1500 |
)) |
|
1501 |
} |
|
1502 | ||
1503 | 5x |
mpf <- matrix_form(obj, TRUE, fontspec = fontspec) |
1504 | 5x |
msgres <- capture.output( |
1505 |
{ |
|
1506 | 5x |
tmp <- try( |
1507 | 5x |
paginate_to_mpfs( |
1508 | 5x |
obj, |
1509 | 5x |
page_type = page_type, |
1510 | 5x |
landscape = landscape, |
1511 | 5x |
pg_width = pg_width, |
1512 | 5x |
pg_height = pg_height, |
1513 | 5x |
margins = margins, |
1514 | 5x |
lpp = lpp, |
1515 | 5x |
cpp = cpp, |
1516 | 5x |
tf_wrap = tf_wrap, |
1517 | 5x |
max_width = max_width, |
1518 | 5x |
colwidths = colwidths, |
1519 | 5x |
col_gap = col_gap, |
1520 | 5x |
min_siblings = min_siblings, |
1521 | 5x |
nosplitin = nosplitin, |
1522 | 5x |
fontspec = fontspec, |
1523 | 5x |
verbose = TRUE |
1524 |
) |
|
1525 |
) |
|
1526 |
}, |
|
1527 | 5x |
type = "message" |
1528 |
) |
|
1529 | 5x |
if (is(tmp, "try-error") && grepl("Width of row labels equal to or larger", tmp)) { |
1530 | ! |
cond <- attr(tmp, "condition") |
1531 | ! |
stop(conditionMessage(cond), call. = conditionCall(cond)) |
1532 |
} |
|
1533 | ||
1534 | 5x |
lpp_diagnostic <- grep("^(Determining lines|Lines per page available).*$", msgres, value = TRUE) |
1535 | 5x |
cpp_diagnostic <- unique(grep("^Adjusted characters per page.*$", msgres, value = TRUE)) |
1536 | ||
1537 | 5x |
mpf <- do_cell_fnotes_wrap( |
1538 | 5x |
mpf, |
1539 | 5x |
widths = colwidths, max_width = max_width, tf_wrap = tf_wrap, |
1540 | 5x |
fontspec = font_spec(font_family, font_size, lineheight) |
1541 |
) |
|
1542 | 5x |
mpf <- mpf_infer_cinfo(mpf, colwidths = colwidths, fontspec = fontspec) |
1543 | ||
1544 | 5x |
rownls <- grep("Checking pagination after row", msgres, fixed = TRUE) |
1545 | 5x |
rownum <- as.integer(gsub("[^[:digit:]]*(.*)$", "\\1", msgres[rownls])) |
1546 | 5x |
rowmsgs <- vapply(unique(rownum), function(ii) { |
1547 | ! |
idx <- max(which(rownum == ii)) |
1548 | ! |
gsub("\\t[.]*", "", msgres[rownls[idx] + 1]) |
1549 |
}, "") |
|
1550 | ||
1551 | 5x |
msgdf <- data.frame( |
1552 | 5x |
abs_rownumber = unique(rownum), |
1553 | 5x |
final_pag_result = rowmsgs, stringsAsFactors = FALSE |
1554 |
) |
|
1555 | 5x |
rdf <- mf_rinfo(mpf)[, c("abs_rownumber", "label", "self_extent", "par_extent", "node_class")] |
1556 | 5x |
rdf$pag_attempted <- rdf$abs_rownumber %in% rownum |
1557 | 5x |
row_diagnose <- merge(rdf, msgdf, by = "abs_rownumber", all.x = TRUE) |
1558 | ||
1559 | 5x |
colnls <- grep("Checking pagination after column", msgres, fixed = TRUE) |
1560 | 5x |
colnum <- as.integer(gsub("[^[:digit:]]*(.*)$", "\\1", msgres[colnls])) |
1561 | 5x |
colmsgs <- vapply(unique(colnum), function(ii) { |
1562 | ! |
idx <- max(which(colnum == ii)) |
1563 | ! |
gsub("\\t[.]*", "", msgres[colnls[idx] + 1]) |
1564 |
}, "") |
|
1565 | ||
1566 | 5x |
colmsgdf <- data.frame( |
1567 | 5x |
abs_rownumber = unique(colnum), |
1568 | 5x |
final_pag_result = colmsgs, |
1569 | 5x |
stringsAsFactors = FALSE |
1570 |
) |
|
1571 | 5x |
cdf <- mf_cinfo(mpf)[, c("abs_rownumber", "self_extent")] |
1572 | 5x |
cdf$pag_attempted <- cdf$abs_rownumber %in% colnum |
1573 | 5x |
col_diagnose <- merge(cdf, colmsgdf, by = "abs_rownumber", all.x = TRUE) |
1574 | 5x |
names(col_diagnose) <- gsub("^abs_rownumber$", "abs_colnumber", names(col_diagnose)) |
1575 | 5x |
list( |
1576 | 5x |
lpp_diagnostics = lpp_diagnostic, |
1577 | 5x |
row_diagnostics = row_diagnose, |
1578 | 5x |
cpp_diagnostics = cpp_diagnostic, |
1579 | 5x |
col_diagnostics = col_diagnose |
1580 |
) |
|
1581 |
} |
1 |
### This file defines the generics which make up the interface `formatters` offers. |
|
2 |
### Defining methods for these generics for a new table-like class should be fully |
|
3 |
### sufficient for hooking that class up to the `formatters` pagination and rendering |
|
4 |
### machinery. |
|
5 | ||
6 |
#' Make row layout summary data frames for use during pagination |
|
7 |
#' |
|
8 |
#' All relevant information about table rows (e.g. indentations) is summarized in a `data.frame`. |
|
9 |
#' This function works **only** on `rtables` and `rlistings` objects, and not on their `print` counterparts |
|
10 |
#' (like [`MatrixPrintForm`]). |
|
11 |
#' |
|
12 |
#' @inheritParams open_font_dev |
|
13 |
#' @param tt (`ANY`)\cr object representing the table-like object to be summarized. |
|
14 |
#' @param visible_only (`flag`)\cr should only visible aspects of the table structure be reflected |
|
15 |
#' in this summary. Defaults to `TRUE`. May not be supported by all methods. |
|
16 |
#' @param incontent (`flag`)\cr internal detail, do not set manually. |
|
17 |
#' @param repr_ext (`integer(1)`)\cr internal detail, do not set manually. |
|
18 |
#' @param repr_inds (`integer`)\cr internal detail, do not set manually. |
|
19 |
#' @param sibpos (`integer(1)`)\cr internal detail, do not set manually. |
|
20 |
#' @param nsibs (`integer(1)`)\cr internal detail, do not set manually. |
|
21 |
#' @param rownum (`numeric(1)`)\cr internal detail, do not set manually. |
|
22 |
#' @param indent (`integer(1)`)\cr internal detail, do not set manually. |
|
23 |
#' @param colwidths (`numeric`)\cr internal detail, do not set manually. |
|
24 |
#' @param path (`character`)\cr path to the (sub)table represented by `tt`. Defaults to `character()`. |
|
25 |
#' @param max_width (`numeric(1)` or `NULL`)\cr maximum width for title/footer materials. |
|
26 |
#' @param col_gap (`numeric(1)`)\cr the gap to be assumed between columns, in number of spaces with |
|
27 |
#' font specified by `fontspec`. |
|
28 |
#' |
|
29 |
#' @import methods |
|
30 |
#' @include matrix_form.R |
|
31 |
#' |
|
32 |
#' @details |
|
33 |
#' When `visible_only` is `TRUE` (the default), methods should return a `data.frame` with exactly one |
|
34 |
#' row per visible row in the table-like object. This is useful when reasoning about how a table will |
|
35 |
#' print, but does not reflect the full pathing space of the structure (though the paths which are given |
|
36 |
#' will all work as is). |
|
37 |
#' |
|
38 |
#' If supported, when `visible_only` is `FALSE`, every structural element of the table (in row-space) |
|
39 |
#' will be reflected in the returned `data.frame`, meaning the full pathing-space will be represented |
|
40 |
#' but some rows in the layout summary will not represent printed rows in the table as it is displayed. |
|
41 |
#' |
|
42 |
#' Most arguments beyond `tt` and `visible_only` are present so that `make_row_df` methods can call |
|
43 |
#' `make_row_df` recursively and retain information, and should not be set during a top-level call. |
|
44 |
#' |
|
45 |
#' @return A `data.frame` of row/column-structure information used by the pagination machinery. |
|
46 |
#' |
|
47 |
#' @note The technically present root tree node is excluded from the summary returned by |
|
48 |
#' both `make_row_df` and `make_col_df` (see relevant functions in`rtables`), as it is the |
|
49 |
#' row/column structure of `tt` and thus not useful for pathing or pagination. |
|
50 |
#' |
|
51 |
#' @examples |
|
52 |
#' # Expected error with matrix_form. For real case examples consult {rtables} documentation |
|
53 |
#' mf <- basic_matrix_form(iris) |
|
54 |
#' # make_row_df(mf) # Use table obj instead |
|
55 |
#' |
|
56 |
#' @export |
|
57 |
#' @name make_row_df |
|
58 |
setGeneric("make_row_df", function(tt, colwidths = NULL, visible_only = TRUE, |
|
59 |
rownum = 0, |
|
60 |
indent = 0L, |
|
61 |
path = character(), |
|
62 |
incontent = FALSE, |
|
63 |
repr_ext = 0L, |
|
64 |
repr_inds = integer(), |
|
65 |
sibpos = NA_integer_, |
|
66 |
nsibs = NA_integer_, |
|
67 |
max_width = NULL, |
|
68 |
fontspec = font_spec(), |
|
69 |
col_gap = 3L) { |
|
70 | 1x |
standardGeneric("make_row_df") |
71 |
}) |
|
72 | ||
73 |
#' @rdname make_row_df |
|
74 |
setMethod("make_row_df", "MatrixPrintForm", function(tt, colwidths = NULL, visible_only = TRUE, |
|
75 |
rownum = 0, |
|
76 |
indent = 0L, |
|
77 |
path = character(), |
|
78 |
incontent = FALSE, |
|
79 |
repr_ext = 0L, |
|
80 |
repr_inds = integer(), |
|
81 |
sibpos = NA_integer_, |
|
82 |
nsibs = NA_integer_, |
|
83 |
max_width = NULL, |
|
84 |
fontspec = font_spec(), |
|
85 |
col_gap = mf_colgap(tt) %||% 3L) { |
|
86 | 1x |
msg <- paste0( |
87 | 1x |
"make_row_df can be used only on {rtables} table objects, and not on `matrix_form`-", |
88 | 1x |
"generated objects (MatrixPrintForm)." |
89 |
) |
|
90 | 1x |
stop(msg) |
91 |
}) |
|
92 | ||
93 |
#' Transform `rtable` to a list of matrices which can be used for outputting |
|
94 |
#' |
|
95 |
#' Although `rtable`s are represented as a tree data structure when outputting the table to ASCII or HTML, |
|
96 |
#' it is useful to map the `rtable` to an in-between state with the formatted cells in a matrix form. |
|
97 |
#' |
|
98 |
#' @inheritParams make_row_df |
|
99 |
#' @param obj (`ANY`)\cr object to be transformed into a ready-to-render form (a [`MatrixPrintForm`] object). |
|
100 |
#' @param indent_rownames (`flag`)\cr if `TRUE`, the row names column in the `strings` matrix of `obj` |
|
101 |
#' will have indented row names (strings pre-fixed). |
|
102 |
#' @param expand_newlines (`flag`)\cr whether the generated matrix form should expand rows whose values |
|
103 |
#' contain newlines into multiple 'physical' rows (as they will appear when rendered into ASCII). Defaults |
|
104 |
#' to `TRUE`. |
|
105 |
#' @param indent_size (`numeric(1)`)\cr number of spaces to be used per level of indent (if supported by |
|
106 |
#' the relevant method). Defaults to 2. |
|
107 |
#' |
|
108 |
#' @return A [`MatrixPrintForm`] classed list with an additional `nrow_header` attribute indicating the |
|
109 |
#' number of pseudo "rows" the column structure defines, with the following elements: |
|
110 |
#' \describe{ |
|
111 |
#' \item{`strings`}{The content, as it should be printed, of the top-left material, column headers, row |
|
112 |
#' labels, and cell values of `tt`.} |
|
113 |
#' \item{`spans`}{The column-span information for each print-string in the strings matrix.} |
|
114 |
#' \item{`aligns`}{The text alignment for each print-string in the strings matrix.} |
|
115 |
#' \item{`display`}{Whether each print-string in the strings matrix should be printed or not.} |
|
116 |
#' \item{`row_info`}{The `data.frame` generated by [basic_pagdf()].} |
|
117 |
#' } |
|
118 |
#' |
|
119 |
#' @export |
|
120 |
setGeneric("matrix_form", function(obj, |
|
121 |
indent_rownames = FALSE, |
|
122 |
expand_newlines = TRUE, |
|
123 |
indent_size = 2, |
|
124 |
fontspec = NULL, |
|
125 |
col_gap = NULL) { |
|
126 | 370x |
standardGeneric("matrix_form") |
127 |
}) |
|
128 | ||
129 | ||
130 |
#' @rdname matrix_form |
|
131 |
#' @export |
|
132 |
setMethod("matrix_form", "MatrixPrintForm", function(obj, |
|
133 |
indent_rownames = FALSE, |
|
134 |
expand_newlines = TRUE, |
|
135 |
indent_size = 2, |
|
136 |
fontspec = NULL, |
|
137 |
col_gap = NULL) { |
|
138 | 370x |
if (!is.null(fontspec)) { |
139 | 365x |
mf_fontspec(obj) <- fontspec |
140 |
} |
|
141 | 370x |
if (!is.null(col_gap) && !isTRUE(all.equal(col_gap, mf_colgap(obj)))) { |
142 | ! |
mf_colgap(obj) <- col_gap |
143 |
} |
|
144 | 370x |
obj |
145 |
}) |
|
146 | ||
147 |
# Generics for `toString` and helper functions ----------------------------------------------------------- |
|
148 | ||
149 |
## this is where we will take word wrapping |
|
150 |
## into account when it is added |
|
151 |
## |
|
152 |
## ALL calculations of vertical space for pagination |
|
153 |
## purposes must go through nlines and divider_height!!!!!!!! |
|
154 | ||
155 |
## this will be customizable someday. I have foreseen it (spooky noises) |
|
156 |
#' Divider height |
|
157 |
#' |
|
158 |
#' @param obj (`ANY`)\cr object. |
|
159 |
#' |
|
160 |
#' @return The height, in lines of text, of the divider between header and body. Currently |
|
161 |
#' returns `1L` for the default method. |
|
162 |
#' |
|
163 |
#' @examples |
|
164 |
#' divider_height(mtcars) |
|
165 |
#' |
|
166 |
#' @export |
|
167 | 49x |
setGeneric("divider_height", function(obj) standardGeneric("divider_height")) |
168 | ||
169 |
#' @rdname divider_height |
|
170 |
#' @export |
|
171 |
setMethod( |
|
172 |
"divider_height", "ANY", |
|
173 | 49x |
function(obj) 1L |
174 |
) |
|
175 | ||
176 |
# nlines --------------------------------------------------------------- |
|
177 | ||
178 |
#' Number of lines required to print a value |
|
179 |
#' |
|
180 |
#' @inheritParams open_font_dev |
|
181 |
#' @param x (`ANY`)\cr the object to be printed. |
|
182 |
#' @param colwidths (`numeric`)\cr column widths (if necessary). Principally used in `rtables`' |
|
183 |
#' method. |
|
184 |
#' @param max_width (`numeric(1)`)\cr width that strings should be wrapped to when |
|
185 |
#' determining how many lines they require. |
|
186 |
#' @param col_gap (`numeric(1)`)\cr width of gap between columns in number of spaces. |
|
187 |
#' Only used by methods which must calculate span widths after wrapping. |
|
188 |
#' |
|
189 |
#' @return The number of lines needed to render the object `x`. |
|
190 |
#' |
|
191 |
#' @export |
|
192 |
setGeneric( |
|
193 |
"nlines", |
|
194 |
## XXX TODO come back and add fontspec default value once not having |
|
195 |
## it has found all the disconnection breakages |
|
196 | 50656x |
function(x, colwidths = NULL, max_width = NULL, fontspec, col_gap = NULL) standardGeneric("nlines") |
197 |
) |
|
198 | ||
199 |
## XXX beware. I think it is dangerous |
|
200 |
#' @export |
|
201 |
#' @rdname nlines |
|
202 |
setMethod( |
|
203 |
"nlines", "list", |
|
204 |
function(x, colwidths, max_width, fontspec, col_gap = NULL) { |
|
205 | 2x |
if (length(x) == 0) { |
206 | 1x |
0L |
207 |
} else { |
|
208 | 1x |
sum(unlist(vapply(x, nlines, NA_integer_, colwidths = colwidths, max_width = max_width, fontspec = fontspec))) |
209 |
} |
|
210 |
} |
|
211 |
) |
|
212 | ||
213 |
#' @export |
|
214 |
#' @rdname nlines |
|
215 |
setMethod("nlines", "NULL", function(x, colwidths, max_width, fontspec, col_gap = NULL) 0L) |
|
216 | ||
217 |
#' @export |
|
218 |
#' @rdname nlines |
|
219 |
setMethod("nlines", "character", function(x, colwidths, max_width, fontspec, col_gap = NULL) { |
|
220 | 50653x |
splstr <- strsplit(x, "\n", fixed = TRUE) |
221 | 50653x |
if (length(x) == 0) { |
222 | 1x |
return(0L) |
223 |
} |
|
224 | ||
225 | 50652x |
sum(vapply(splstr, |
226 | 50652x |
function(xi, max_width) { |
227 | 50701x |
if (length(xi) == 0) { |
228 | 1522x |
1L |
229 | 49179x |
} else if (length(max_width) == 0) { ## this happens with strsplit("", "\n") |
230 | 49057x |
length(xi) |
231 |
} else { |
|
232 | 122x |
length(wrap_txt(xi, max_width, fontspec = fontspec)) |
233 |
} |
|
234 | 50652x |
}, 1L, |
235 | 50652x |
max_width = max_width |
236 |
)) |
|
237 |
}) |
|
238 | ||
239 |
#' Transform objects into string representations |
|
240 |
#' |
|
241 |
#' Transform a complex object into a string representation ready to be printed or written |
|
242 |
#' to a plain-text file. |
|
243 |
#' |
|
244 |
#' @param x (`ANY`)\cr object to be prepared for rendering. |
|
245 |
#' @param ... additional parameters passed to individual methods. |
|
246 |
#' |
|
247 |
#' @export |
|
248 |
#' @rdname tostring |
|
249 |
setGeneric("toString", function(x, ...) standardGeneric("toString")) |
|
250 | ||
251 |
## preserve S3 behavior |
|
252 |
setMethod("toString", "ANY", base::toString) |
|
253 | ||
254 |
|
|
255 |
#' |
|
256 |
#' Print an R object. See [print()]. |
|
257 |
#' |
|
258 |
#' @inheritParams base::print |
|
259 |
#' |
|
260 |
#' @rdname basemethods |
|
261 |
setMethod("print", "ANY", base::print) |
|
262 | ||
263 |
# General/"universal" property getter and setter generics and stubs -------------------------------------- |
|
264 | ||
265 |
#' Label, name, and format accessor generics |
|
266 |
#' |
|
267 |
#' Getters and setters for basic, relatively universal attributes of "table-like" objects. |
|
268 |
#' |
|
269 |
#' @param obj (`ANY`)\cr the object. |
|
270 |
#' @param value (`string` or `FormatSpec`)\cr the new value of the attribute. |
|
271 |
#' |
|
272 |
#' @return The name, format, or label of `obj` for getters, or `obj` after modification for setters. |
|
273 |
#' |
|
274 |
#' @export |
|
275 |
#' @name lab_name |
|
276 |
#' @aliases obj_name |
|
277 | ||
278 |
# obj_name --------------------------------------------------------------- |
|
279 | ||
280 | ! |
setGeneric("obj_name", function(obj) standardGeneric("obj_name")) |
281 | ||
282 |
#' @rdname lab_name |
|
283 |
#' @export |
|
284 | ! |
setGeneric("obj_name<-", function(obj, value) standardGeneric("obj_name<-")) |
285 | ||
286 |
# obj_label --------------------------------------------------------------- |
|
287 | ||
288 |
#' @seealso with_label |
|
289 |
#' @rdname lab_name |
|
290 |
#' @export |
|
291 | 3x |
setGeneric("obj_label", function(obj) standardGeneric("obj_label")) |
292 | ||
293 |
#' @rdname lab_name |
|
294 |
#' @param value character(1). The new label |
|
295 |
#' @export |
|
296 | 2x |
setGeneric("obj_label<-", function(obj, value) standardGeneric("obj_label<-")) |
297 | ||
298 |
#' @rdname lab_name |
|
299 |
#' @exportMethod obj_label |
|
300 | 3x |
setMethod("obj_label", "ANY", function(obj) attr(obj, "label")) |
301 | ||
302 |
#' @rdname lab_name |
|
303 |
#' @exportMethod obj_label<- |
|
304 |
setMethod( |
|
305 |
"obj_label<-", "ANY", |
|
306 |
function(obj, value) { |
|
307 | 2x |
attr(obj, "label") <- value |
308 | 2x |
obj |
309 |
} |
|
310 |
) |
|
311 | ||
312 |
# obj_format --------------------------------------------------------------- |
|
313 | ||
314 |
#' @rdname lab_name |
|
315 |
#' @export |
|
316 | 292x |
setGeneric("obj_format", function(obj) standardGeneric("obj_format")) |
317 | ||
318 |
## this covers rcell, etc |
|
319 |
#' @rdname lab_name |
|
320 |
#' @exportMethod obj_format |
|
321 | 290x |
setMethod("obj_format", "ANY", function(obj) attr(obj, "format", exact = TRUE)) |
322 | ||
323 |
#' @rdname lab_name |
|
324 |
#' @export |
|
325 | 2x |
setMethod("obj_format", "fmt_config", function(obj) obj@format) |
326 | ||
327 |
#' @export |
|
328 |
#' @rdname lab_name |
|
329 | 3x |
setGeneric("obj_format<-", function(obj, value) standardGeneric("obj_format<-")) |
330 | ||
331 |
## this covers rcell, etc |
|
332 |
#' @exportMethod obj_format<- |
|
333 |
#' @rdname lab_name |
|
334 |
setMethod("obj_format<-", "ANY", function(obj, value) { |
|
335 | 2x |
attr(obj, "format") <- value |
336 | 2x |
obj |
337 |
}) |
|
338 | ||
339 |
#' @rdname lab_name |
|
340 |
#' @export |
|
341 |
setMethod("obj_format<-", "fmt_config", function(obj, value) { |
|
342 | 1x |
obj@format <- value |
343 | 1x |
obj |
344 |
}) |
|
345 | ||
346 |
# obj_na_str --------------------------------------------------------------- |
|
347 | ||
348 |
#' @rdname lab_name |
|
349 |
#' @export |
|
350 | 3x |
setGeneric("obj_na_str", function(obj) standardGeneric("obj_na_str")) |
351 | ||
352 |
#' @rdname lab_name |
|
353 |
#' @exportMethod obj_na_str |
|
354 | 1x |
setMethod("obj_na_str", "ANY", function(obj) attr(obj, "format_na_str", exact = TRUE)) |
355 | ||
356 |
#' @rdname lab_name |
|
357 |
#' @export |
|
358 | 2x |
setMethod("obj_na_str", "fmt_config", function(obj) obj@format_na_str) |
359 | ||
360 |
#' @rdname lab_name |
|
361 |
#' @export |
|
362 | 2x |
setGeneric("obj_na_str<-", function(obj, value) standardGeneric("obj_na_str<-")) |
363 | ||
364 |
#' @exportMethod obj_na_str<- |
|
365 |
#' @rdname lab_name |
|
366 |
setMethod("obj_na_str<-", "ANY", function(obj, value) { |
|
367 | 1x |
attr(obj, "format_na_str") <- value |
368 | 1x |
obj |
369 |
}) |
|
370 | ||
371 |
#' @rdname lab_name |
|
372 |
#' @export |
|
373 |
setMethod("obj_na_str<-", "fmt_config", function(obj, value) { |
|
374 | 1x |
obj@format_na_str <- value |
375 | 1x |
obj |
376 |
}) |
|
377 | ||
378 |
# obj_align --------------------------------------------------------------- |
|
379 | ||
380 |
#' @rdname lab_name |
|
381 |
#' @export |
|
382 | 3x |
setGeneric("obj_align", function(obj) standardGeneric("obj_align")) |
383 | ||
384 |
#' @rdname lab_name |
|
385 |
#' @exportMethod obj_align |
|
386 | 1x |
setMethod("obj_align", "ANY", function(obj) attr(obj, "align", exact = TRUE)) |
387 | ||
388 |
#' @rdname lab_name |
|
389 |
#' @export |
|
390 | 2x |
setMethod("obj_align", "fmt_config", function(obj) obj@align) |
391 | ||
392 |
#' @rdname lab_name |
|
393 |
#' @export |
|
394 | 2x |
setGeneric("obj_align<-", function(obj, value) standardGeneric("obj_align<-")) |
395 | ||
396 |
#' @exportMethod obj_align<- |
|
397 |
#' @rdname lab_name |
|
398 |
setMethod("obj_align<-", "ANY", function(obj, value) { |
|
399 | 1x |
attr(obj, "align") <- value |
400 | 1x |
obj |
401 |
}) |
|
402 | ||
403 |
#' @rdname lab_name |
|
404 |
#' @export |
|
405 |
setMethod("obj_align<-", "fmt_config", function(obj, value) { |
|
406 | 1x |
obj@align <- value |
407 | 1x |
obj |
408 |
}) |
|
409 | ||
410 |
# main_title --------------------------------------------------------------- |
|
411 | ||
412 |
#' General title and footer accessors |
|
413 |
#' |
|
414 |
#' @param obj (`ANY`)\cr object to extract information from. |
|
415 |
#' |
|
416 |
#' @return A character scalar (`main_title`), character vector (`main_footer`), or |
|
417 |
#' vector of length zero or more (`subtitles`, `page_titles`, `prov_footer`) containing |
|
418 |
#' the relevant title/footer contents. |
|
419 |
#' |
|
420 |
#' @export |
|
421 |
#' @rdname title_footer |
|
422 | 492x |
setGeneric("main_title", function(obj) standardGeneric("main_title")) |
423 | ||
424 |
#' @export |
|
425 |
#' @rdname title_footer |
|
426 |
setMethod( |
|
427 |
"main_title", "MatrixPrintForm", |
|
428 | 492x |
function(obj) obj$main_title |
429 |
) |
|
430 | ||
431 |
##' @rdname title_footer |
|
432 |
##' @export |
|
433 | 17x |
setGeneric("main_title<-", function(obj, value) standardGeneric("main_title<-")) |
434 | ||
435 |
##' @rdname title_footer |
|
436 |
##' @export |
|
437 |
setMethod( |
|
438 |
"main_title<-", "MatrixPrintForm", |
|
439 |
function(obj, value) { |
|
440 | 17x |
obj$main_title <- value |
441 | 17x |
obj |
442 |
} |
|
443 |
) |
|
444 | ||
445 |
# subtitles --------------------------------------------------------------- |
|
446 | ||
447 |
#' @export |
|
448 |
#' @rdname title_footer |
|
449 | 491x |
setGeneric("subtitles", function(obj) standardGeneric("subtitles")) |
450 | ||
451 |
#' @export |
|
452 |
#' @rdname title_footer |
|
453 |
setMethod( |
|
454 |
"subtitles", "MatrixPrintForm", |
|
455 | 491x |
function(obj) obj$subtitles |
456 |
) |
|
457 | ||
458 |
##' @rdname title_footer |
|
459 |
##' @export |
|
460 | 14x |
setGeneric("subtitles<-", function(obj, value) standardGeneric("subtitles<-")) |
461 | ||
462 |
##' @rdname title_footer |
|
463 |
##' @export |
|
464 |
setMethod( |
|
465 |
"subtitles<-", "MatrixPrintForm", |
|
466 |
function(obj, value) { |
|
467 | 14x |
obj$subtitles <- value |
468 | 14x |
obj |
469 |
} |
|
470 |
) |
|
471 | ||
472 |
# page_titles --------------------------------------------------------------- |
|
473 | ||
474 |
#' @export |
|
475 |
#' @rdname title_footer |
|
476 | 532x |
setGeneric("page_titles", function(obj) standardGeneric("page_titles")) |
477 | ||
478 |
#' @export |
|
479 |
#' @rdname title_footer |
|
480 |
setMethod( |
|
481 |
"page_titles", "MatrixPrintForm", |
|
482 | 532x |
function(obj) obj$page_titles |
483 |
) |
|
484 |
#' @rdname title_footer |
|
485 |
#' @export |
|
486 | ! |
setMethod("page_titles", "ANY", function(obj) NULL) |
487 | ||
488 |
##' @rdname title_footer |
|
489 |
##' @export |
|
490 | 2x |
setGeneric("page_titles<-", function(obj, value) standardGeneric("page_titles<-")) |
491 | ||
492 |
#' @export |
|
493 |
#' @rdname title_footer |
|
494 |
setMethod( |
|
495 |
"page_titles<-", "MatrixPrintForm", |
|
496 |
function(obj, value) { |
|
497 | 2x |
if (!is.character(value)) { |
498 | ! |
stop("page titles must be in the form of a character vector, got object of class ", class(value)) |
499 |
} |
|
500 | 2x |
obj$page_titles <- value |
501 | 2x |
obj |
502 |
} |
|
503 |
) |
|
504 | ||
505 |
# main_footer --------------------------------------------------------------- |
|
506 | ||
507 |
#' @export |
|
508 |
#' @rdname title_footer |
|
509 | 472x |
setGeneric("main_footer", function(obj) standardGeneric("main_footer")) |
510 | ||
511 |
#' @export |
|
512 |
#' @rdname title_footer |
|
513 |
setMethod( |
|
514 |
"main_footer", "MatrixPrintForm", |
|
515 | 472x |
function(obj) obj$main_footer |
516 |
) |
|
517 | ||
518 |
#' @rdname title_footer |
|
519 |
#' @param value character. New value. |
|
520 |
#' @export |
|
521 | 274x |
setGeneric("main_footer<-", function(obj, value) standardGeneric("main_footer<-")) |
522 | ||
523 |
#' @export |
|
524 |
#' @rdname title_footer |
|
525 |
setMethod( |
|
526 |
"main_footer<-", "MatrixPrintForm", |
|
527 |
function(obj, value) { |
|
528 | 274x |
if (!is.character(value)) { |
529 | ! |
stop("main footer must be a character vector. Got object of class ", class(value)) |
530 |
} |
|
531 | 274x |
obj$main_footer <- value |
532 | 274x |
obj |
533 |
} |
|
534 |
) |
|
535 | ||
536 |
# prov_footer --------------------------------------------------------------- |
|
537 | ||
538 |
#' @export |
|
539 |
#' @rdname title_footer |
|
540 | 597x |
setGeneric("prov_footer", function(obj) standardGeneric("prov_footer")) |
541 | ||
542 |
#' @export |
|
543 |
#' @rdname title_footer |
|
544 |
setMethod( |
|
545 |
"prov_footer", "MatrixPrintForm", |
|
546 | 597x |
function(obj) obj$prov_footer |
547 |
) |
|
548 | ||
549 |
#' @rdname title_footer |
|
550 |
#' @export |
|
551 | 357x |
setGeneric("prov_footer<-", function(obj, value) standardGeneric("prov_footer<-")) |
552 | ||
553 |
#' @export |
|
554 |
#' @rdname title_footer |
|
555 |
setMethod( |
|
556 |
"prov_footer<-", "MatrixPrintForm", |
|
557 |
function(obj, value) { |
|
558 | 357x |
if (!is.character(value)) { |
559 | ! |
stop("provenance footer must be a character vector. Got object of class ", class(value)) |
560 |
} |
|
561 | 357x |
obj$prov_footer <- value |
562 | 357x |
obj |
563 |
} |
|
564 |
) |
|
565 | ||
566 |
#' @rdname title_footer |
|
567 |
#' @export |
|
568 | 1x |
all_footers <- function(obj) c(main_footer(obj), prov_footer(obj)) |
569 | ||
570 |
#' @rdname title_footer |
|
571 |
#' @export |
|
572 | 484x |
all_titles <- function(obj) c(main_title(obj), subtitles(obj), page_titles(obj)) |
573 | ||
574 |
# table_inset --------------------------------------------------------------- |
|
575 | ||
576 |
#' Access or (recursively) set table inset |
|
577 |
#' |
|
578 |
#' Table inset is the amount of characters that the body of a table, referential footnotes, and |
|
579 |
#' main footer material are inset from the left-alignment of the titles and provenance |
|
580 |
#' footer materials. |
|
581 |
#' |
|
582 |
#' @param obj (`ANY`)\cr object to get or (recursively if necessary) set table inset for. |
|
583 |
#' @param value (`string`)\cr string to use as new header/body separator. |
|
584 |
#' |
|
585 |
#' @return |
|
586 |
#' * `table_inset` returns the integer value that the table body (including column heading |
|
587 |
#' information and section dividers), referential footnotes, and main footer should be inset |
|
588 |
#' from the left alignment of the titles and provenance footers during rendering. |
|
589 |
#' * `table_inset<-` returns `obj` with the new table_inset value applied recursively to it and |
|
590 |
#' all its subtables. |
|
591 |
#' |
|
592 |
#' @export |
|
593 | 454x |
setGeneric("table_inset", function(obj) standardGeneric("table_inset")) |
594 | ||
595 |
#' @rdname table_inset |
|
596 |
#' @export |
|
597 |
setMethod( |
|
598 |
"table_inset", "MatrixPrintForm", |
|
599 | 454x |
function(obj) obj$table_inset |
600 |
) |
|
601 | ||
602 |
#' @rdname table_inset |
|
603 |
#' @export |
|
604 | 4x |
setGeneric("table_inset<-", function(obj, value) standardGeneric("table_inset<-")) |
605 | ||
606 |
#' @rdname table_inset |
|
607 |
#' @export |
|
608 |
setMethod( |
|
609 |
"table_inset<-", "MatrixPrintForm", |
|
610 |
function(obj, value) { |
|
611 | 4x |
newval <- as.integer(value) |
612 | 4x |
if (is.na(newval) || newval < 0) { |
613 | 1x |
stop("Got invalid value for table_inset: ", newval) |
614 |
} |
|
615 | 3x |
obj$table_inset <- newval |
616 | 3x |
obj |
617 |
} |
|
618 |
) |
|
619 | ||
620 |
# do_forced_paginate --------------------------------------------------------------- |
|
621 | ||
622 |
#' Generic for performing "forced" pagination |
|
623 |
#' |
|
624 |
#' Forced pagination is pagination which happens regardless of position on page. The object |
|
625 |
#' is expected to have all information necessary to locate such page breaks, and the |
|
626 |
#' `do_forced_pag` method is expected to fully perform those paginations. |
|
627 |
#' |
|
628 |
#' @param obj (`ANY`)\cr object to be paginated. The `ANY` method simply returns a list of |
|
629 |
#' length one, containing `obj`. |
|
630 |
#' |
|
631 |
#' @return A list of sub-objects, which will be further paginated by the standard pagination |
|
632 |
#' algorithm. |
|
633 |
#' |
|
634 |
#' @export |
|
635 | 104x |
setGeneric("do_forced_paginate", function(obj) standardGeneric("do_forced_paginate")) |
636 | ||
637 |
#' @export |
|
638 |
#' @rdname do_forced_paginate |
|
639 | 101x |
setMethod("do_forced_paginate", "ANY", function(obj) list(obj)) |
640 | ||
641 |
# num_rep_cols --------------------------------------------------------------- |
|
642 | ||
643 |
#' Number of repeated columns |
|
644 |
#' |
|
645 |
#' When called on a table-like object using the formatters framework, this method returns the |
|
646 |
#' number of columns which are mandatorily repeated after each horizontal pagination. |
|
647 |
#' |
|
648 |
#' Absent a class-specific method, this function returns 0, indicating no always-repeated columns. |
|
649 |
#' |
|
650 |
#' @param obj (`ANY`)\cr a table-like object. |
|
651 |
#' |
|
652 |
#' @return An integer. |
|
653 |
#' |
|
654 |
#' @note This number *does not* include row labels, the repetition of which is handled separately. |
|
655 |
#' |
|
656 |
#' @examples |
|
657 |
#' mpf <- basic_matrix_form(mtcars) |
|
658 |
#' num_rep_cols(mpf) |
|
659 |
#' lmpf <- basic_listing_mf(mtcars) |
|
660 |
#' num_rep_cols(lmpf) |
|
661 |
#' |
|
662 |
#' @export |
|
663 | 659x |
setGeneric("num_rep_cols", function(obj) standardGeneric("num_rep_cols")) |
664 | ||
665 |
#' @export |
|
666 |
#' @rdname num_rep_cols |
|
667 | ! |
setMethod("num_rep_cols", "ANY", function(obj) 0L) |
668 | ||
669 |
#' @export |
|
670 |
#' @rdname num_rep_cols |
|
671 | 659x |
setMethod("num_rep_cols", "MatrixPrintForm", function(obj) obj$num_rep_cols) |
672 | ||
673 |
#' @export |
|
674 |
#' @param value (`numeric(1)`)\cr the new number of columns to repeat. |
|
675 |
#' @rdname num_rep_cols |
|
676 | 144x |
setGeneric("num_rep_cols<-", function(obj, value) standardGeneric("num_rep_cols<-")) |
677 | ||
678 |
#' @export |
|
679 |
#' @rdname num_rep_cols |
|
680 | ! |
setMethod("num_rep_cols<-", "ANY", function(obj, value) stop("No num_rep_cols<- method for class ", class(obj))) |
681 | ||
682 |
#' @export |
|
683 |
#' @rdname num_rep_cols |
|
684 |
setMethod("num_rep_cols<-", "MatrixPrintForm", function(obj, value) { |
|
685 | 144x |
obj <- mf_update_cinfo(obj, colwidths = NULL, rep_cols = value) |
686 | 144x |
obj |
687 |
}) |
|
688 | ||
689 |
# header_section_div ----------------------------------------------------------- |
|
690 | ||
691 |
#' @keywords internal |
|
692 | 153x |
setGeneric("header_section_div", function(obj) standardGeneric("header_section_div")) |
693 | ||
694 |
#' @keywords internal |
|
695 |
setMethod( |
|
696 |
"header_section_div", "MatrixPrintForm", |
|
697 | 153x |
function(obj) obj$header_section_div |
698 |
) |
|
699 | ||
700 |
#' @keywords internal |
|
701 | ! |
setGeneric("header_section_div<-", function(obj, value) standardGeneric("header_section_div<-")) |
702 | ||
703 |
#' @keywords internal |
|
704 |
setMethod( |
|
705 |
"header_section_div<-", "MatrixPrintForm", |
|
706 |
function(obj, value) { |
|
707 | ! |
obj$header_section_div <- value |
708 | ! |
obj |
709 |
} |
|
710 |
) |
|
711 | ||
712 |
# horizontal_sep --------------------------------------------------------------- |
|
713 | ||
714 |
#' @keywords internal |
|
715 | 121x |
setGeneric("horizontal_sep", function(obj) standardGeneric("horizontal_sep")) |
716 | ||
717 |
#' @keywords internal |
|
718 |
setMethod( |
|
719 |
"horizontal_sep", "MatrixPrintForm", |
|
720 | 121x |
function(obj) obj$horizontal_sep |
721 |
) |
|
722 | ||
723 |
#' @keywords internal |
|
724 | 1x |
setGeneric("horizontal_sep<-", function(obj, value) standardGeneric("horizontal_sep<-")) |
725 | ||
726 |
#' @keywords internal |
|
727 |
setMethod( |
|
728 |
"horizontal_sep<-", "MatrixPrintForm", |
|
729 |
function(obj, value) { |
|
730 | 1x |
obj$horizontal_sep <- value |
731 | 1x |
obj |
732 |
} |
|
733 |
) |
1 |
## until we do it for real |
|
2 | ||
3 |
#' Class for Matrix Print Form |
|
4 |
#' |
|
5 |
#' The `MatrixPrintForm` class, an intermediate representation for ASCII table printing. |
|
6 |
#' |
|
7 |
#' @name MatrixPrintForm-class |
|
8 |
#' @rdname MatrixPrintForm_class |
|
9 |
#' @exportClass MatrixPrintForm |
|
10 |
setOldClass(c("MatrixPrintForm", "list")) |
|
11 | ||
12 |
mform_handle_newlines <- function(matform) { |
|
13 |
# Retrieving relevant information |
|
14 | 259x |
has_topleft <- mf_has_topleft(matform) |
15 | 259x |
strmat <- mf_strings(matform) |
16 | 259x |
frmmat <- mf_formats(matform) |
17 | 259x |
spamat <- mf_spans(matform) |
18 | 259x |
alimat <- mf_aligns(matform) |
19 | 259x |
nr_header <- mf_nrheader(matform) |
20 | 259x |
nl_inds_header <- seq(1, mf_nlheader(matform)) |
21 | 259x |
hdr_inds <- 1:nr_header |
22 | ||
23 |
# hack that is necessary only if top-left is bottom aligned (default) |
|
24 | 259x |
topleft_has_nl_char <- FALSE |
25 | 259x |
if (has_topleft) { |
26 | 3x |
tl <- strmat[nl_inds_header, 1, drop = TRUE] |
27 | 3x |
strmat[nl_inds_header, 1] <- "" |
28 | 3x |
tl <- tl[nzchar(tl)] # we are not interested in initial "" but we cover initial \n |
29 | 3x |
topleft_has_nl_char <- any(grepl("\n", tl)) |
30 | 3x |
tl_to_add_back <- strsplit(paste0(tl, collapse = "\n"), split = "\n", fixed = TRUE)[[1]] |
31 | 3x |
how_many_nl <- length(tl_to_add_back) |
32 |
} |
|
33 | ||
34 |
# pre-proc in case of wrapping and \n |
|
35 | 259x |
line_grouping <- mf_lgrouping(matform) |
36 | 259x |
strmat <- .compress_mat(strmat, line_grouping, "nl") |
37 | 259x |
frmmat <- .compress_mat(frmmat, line_grouping, "unique") # never not unique |
38 | 259x |
spamat <- .compress_mat(spamat, line_grouping, "unique") |
39 | 259x |
alimat <- .compress_mat(alimat, line_grouping, "unique") |
40 | 259x |
line_grouping <- unique(line_grouping) |
41 | ||
42 |
# nlines detects if there is a newline character |
|
43 |
# colwidths = NULL, max_width = NULL, fontspec = NULL |
|
44 |
# because we don't care about wrapping here we're counting lines |
|
45 |
# TODO probably better if we had a nlines_nowrap fun to be more explicit |
|
46 | ||
47 | 259x |
row_nlines <- apply( |
48 | 259x |
strmat, |
49 | 259x |
1, |
50 | 259x |
function(x) { |
51 | 5109x |
max( |
52 | 5109x |
vapply(x, |
53 | 5109x |
nlines, |
54 | 5109x |
colwidths = NULL, |
55 | 5109x |
max_width = NULL, |
56 | 5109x |
fontspec = NULL, 1L |
57 |
), |
|
58 | 5109x |
1L |
59 |
) |
|
60 |
} |
|
61 |
) |
|
62 | ||
63 | ||
64 |
# Correction for the case where there are more lines for topleft material than for cols |
|
65 | 259x |
if (has_topleft && (sum(row_nlines[nl_inds_header]) < how_many_nl)) { |
66 | 1x |
row_nlines[1] <- row_nlines[1] + how_many_nl - sum(row_nlines[nl_inds_header]) |
67 |
} |
|
68 | ||
69 |
# There is something to change |
|
70 | 259x |
if (any(row_nlines > 1) || topleft_has_nl_char) { |
71 |
# False: Padder should be bottom aligned if no topleft (case of rlistings) |
|
72 |
# It is always bottom: tl_padder <- ifelse(has_topleft, pad_vert_top, pad_vert_bottom) |
|
73 | ||
74 | 34x |
newstrmat <- rbind( |
75 | 34x |
cbind( |
76 | 34x |
expand_mat_rows(strmat[hdr_inds, 1, drop = FALSE], |
77 | 34x |
row_nlines[hdr_inds], |
78 | 34x |
cpadder = pad_vert_bottom # topleft info is NOT top aligned |
79 |
), |
|
80 | 34x |
expand_mat_rows(strmat[hdr_inds, -1, drop = FALSE], |
81 | 34x |
row_nlines[hdr_inds], |
82 | 34x |
cpadder = pad_vert_bottom # colnames are bottom aligned |
83 |
) |
|
84 |
), |
|
85 | 34x |
expand_mat_rows(strmat[-1 * hdr_inds, , drop = FALSE], row_nlines[-hdr_inds]) |
86 |
) |
|
87 | ||
88 | 34x |
newfrmmat <- rbind( |
89 | 34x |
expand_mat_rows( |
90 | 34x |
frmmat[hdr_inds, , drop = FALSE], |
91 | 34x |
row_nlines[hdr_inds], |
92 | 34x |
cpadder = pad_vert_bottom |
93 |
), |
|
94 | 34x |
expand_mat_rows(frmmat[-1 * hdr_inds, , drop = FALSE], row_nlines[-hdr_inds]) |
95 |
) |
|
96 | ||
97 | 34x |
if (has_topleft) { |
98 | 3x |
starts_from_ind <- if (sum(row_nlines[hdr_inds]) - how_many_nl > 0) { |
99 | 2x |
sum(row_nlines[hdr_inds]) - how_many_nl |
100 |
} else { |
|
101 | 1x |
0 |
102 |
} |
|
103 | 3x |
newstrmat[starts_from_ind + seq_along(tl_to_add_back), 1] <- tl_to_add_back |
104 |
} |
|
105 | ||
106 | 34x |
mf_strings(matform) <- newstrmat |
107 | 34x |
mf_formats(matform) <- newfrmmat |
108 | 34x |
mf_spans(matform) <- expand_mat_rows(spamat, row_nlines, rep_vec_to_len) |
109 | 34x |
mf_aligns(matform) <- expand_mat_rows(alimat, row_nlines, rep_vec_to_len) |
110 |
## mf_display(matform) <- expand_mat_rows(mf_display(matform), row_nlines, rep_vec_to_len) |
|
111 | 34x |
mf_lgrouping(matform) <- rep(line_grouping, times = row_nlines) |
112 |
} |
|
113 | ||
114 |
# Solve \n in titles |
|
115 | 259x |
if (any(grepl("\n", all_titles(matform)))) { |
116 | 2x |
if (any(grepl("\n", main_title(matform)))) { |
117 | 2x |
tmp_title_vec <- .quick_handle_nl(main_title(matform)) |
118 | 2x |
main_title(matform) <- tmp_title_vec[1] |
119 | 2x |
subtitles(matform) <- c(tmp_title_vec[-1], .quick_handle_nl(subtitles(matform))) |
120 |
} else { |
|
121 | ! |
subtitles(matform) <- .quick_handle_nl(subtitles(matform)) |
122 |
} |
|
123 |
} |
|
124 | ||
125 |
# Solve \n in footers |
|
126 | 259x |
main_footer(matform) <- .quick_handle_nl(main_footer(matform)) |
127 | 259x |
prov_footer(matform) <- .quick_handle_nl(prov_footer(matform)) |
128 | ||
129 |
# xxx \n in page titles are not working atm (I think) |
|
130 | ||
131 | 259x |
matform |
132 |
} |
|
133 | ||
134 |
.quick_handle_nl <- function(str_v) { |
|
135 | 522x |
if (any(grepl("\n", str_v))) { |
136 | 4x |
return(unlist(strsplit(str_v, "\n", fixed = TRUE))) |
137 |
} else { |
|
138 | 518x |
return(str_v) |
139 |
} |
|
140 |
} |
|
141 | ||
142 |
# Helper function to recompact the lines following line groupings to then have them expanded again |
|
143 |
.compress_mat <- function(mat, line_grouping, collapse_method = c("nl", "unique")) { |
|
144 | 1036x |
list_compacted_mat <- lapply(unique(line_grouping), function(lg) { |
145 | 20436x |
apply(mat, 2, function(mat_cols) { |
146 | 175676x |
col_vec <- mat_cols[which(line_grouping == lg)] |
147 | 175676x |
if (collapse_method[1] == "nl") { |
148 | 43919x |
paste0(col_vec, collapse = "\n") |
149 |
} else { |
|
150 | 131757x |
val <- unique(col_vec) |
151 | 131757x |
val <- val[nzchar(val)] |
152 | 131757x |
if (length(val) > 1) { |
153 | 20436x |
stop("Problem in linegroupings! Some do not have the same values.") # nocov |
154 | 131757x |
} else if (length(val) < 1) { |
155 | 5110x |
val <- "" # Case in which it is only "" |
156 |
} |
|
157 | 131757x |
val[[1]] |
158 |
} |
|
159 |
}) |
|
160 |
}) |
|
161 | 1036x |
do.call("rbind", list_compacted_mat) |
162 |
} |
|
163 | ||
164 |
disp_from_spans <- function(spans) { |
|
165 | 401x |
display <- matrix(rep(TRUE, length(spans)), ncol = ncol(spans)) |
166 | ||
167 | 401x |
print_cells_mat <- spans == 1L |
168 | 401x |
if (!all(print_cells_mat)) { |
169 | 1x |
display_rws <- lapply( |
170 | 1x |
seq_len(nrow(spans)), |
171 | 1x |
function(i) { |
172 | 2x |
print_cells <- print_cells_mat[i, ] |
173 | 2x |
row <- spans[i, ] |
174 |
## display <- t(apply(spans, 1, function(row) { |
|
175 |
## print_cells <- row == 1 |
|
176 | ||
177 | 2x |
if (!all(print_cells)) { |
178 |
## need to calculate which cell need to be printed |
|
179 | 1x |
print_cells <- spans_to_viscell(row) |
180 |
} |
|
181 | 2x |
print_cells |
182 |
} |
|
183 |
) |
|
184 | 1x |
display <- do.call(rbind, display_rws) |
185 |
} |
|
186 | 401x |
display |
187 |
} |
|
188 | ||
189 |
#' Constructor for Matrix Print Form |
|
190 |
#' |
|
191 |
#' Constructor for `MatrixPrintForm`, an intermediate representation for ASCII table printing. |
|
192 |
#' |
|
193 |
#' @inheritParams open_font_dev |
|
194 |
#' @param strings (`character matrix`)\cr matrix of formatted, ready-to-display strings |
|
195 |
#' organized as they will be positioned when rendered. Elements that span more than one |
|
196 |
#' column must be followed by the correct number of placeholders (typically either empty |
|
197 |
#' strings or repeats of the value). |
|
198 |
#' @param spans (`numeric matrix`)\cr matrix of same dimension as `strings` giving the |
|
199 |
#' spanning information for each element. Must be repeated to match placeholders in `strings`. |
|
200 |
#' @param aligns (`character matrix`)\cr matrix of same dimension as `strings` giving the text |
|
201 |
#' alignment information for each element. Must be repeated to match placeholders in `strings`. |
|
202 |
#' Must be a supported text alignment. See [decimal_align] for allowed values. |
|
203 |
#' @param formats (`matrix`)\cr matrix of same dimension as `strings` giving the text format |
|
204 |
#' information for each element. Must be repeated to match placeholders in `strings`. |
|
205 |
#' @param row_info (`data.frame`)\cr data frame with row-information necessary for pagination (see |
|
206 |
#' [basic_pagdf()] for more details). |
|
207 |
#' @param colpaths (`list` or `NULL`)\cr `NULL`, or a list of paths to each leaf column, |
|
208 |
#' for use during horizontal pagination. |
|
209 |
#' @param line_grouping (`integer`)\cr sequence of integers indicating how print lines correspond |
|
210 |
#' to semantic rows in the object. Typically this should not be set manually unless |
|
211 |
#' `expand_newlines` is set to `FALSE`. |
|
212 |
#' @param ref_fnotes (`list`)\cr referential footnote information, if applicable. |
|
213 |
#' @param nlines_header (`numeric(1)`)\cr number of lines taken up by the values of the header |
|
214 |
#' (i.e. not including the divider). |
|
215 |
#' @param nrow_header (`numeric(1)`)\cr number of *rows* corresponding to the header. |
|
216 |
#' @param has_topleft (`flag`)\cr does the corresponding table have "top left information" |
|
217 |
#' which should be treated differently when expanding newlines. Ignored if `expand_newlines` |
|
218 |
#' is `FALSE`. |
|
219 |
#' @param has_rowlabs (`flag`)\cr do the matrices (`strings`, `spans`, `aligns`) each contain a |
|
220 |
#' column that corresponds with row labels (rather than with table cell values). Defaults to `TRUE`. |
|
221 |
#' @param main_title (`string`)\cr main title as a string. |
|
222 |
#' @param subtitles (`character`)\cr subtitles, as a character vector. |
|
223 |
#' @param page_titles (`character`)\cr page-specific titles, as a character vector. |
|
224 |
#' @param main_footer (`character`)\cr main footer, as a character vector. |
|
225 |
#' @param prov_footer (`character`)\cr provenance footer information, as a character vector. |
|
226 |
#' @param listing_keycols (`character`)\cr. if matrix form of a listing, this contains |
|
227 |
#' the key columns as a character vector. |
|
228 |
#' @param header_section_div (`string`)\cr divider to be used between header and body sections. |
|
229 |
#' @param horizontal_sep (`string`)\cr horizontal separator to be used for printing divisors |
|
230 |
#' between header and table body and between different footers. |
|
231 |
#' @param expand_newlines (`flag`)\cr whether the matrix form generated should expand rows whose |
|
232 |
#' values contain newlines into multiple 'physical' rows (as they will appear when rendered into |
|
233 |
#' ASCII). Defaults to `TRUE`. |
|
234 |
#' @param col_gap (`numeric(1)`)\cr space (in characters) between columns. |
|
235 |
#' @param table_inset (`numeric(1)`)\cr table inset. See [table_inset()]. |
|
236 |
#' @param colwidths (`numeric` or `NULL`)\cr column rendering widths. If non-`NULL`, must have length |
|
237 |
#' equal to `ncol(strings)`. |
|
238 |
#' @param indent_size (`numeric(1)`)\cr number of spaces to be used per level of indent (if supported by |
|
239 |
#' the relevant method). Defaults to 2. |
|
240 |
#' @param rep_cols (`numeric(1)`)\cr number of columns to be repeated as context during horizontal pagination. |
|
241 |
#' |
|
242 |
#' @return An object of class `MatrixPrintForm`. Currently this is implemented as an S3 class inheriting |
|
243 |
#' from list with the following elements: |
|
244 |
#' \describe{ |
|
245 |
#' \item{`strings`}{see argument.} |
|
246 |
#' \item{`spans`}{see argument.} |
|
247 |
#' \item{`aligns`}{see argument.} |
|
248 |
#' \item{`display`}{logical matrix of same dimension as `strings` that specifies whether an element |
|
249 |
#' in `strings` will be displayed when the table is rendered.} |
|
250 |
#' \item{`formats`}{see argument.} |
|
251 |
#' \item{`row_info`}{see argument.} |
|
252 |
#' \item{`line_grouping`}{see argument.} |
|
253 |
#' \item{`ref_footnotes`}{see argument.} |
|
254 |
#' \item{`main_title`}{see argument.} |
|
255 |
#' \item{`subtitles`}{see argument.} |
|
256 |
#' \item{`page_titles`}{see argument.} |
|
257 |
#' \item{`main_footer`}{see argument.} |
|
258 |
#' \item{`prov_footer`}{see argument.} |
|
259 |
#' \item{`header_section_div`}{see argument.} |
|
260 |
#' \item{`horizontal_sep`}{see argument.} |
|
261 |
#' \item{`col_gap`}{see argument.} |
|
262 |
#' \item{`table_inset`}{see argument.} |
|
263 |
#' } |
|
264 |
#' |
|
265 |
#' as well as the following attributes: |
|
266 |
#' |
|
267 |
#' \describe{ |
|
268 |
#' \item{`nlines_header`}{see argument.} |
|
269 |
#' \item{`nrow_header`}{see argument.} |
|
270 |
#' \item{`ncols`}{number of columns *of the table*, not including any row names/row labels} |
|
271 |
#' } |
|
272 |
#' |
|
273 |
#' @note The bare constructor for the `MatrixPrintForm` should generally |
|
274 |
#' only be called by `matrix_form` custom methods, and almost never from other code. |
|
275 |
#' |
|
276 |
#' @examples |
|
277 |
#' basic_matrix_form(iris) # calls matrix_form which calls this constructor |
|
278 |
#' |
|
279 |
#' @export |
|
280 |
MatrixPrintForm <- function(strings = NULL, |
|
281 |
spans, |
|
282 |
aligns, |
|
283 |
formats, |
|
284 |
row_info, |
|
285 |
colpaths = NULL, |
|
286 |
line_grouping = seq_len(NROW(strings)), |
|
287 |
ref_fnotes = list(), |
|
288 |
nlines_header, |
|
289 |
nrow_header, |
|
290 |
has_topleft = TRUE, |
|
291 |
has_rowlabs = has_topleft, |
|
292 |
expand_newlines = TRUE, |
|
293 |
main_title = "", |
|
294 |
subtitles = character(), |
|
295 |
page_titles = character(), |
|
296 |
listing_keycols = NULL, |
|
297 |
main_footer = "", |
|
298 |
prov_footer = character(), |
|
299 |
header_section_div = NA_character_, |
|
300 |
horizontal_sep = default_hsep(), |
|
301 |
col_gap = 3, |
|
302 |
table_inset = 0L, |
|
303 |
colwidths = NULL, |
|
304 |
indent_size = 2, |
|
305 |
fontspec = font_spec(), |
|
306 |
rep_cols = 0L) { |
|
307 | 50x |
display <- disp_from_spans(spans) |
308 | ||
309 | 50x |
ncs <- if (has_rowlabs) ncol(strings) - 1 else ncol(strings) |
310 | 50x |
ret <- structure( |
311 | 50x |
list( |
312 | 50x |
strings = strings, |
313 | 50x |
spans = spans, |
314 | 50x |
aligns = aligns, |
315 | 50x |
display = display, |
316 | 50x |
formats = formats, |
317 | 50x |
row_info = row_info, |
318 | 50x |
line_grouping = line_grouping, |
319 | 50x |
ref_footnotes = ref_fnotes, |
320 | 50x |
main_title = main_title, |
321 | 50x |
subtitles = subtitles, |
322 | 50x |
page_titles = page_titles, |
323 | 50x |
main_footer = main_footer, |
324 | 50x |
prov_footer = prov_footer, |
325 | 50x |
header_section_div = header_section_div, |
326 | 50x |
horizontal_sep = horizontal_sep, |
327 | 50x |
col_gap = col_gap, |
328 | 50x |
listing_keycols = listing_keycols, |
329 | 50x |
table_inset = as.integer(table_inset), |
330 | 50x |
has_topleft = has_topleft, |
331 | 50x |
indent_size = indent_size, |
332 | 50x |
col_widths = colwidths, |
333 | 50x |
fontspec = fontspec, |
334 | 50x |
num_rep_cols = rep_cols |
335 |
), |
|
336 | 50x |
nrow_header = nrow_header, |
337 | 50x |
ncols = ncs, |
338 | 50x |
class = c("MatrixPrintForm", "list") |
339 |
) |
|
340 | ||
341 |
## .do_mat_expand(ret) |
|
342 | 50x |
if (expand_newlines) { |
343 | 50x |
ret <- mform_handle_newlines(ret) |
344 |
} |
|
345 | ||
346 |
## ret <- shove_refdf_into_rowinfo(ret) |
|
347 | 50x |
if (is.null(colwidths)) { |
348 | 50x |
colwidths <- propose_column_widths(ret, fontspec = fontspec) |
349 |
} |
|
350 | 50x |
mf_col_widths(ret) <- colwidths |
351 | 50x |
ret <- mform_build_refdf(ret) |
352 | 50x |
ret <- mpf_infer_cinfo(ret, colpaths = colpaths, fontspec = fontspec) |
353 | ||
354 | 50x |
ret |
355 |
} |
|
356 | ||
357 |
mf_update_cinfo <- function(mf, colwidths = NULL, rep_cols = NULL) { |
|
358 | 560x |
need_update <- FALSE |
359 | 560x |
if (!is.null(colwidths)) { |
360 | 416x |
mf$col_widths <- colwidths |
361 | 416x |
need_update <- TRUE |
362 |
} |
|
363 | ||
364 | 560x |
if (!is.null(rep_cols)) { |
365 | 144x |
mf$num_rep_cols <- rep_cols |
366 | 144x |
need_update <- TRUE |
367 |
} |
|
368 | ||
369 | 560x |
if (need_update && !is.null(mf_cinfo(mf))) { |
370 | 510x |
cinfo <- mf_cinfo(mf) |
371 | 510x |
r_colwidths <- mf_col_widths(mf) |
372 | 510x |
has_rlabs <- mf_has_rlabels(mf) |
373 | 510x |
if (has_rlabs) { |
374 | 398x |
r_colwidths <- r_colwidths[-1] ## row label widths |
375 |
} |
|
376 | 510x |
cinfo$self_extent <- r_colwidths |
377 | 510x |
nrepcols <- num_rep_cols(mf) |
378 | 510x |
rep_seq <- seq_len(nrepcols) |
379 | 510x |
cinfo$par_extent <- cumsum(c(0, cinfo$self_extent[seq_len(nrepcols)], rep(0, length(r_colwidths) - nrepcols - 1))) |
380 | 510x |
cinfo$reprint_inds <- I(lapply(seq_len(NROW(cinfo)), function(i) rep_seq[rep_seq < i])) |
381 | 510x |
mf_cinfo(mf) <- cinfo |
382 |
} |
|
383 | 560x |
mf |
384 |
} |
|
385 | ||
386 |
#' Create a row for a referential footnote information data frame |
|
387 |
#' |
|
388 |
#' @inheritParams nlines |
|
389 |
#' @param row_path (`character`)\cr row path (or `NA_character_` for none). |
|
390 |
#' @param col_path (`character`)\cr column path (or `NA_character_` for none). |
|
391 |
#' @param row (`integer(1)`)\cr integer position of the row. |
|
392 |
#' @param col (`integer(1)`)\cr integer position of the column. |
|
393 |
#' @param symbol (`string`)\cr symbol for the reference. `NA_character_` to use the |
|
394 |
#' `ref_index` automatically. |
|
395 |
#' @param ref_index (`integer(1)`)\cr index of the footnote, used for ordering even when |
|
396 |
#' symbol is not `NA`. |
|
397 |
#' @param msg (`string`)\cr the string message, not including the symbol portion (`{symbol} - `) |
|
398 |
#' |
|
399 |
#' @return A single row data frame with the appropriate columns. |
|
400 |
#' |
|
401 |
#' @export |
|
402 |
ref_df_row <- function(row_path = NA_character_, |
|
403 |
col_path = NA_character_, |
|
404 |
row = NA_integer_, |
|
405 |
col = NA_integer_, |
|
406 |
symbol = NA_character_, |
|
407 |
ref_index = NA_integer_, |
|
408 |
msg = NA_character_, |
|
409 |
max_width = NULL) { |
|
410 | 6329x |
nlines <- nlines(msg, max_width = max_width) |
411 | 6329x |
data.frame( |
412 | 6329x |
row_path = I(list(row_path)), |
413 | 6329x |
col_path = I(list(col_path)), |
414 | 6329x |
row = row, |
415 | 6329x |
col = col, |
416 | 6329x |
symbol = symbol, |
417 | 6329x |
ref_index = ref_index, |
418 | 6329x |
msg = msg, |
419 | 6329x |
nlines = nlines, |
420 | 6329x |
stringsAsFactors = FALSE |
421 |
) |
|
422 |
} |
|
423 | ||
424 |
## this entire thing is a hatchetjob of a hack which should not be necessary. |
|
425 |
## mf_rinfo(mform) should have the relevant info in it and |
|
426 |
## mf_cinfo(mform) should be non-null (!!!) and have the info in it |
|
427 |
## in which case this becomes silly and dumb, but here we are, so here we go. |
|
428 |
infer_ref_info <- function(mform, colspace_only) { |
|
429 | 200x |
if (colspace_only) { |
430 | 100x |
idx <- seq_len(mf_nlheader(mform)) |
431 |
} else { |
|
432 | 100x |
idx <- seq_len(nrow(mf_strings(mform))) |
433 |
} |
|
434 | ||
435 | 200x |
hasrlbs <- mf_has_rlabels(mform) |
436 | ||
437 | 200x |
strs <- mf_strings(mform)[idx, , drop = FALSE] |
438 | ||
439 |
## they're nested so \\2 is the inner one, without the brackets |
|
440 |
## include space in front of { so we don't catch \{ when |
|
441 |
## rtfs want to pass markup through |
|
442 | 200x |
refs <- gsub("^[^{]*([{]([^}]+)[}]){0,1}$", "\\2", strs) |
443 |
## handle spanned values |
|
444 | 200x |
refs[!mf_display(mform)[idx, ]] <- "" |
445 | ||
446 |
## we want to count across rows first, not down columns, cause |
|
447 |
## thats how footnote numbering works |
|
448 | 200x |
refs_inorder <- as.vector(t(refs)) |
449 | 200x |
keepem <- nzchar(refs_inorder) |
450 | 200x |
if (sum(keepem) == 0) { |
451 | 198x |
return(ref_df_row()[0, ]) |
452 |
} |
|
453 | ||
454 | 2x |
refs_spl <- strsplit(refs_inorder[keepem], ", ", fixed = TRUE) |
455 | 2x |
runvec <- vapply(refs_spl, length, 1L) |
456 | ||
457 | 2x |
row_index <- as.vector( |
458 | 2x |
t(do.call(cbind, replicate(ncol(strs), list(mf_lgrouping(mform)[idx] - mf_nlheader(mform))))) |
459 | 2x |
)[keepem] |
460 | 2x |
row_index[row_index < 1] <- NA_integer_ |
461 | 2x |
c_torep <- if (hasrlbs) c(NA_integer_, seq(1, ncol(strs) - 1)) else seq_len(ncol(strs)) |
462 | 2x |
col_index <- rep(c_torep, nrow(strs))[keepem] |
463 | ||
464 | 2x |
ret <- data.frame( |
465 | 2x |
symbol = unlist(refs_spl), |
466 | 2x |
row_path = I(mf_rinfo(mform)$path[rep(row_index, times = runvec)]), |
467 | 2x |
row = rep(row_index, times = runvec), |
468 | 2x |
col = rep(col_index, times = runvec) |
469 |
) |
|
470 | 2x |
ret$msg <- vapply(ret$symbol, function(sym) { |
471 | 16x |
fullmsg <- unique(grep(paste0("{", sym, "}"), fixed = TRUE, mf_rfnotes(mform), value = TRUE)) |
472 | 16x |
gsub("^[{][^}]+[}] - ", "", fullmsg) |
473 |
}, "") |
|
474 | ||
475 | 2x |
col_pths <- mf_col_paths(mform) |
476 | 2x |
ret$col_path <- replicate(nrow(ret), list(NA_character_)) |
477 | 2x |
non_na_col <- !is.na(ret$col) |
478 | 2x |
ret$col_path[non_na_col] <- col_pths[ret$col[non_na_col]] |
479 | 2x |
ret$ref_index <- match(ret$symbol, unique(ret$symbol)) |
480 |
## |
|
481 | 2x |
ret$nlines <- vapply(paste0("{", ret$symbol, "} - ", ret$msg), nlines, 1L) |
482 | 2x |
ret <- ret[, names(ref_df_row())] |
483 | 2x |
ret |
484 |
} |
|
485 | ||
486 |
mform_build_refdf <- function(mform) { |
|
487 | 100x |
rdf <- mf_rinfo(mform) |
488 | 100x |
cref_rows <- infer_ref_info(mform, colspace_only = TRUE) |
489 |
## this will recheck sometimes but its safer and shouldn't |
|
490 |
## be too prohibitively costly |
|
491 | 100x |
if (NROW(rdf$ref_info_df) > 0 && sum(sapply(rdf$ref_info_df, NROW)) > 0) { |
492 | ! |
cref_rows <- infer_ref_info(mform, colspace_only = TRUE) |
493 | ! |
rref_rows <- rdf$ref_info_df |
494 |
} else { |
|
495 | 100x |
cref_rows <- infer_ref_info(mform, colspace_only = FALSE) |
496 | 100x |
rref_rows <- list() |
497 |
} |
|
498 | 100x |
mf_fnote_df(mform) <- do.call(rbind.data.frame, c(list(cref_rows), rref_rows)) |
499 | 100x |
update_mf_nlines(mform, colwidths = mf_col_widths(mform), max_width = NULL) |
500 |
} |
|
501 | ||
502 |
## hide the implementation behind abstraction in case we decide we want a real class someday |
|
503 |
#' Getters and setters for aspects of `MatrixPrintForm` objects |
|
504 |
#' |
|
505 |
#' Most of these functions, particularly the setters, are intended almost exclusively for |
|
506 |
#' internal use in, e.g., [`matrix_form`] methods, and should generally not be called by end users. |
|
507 |
#' |
|
508 |
#' @param mf (`MatrixPrintForm`)\cr a `MatrixPrintForm` object. |
|
509 |
#' @param value (`ANY`)\cr the new value for the component in question. |
|
510 |
#' |
|
511 |
#' @return |
|
512 |
#' * Getters return the associated element of `mf`. |
|
513 |
#' * Setters return the modified `mf` object. |
|
514 |
#' |
|
515 |
#' @export |
|
516 |
#' @rdname mpf_accessors |
|
517 | 4800x |
mf_strings <- function(mf) mf$strings |
518 | ||
519 |
#' @export |
|
520 |
#' @rdname mpf_accessors |
|
521 | ||
522 | 669x |
mf_spans <- function(mf) mf$spans |
523 |
#' @export |
|
524 |
#' @rdname mpf_accessors |
|
525 | ||
526 | 996x |
mf_aligns <- function(mf) mf$aligns |
527 | ||
528 |
#' @export |
|
529 |
#' @rdname mpf_accessors |
|
530 | 445x |
mf_display <- function(mf) mf$display |
531 | ||
532 |
#' @export |
|
533 |
#' @rdname mpf_accessors |
|
534 | 577x |
mf_formats <- function(mf) mf$formats |
535 | ||
536 |
#' @export |
|
537 |
#' @rdname mpf_accessors |
|
538 | 4663x |
mf_rinfo <- function(mf) mf$row_info |
539 | ||
540 |
#' @export |
|
541 |
#' @rdname mpf_accessors |
|
542 | 1761x |
mf_cinfo <- function(mf) mf$col_info |
543 | ||
544 | ||
545 |
#' @export |
|
546 |
#' @rdname mpf_accessors |
|
547 | 259x |
mf_has_topleft <- function(mf) mf$has_topleft |
548 | ||
549 |
#' @export |
|
550 |
#' @rdname mpf_accessors |
|
551 | 5743x |
mf_lgrouping <- function(mf) mf$line_grouping |
552 | ||
553 |
#' @export |
|
554 |
#' @rdname mpf_accessors |
|
555 | 170x |
mf_rfnotes <- function(mf) mf$ref_footnotes |
556 | ||
557 |
#' @export |
|
558 |
#' @rdname mpf_accessors |
|
559 | 2698x |
mf_nlheader <- function(mf) sum(mf_lgrouping(mf) <= mf_nrheader(mf)) |
560 | ||
561 |
#' @export |
|
562 |
#' @rdname mpf_accessors |
|
563 | 4591x |
mf_nrheader <- function(mf) attr(mf, "nrow_header", exact = TRUE) |
564 | ||
565 |
#' @export |
|
566 |
#' @rdname mpf_accessors |
|
567 | 359x |
mf_colgap <- function(mf) mf$col_gap |
568 | ||
569 |
#' @export |
|
570 |
#' @rdname mpf_accessors |
|
571 | 7x |
mf_fontspec <- function(mf) mf$fontspec |
572 | ||
573 |
#' @export |
|
574 |
#' @rdname mpf_accessors |
|
575 |
`mf_fontspec<-` <- function(mf, value) { |
|
576 | 365x |
mf$fontspec <- value |
577 | 365x |
mf |
578 |
} |
|
579 | ||
580 |
## XXX should this be exported? not sure if there's a point |
|
581 |
mf_col_paths <- function(mf) { |
|
582 | 2x |
if (!is.null(mf_cinfo(mf))) { |
583 | 2x |
mf_cinfo(mf)$path |
584 |
} else { |
|
585 | ! |
as.list(paste0("col", seq_len(nrow(mf_strings(mf)) - mf_has_topleft(mf)))) |
586 |
} |
|
587 |
} |
|
588 | ||
589 |
mf_col_widths <- function(mf) { |
|
590 | 1169x |
mf$col_widths |
591 |
} |
|
592 | ||
593 |
`mf_col_widths<-` <- function(mf, value) { |
|
594 | 411x |
if (!is.null(value) && length(value) != NCOL(mf_strings(mf))) { |
595 | ! |
stop( |
596 | ! |
"Number of column widths (", length(value), ") does not match ", |
597 | ! |
"number of columns in strings matrix (", NCOL(mf_strings(mf)), ")." |
598 |
) |
|
599 |
} |
|
600 | 411x |
mf <- mf_update_cinfo(mf, colwidths = value, rep_cols = NULL) |
601 | 411x |
mf |
602 |
} |
|
603 | ||
604 |
mf_fnote_df <- function(mf) { |
|
605 | 1689x |
mf$ref_fnote_df |
606 |
} |
|
607 | ||
608 |
`mf_fnote_df<-` <- function(mf, value) { |
|
609 | 443x |
stopifnot(is.null(value) || (is.data.frame(value) && identical(names(value), names(ref_df_row())))) |
610 | 443x |
mf$ref_fnote_df <- value |
611 | 443x |
mf |
612 |
} |
|
613 | ||
614 |
splice_fnote_info_in <- function(df, refdf, row = TRUE) { |
|
615 | 393x |
if (NROW(df) == 0) { |
616 | ! |
return(df) |
617 |
} |
|
618 | ||
619 | 393x |
colnm <- ifelse(row, "row", "col") |
620 | 393x |
refdf <- refdf[!is.na(refdf[[colnm]]), ] |
621 | ||
622 | 393x |
refdf_spl <- split(refdf, refdf[[colnm]]) |
623 | 393x |
df$ref_info_df <- replicate(nrow(df), list(ref_df_row()[0, ])) |
624 | 393x |
df$ref_info_df[as.integer(names(refdf_spl))] <- refdf_spl |
625 | 393x |
df |
626 |
} |
|
627 | ||
628 |
shove_refdf_into_rowinfo <- function(mform) { |
|
629 | 343x |
refdf <- mf_fnote_df(mform) |
630 | 343x |
rowinfo <- mf_rinfo(mform) |
631 | 343x |
mf_rinfo(mform) <- splice_fnote_info_in(rowinfo, refdf) |
632 | 343x |
mform |
633 |
} |
|
634 | ||
635 |
update_mf_nlines <- function(mform, colwidths, max_width) { |
|
636 | 307x |
mform <- update_mf_ref_nlines(mform, max_width = max_width) |
637 | 307x |
mform <- update_mf_rinfo_extents(mform) |
638 | ||
639 | 307x |
mform |
640 |
} |
|
641 | ||
642 |
update_mf_rinfo_extents <- function(mform) { |
|
643 | 307x |
rinfo <- mf_rinfo(mform) |
644 | 307x |
refdf_all <- mf_fnote_df(mform) |
645 | 307x |
refdf_rows <- refdf_all[!is.na(refdf_all$row), ] |
646 | 307x |
if (NROW(rinfo) == 0) { |
647 | ! |
return(mform) |
648 |
} |
|
649 | 307x |
lgrp <- mf_lgrouping(mform) - mf_nrheader(mform) |
650 | 307x |
lgrp <- lgrp[lgrp > 0] |
651 | 307x |
rf_nlines <- vapply(seq_len(max(lgrp)), function(ii) { |
652 | 5950x |
refdfii <- refdf_rows[refdf_rows$row == ii, ] |
653 | 5950x |
refdfii <- refdfii[!duplicated(refdfii$symbol), ] |
654 | 5950x |
if (NROW(refdfii) == 0L) { |
655 | 5854x |
return(0L) |
656 |
} |
|
657 | 96x |
sum(refdfii$nlines) |
658 | 307x |
}, 1L) |
659 | ||
660 | 307x |
raw_self_exts <- vapply(split(lgrp, lgrp), length, 0L) |
661 | 307x |
stopifnot(length(raw_self_exts) == length(rf_nlines)) |
662 | 307x |
new_exts <- raw_self_exts + rf_nlines |
663 | ||
664 | 307x |
mapdf <- data.frame( |
665 | 307x |
row_num = as.integer(names(new_exts)), |
666 | 307x |
raw_extent = raw_self_exts |
667 |
) |
|
668 | 307x |
stopifnot(all(mapdf$row_num == rinfo$abs_rownumber)) |
669 | ||
670 | 307x |
new_par_exts <- vapply(rinfo$reprint_inds, function(idx) { |
671 | 5950x |
sum(0L, mapdf$raw_extent[mapdf$row_num %in% idx]) |
672 | 307x |
}, 1L) |
673 | ||
674 | 307x |
rinfo$self_extent <- new_exts |
675 | 307x |
rinfo$par_extent <- new_par_exts |
676 | 307x |
rinfo$nreflines <- rf_nlines |
677 | 307x |
mf_rinfo(mform) <- rinfo |
678 | 307x |
mform |
679 |
} |
|
680 | ||
681 |
update_mf_ref_nlines <- function(mform, max_width) { |
|
682 | 307x |
refdf <- mf_fnote_df(mform) |
683 | 307x |
if (NROW(refdf) == 0) { |
684 | 280x |
return(mform) |
685 |
} |
|
686 | ||
687 | 27x |
refdf$nlines <- vapply( |
688 | 27x |
paste0("{", refdf$symbol, "} - ", refdf$msg), |
689 | 27x |
nlines, |
690 | 27x |
max_width = max_width, |
691 | 27x |
fontspec = mf_fontspec(mform), |
692 | 27x |
1L |
693 |
) |
|
694 | 27x |
mf_fnote_df(mform) <- refdf |
695 | 27x |
shove_refdf_into_rowinfo(mform) |
696 |
} |
|
697 | ||
698 |
#' @export |
|
699 |
#' @rdname mpf_accessors |
|
700 |
`mf_strings<-` <- function(mf, value) { |
|
701 | 793x |
mf$strings <- value |
702 | 793x |
mf |
703 |
} |
|
704 | ||
705 |
.chkdim_and_replace <- function(mf, value, component) { |
|
706 | 1068x |
strdim <- dim(mf_strings(mf)) |
707 | 1068x |
vdim <- dim(value) |
708 | 1068x |
if (!is.null(strdim) && !identical(strdim, vdim)) { |
709 | 1x |
stop( |
710 | 1x |
"Dimensions of new '", component, "' value (", |
711 | 1x |
vdim[1], ", ", vdim[2], # nocov |
712 | 1x |
") do not match dimensions of existing 'strings' component (", # nocov |
713 | 1x |
strdim[1], ", ", strdim[2], ")." # nocov |
714 |
) |
|
715 |
} |
|
716 | 1067x |
mf[[component]] <- value |
717 | 1067x |
mf |
718 |
} |
|
719 | ||
720 |
#' @export |
|
721 |
#' @rdname mpf_accessors |
|
722 |
`mf_spans<-` <- function(mf, value) { |
|
723 | 352x |
mf <- .chkdim_and_replace(mf, value, component = "spans") |
724 | 351x |
mf$display <- disp_from_spans(value) |
725 | 351x |
mf |
726 |
} |
|
727 | ||
728 |
#' @export |
|
729 |
#' @rdname mpf_accessors |
|
730 |
`mf_aligns<-` <- function(mf, value) { |
|
731 | 365x |
.chkdim_and_replace(mf, value, component = "aligns") |
732 |
} |
|
733 | ||
734 |
#' @export |
|
735 |
#' @rdname mpf_accessors |
|
736 |
`mf_display<-` <- function(mf, value) { |
|
737 | ! |
stop("display is now a derived element of the matrix print form, modify it via `mf_spans<-`") |
738 | ! |
.chkdim_and_replace(mf, value, component = "display") |
739 |
} |
|
740 | ||
741 |
#' @export |
|
742 |
#' @rdname mpf_accessors |
|
743 |
`mf_formats<-` <- function(mf, value) { |
|
744 | 351x |
.chkdim_and_replace(mf, value, component = "formats") |
745 |
} |
|
746 | ||
747 |
## NB NROW(v) == length(v) for atomic vectors so this is ok for lgrouping as wellas rinfo |
|
748 |
.chknrow_and_replace <- function(mf, value, component, noheader = FALSE) { |
|
749 | 351x |
strdim <- NROW(mf_strings(mf)) - if (noheader) mf_nlheader(mf) else 0L |
750 | 351x |
vdim <- NROW(value) |
751 | 351x |
if (!is.null(strdim) && !identical(strdim, vdim)) { |
752 | ! |
stop( |
753 | ! |
"Number of rows/length of new '", component, "' value (", |
754 | ! |
vdim[1], |
755 | ! |
") does not match existing 'strings' component (", |
756 | ! |
strdim[1], ")." |
757 |
) |
|
758 |
} |
|
759 | 351x |
mf[[component]] <- value |
760 | 351x |
mf |
761 |
} |
|
762 | ||
763 |
#' @export |
|
764 |
#' @rdname mpf_accessors |
|
765 |
`mf_rinfo<-` <- function(mf, value) { |
|
766 |
## this can someijtmes be called after expanding newlines so in general |
|
767 |
## we should not expect it to match the number of rows in the strings matrix |
|
768 |
## .chknrow_and_replace(mf, value, component = "row_info", noheader = TRUE) |
|
769 | 766x |
lgrps <- mf_lgrouping(mf) |
770 | 766x |
nrs <- length(unique(lgrps[-seq_len(mf_nlheader(mf))])) |
771 | 766x |
if (NROW(value) != nrs) { |
772 | 1x |
stop( |
773 | 1x |
"Rows in new row_info component (", |
774 | 1x |
NROW(value), |
775 | 1x |
") does not match number of rows reflected in line_grouping component (", |
776 | 1x |
nrs, ")" |
777 |
) |
|
778 |
} |
|
779 | 765x |
mf$row_info <- value |
780 | 765x |
mf |
781 |
} |
|
782 | ||
783 |
#' @export |
|
784 |
#' @rdname mpf_accessors |
|
785 |
`mf_cinfo<-` <- function(mf, value) { |
|
786 | 780x |
if (NROW(value) > 0 && NROW(value) != mf_ncol(mf)) { |
787 | ! |
stop( |
788 | ! |
"Number of rows in new cinfo (", NROW(value), ") does not match ", |
789 | ! |
"number of columns (", mf_ncol(mf), ")" |
790 |
) |
|
791 |
} |
|
792 | 780x |
mf$col_info <- value |
793 | 780x |
mf |
794 |
} |
|
795 | ||
796 |
#' @export |
|
797 |
#' @rdname mpf_accessors |
|
798 |
`mf_lgrouping<-` <- function(mf, value) { |
|
799 | 351x |
.chknrow_and_replace(mf, value, component = "line_grouping") |
800 |
} |
|
801 | ||
802 |
#' @export |
|
803 |
#' @rdname mpf_accessors |
|
804 |
`mf_rfnotes<-` <- function(mf, value) { |
|
805 | 321x |
mf$ref_footnotes <- value |
806 | 321x |
mf |
807 |
} |
|
808 | ||
809 |
#' @export |
|
810 |
#' @rdname mpf_accessors |
|
811 |
`mf_nrheader<-` <- function(mf, value) { |
|
812 | 2x |
attr(mf, "nrow_header") <- value |
813 | 2x |
mf |
814 |
} |
|
815 | ||
816 |
#' @export |
|
817 |
#' @rdname mpf_accessors |
|
818 |
`mf_colgap<-` <- function(mf, value) { |
|
819 | 96x |
mf$col_gap <- value |
820 | 96x |
mf |
821 |
} |
|
822 | ||
823 |
#' @export |
|
824 |
#' @rdname mpf_accessors |
|
825 | 2682x |
mf_ncol <- function(mf) attr(mf, "ncols", exact = TRUE) |
826 | ||
827 |
#' @export |
|
828 |
#' @rdname mpf_accessors |
|
829 | 10x |
mf_nrow <- function(mf) max(mf_lgrouping(mf)) - mf_nrheader(mf) |
830 | ||
831 |
#' @export |
|
832 |
#' @rdname mpf_accessors |
|
833 |
`mf_ncol<-` <- function(mf, value) { |
|
834 | 440x |
stopifnot(is.numeric(value)) |
835 | 440x |
attr(mf, "ncols") <- value |
836 | 440x |
mf |
837 |
} |
|
838 | ||
839 |
#' @param x `MatrixPrintForm`. The object. |
|
840 |
#' @export |
|
841 |
#' @rdname mpf_accessors |
|
842 |
setMethod( |
|
843 |
"ncol", "MatrixPrintForm", |
|
844 | 27x |
function(x) mf_ncol(x) |
845 |
) |
|
846 | ||
847 |
#' @export |
|
848 |
#' @rdname mpf_accessors |
|
849 |
mpf_has_rlabels <- function(mf) { |
|
850 | ! |
.Deprecated("mf_has_rlabels") |
851 | ! |
mf_has_rlabels(mf) |
852 |
} |
|
853 | ||
854 |
#' @export |
|
855 |
#' @rdname mpf_accessors |
|
856 | 1338x |
mf_has_rlabels <- function(mf) ncol(mf$strings) > mf_ncol(mf) |
857 | ||
858 |
#' Create spoof matrix form from a data frame |
|
859 |
#' |
|
860 |
#' Useful functions for writing tests and examples, and a starting point for |
|
861 |
#' more sophisticated custom `matrix_form` methods. |
|
862 |
#' |
|
863 |
#' @inheritParams open_font_dev |
|
864 |
#' @param df (`data.frame`)\cr a data frame. |
|
865 |
#' @param indent_rownames (`flag`)\cr whether row names should be indented. Being this |
|
866 |
#' used for testing purposes, it defaults to `FALSE`. If `TRUE`, it assigns label rows |
|
867 |
#' on even lines (also format is `"-"` and value strings are `""`). Indentation works |
|
868 |
#' only if split labels are used (see parameters `split_labels` and `data_labels`). |
|
869 |
#' @param parent_path (`string`)\cr parent path that all rows should be "children of". |
|
870 |
#' Defaults to `NULL`, as usually this is not needed. It may be necessary to use `"root"`, |
|
871 |
#' for some specific scenarios. |
|
872 |
#' @param ignore_rownames (`flag`)\cr whether row names should be ignored. |
|
873 |
#' @param add_decoration (`flag`)\cr whether adds title and footer decorations should |
|
874 |
#' be added to the matrix form. |
|
875 |
#' @param split_labels (`string`)\cr indicates which column to use as split labels. If |
|
876 |
#' `NULL`, no split labels are used. |
|
877 |
#' @param data_labels (`string`)\cr indicates which column to use as data labels. It is |
|
878 |
#' ignored if no `split_labels` is present and is automatically assigned to |
|
879 |
#' `"Analysis method"` when `split_labels` is present, but `data_labels` is `NULL`. |
|
880 |
#' Its direct column name is used as node name in `"DataRow"` pathing. See [mf_rinfo()] |
|
881 |
#' for more information. |
|
882 |
#' @param num_rep_cols (`numeric(1)`)\cr Number of columns to be treated as repeating columns. |
|
883 |
#' Defaults to `0` for `basic_matrix_form` and `length(keycols)` for |
|
884 |
#' `basic_listing_mf`. Note repeating columns are separate from row labels if present. |
|
885 |
#' |
|
886 |
#' @return A valid `MatrixPrintForm` object representing `df` that is ready for |
|
887 |
#' ASCII rendering. |
|
888 |
#' |
|
889 |
#' @details |
|
890 |
#' If some of the column has a [obj_format] assigned, it will be respected for all column |
|
891 |
#' values except for label rows, if present (see parameter `split_labels`). |
|
892 |
#' |
|
893 |
#' @examples |
|
894 |
#' mform <- basic_matrix_form(mtcars) |
|
895 |
#' cat(toString(mform)) |
|
896 |
#' |
|
897 |
#' @examplesIf require("dplyr") |
|
898 |
#' # Advanced test case with label rows |
|
899 |
#' library(dplyr) |
|
900 |
#' iris_output <- iris %>% |
|
901 |
#' group_by(Species) %>% |
|
902 |
#' summarize("all obs" = round(mean(Petal.Length), 2)) %>% |
|
903 |
#' mutate("DataRow_label" = "Mean") |
|
904 |
#' mf <- basic_matrix_form(iris_output, |
|
905 |
#' indent_rownames = TRUE, |
|
906 |
#' split_labels = "Species", data_labels = "DataRow_label" |
|
907 |
#' ) |
|
908 |
#' cat(toString(mf)) |
|
909 |
#' |
|
910 |
#' @name test_matrix_form |
|
911 |
#' @export |
|
912 |
basic_matrix_form <- function(df, |
|
913 |
indent_rownames = FALSE, |
|
914 |
parent_path = NULL, |
|
915 |
ignore_rownames = FALSE, |
|
916 |
add_decoration = FALSE, |
|
917 |
fontspec = font_spec(), |
|
918 |
split_labels = NULL, |
|
919 |
data_labels = NULL, |
|
920 |
num_rep_cols = 0L) { |
|
921 | 48x |
checkmate::assert_data_frame(df) |
922 | 48x |
checkmate::assert_flag(indent_rownames) |
923 | 48x |
checkmate::assert_character(parent_path, null.ok = TRUE) |
924 | 48x |
checkmate::assert_flag(ignore_rownames) |
925 | 48x |
checkmate::assert_flag(add_decoration) |
926 | 48x |
checkmate::assert_character(split_labels, null.ok = TRUE) |
927 | 48x |
checkmate::assert_character(data_labels, null.ok = TRUE) |
928 | ||
929 |
# Some defaults |
|
930 | 48x |
row_classes <- "DataRow" # Default for all rows |
931 | 48x |
data_row_format <- "xx" # Default if no labels are used |
932 | 48x |
indent_size <- 2 |
933 | 48x |
indent_space <- paste0(rep(" ", indent_size), collapse = "") |
934 | ||
935 |
# Pre-processing the fake split |
|
936 | 48x |
if (!is.null(split_labels)) { |
937 | 4x |
checkmate::assert_choice(split_labels, colnames(df)) |
938 | 4x |
label_rows <- as.character(df[[split_labels]]) |
939 | 4x |
if (is.null(data_labels)) { |
940 | ! |
data_rows <- rep("Analysis Method", nrow(df)) |
941 | ! |
data_labels <- "Analyzed Variable" |
942 |
} else { |
|
943 | 4x |
checkmate::assert_choice(data_labels, colnames(df)) |
944 | 4x |
data_rows <- as.character(df[[data_labels]]) |
945 |
} |
|
946 | 4x |
rnms_special <- c(rbind(label_rows, data_rows)) |
947 | 4x |
row_classes <- c(rbind( |
948 | 4x |
rep("LabelRow", length(label_rows)), |
949 | 4x |
rep("DataRow", length(data_rows)) |
950 |
)) |
|
951 | 4x |
data_colnm <- setdiff(colnames(df), c(split_labels, data_labels)) |
952 | 4x |
tmp_df <- NULL |
953 | 4x |
for (col_i in seq_along(data_colnm)) { |
954 | 8x |
lbl_and_dt <- c(rbind(rep("", length(label_rows)), df[[data_colnm[col_i]]])) |
955 | 8x |
tmp_df <- cbind(tmp_df, lbl_and_dt) |
956 |
} |
|
957 | 4x |
colnames(tmp_df) <- data_colnm |
958 | 4x |
rownames(tmp_df) <- NULL |
959 | 4x |
df <- as.data.frame(tmp_df) |
960 | 4x |
ignore_rownames <- FALSE |
961 |
} |
|
962 | ||
963 |
# Formats |
|
964 | 48x |
fmts <- lapply(df, function(x) { |
965 | 288x |
if (is.null(obj_format(x))) { |
966 | 288x |
fmt_tmp <- data_row_format |
967 |
} else { |
|
968 | ! |
fmt_tmp <- obj_format(x) # Can be assigned for each column |
969 |
} |
|
970 | 288x |
out <- rep(fmt_tmp, NROW(df)) |
971 | 288x |
if (!is.null(split_labels)) { |
972 | 8x |
out[row_classes == "LabelRow"] <- "-" |
973 |
} |
|
974 | 288x |
out |
975 |
}) |
|
976 | ||
977 | 48x |
formats <- rbind("", data.frame(fmts)) |
978 | 48x |
if (!ignore_rownames) { |
979 | 38x |
formats <- cbind("rnms" = "", formats) |
980 |
} |
|
981 | ||
982 |
# Strings |
|
983 | 48x |
bodystrs <- mapply(function(x, coli_fmt) { |
984 | 288x |
coli_fmt[coli_fmt == "-"] <- "xx" |
985 | 288x |
sapply(seq_along(x), function(y) { |
986 | 8685x |
format_value(x[y], format = coli_fmt[y]) |
987 |
}) |
|
988 | 48x |
}, x = df, coli_fmt = fmts) |
989 | ||
990 | 48x |
if (!ignore_rownames) { |
991 | 38x |
rnms <- row.names(df) |
992 | 38x |
if (!is.null(split_labels)) { |
993 |
# This overload is done because identical rownames not allowed (e.g. Mean.1 Mean.2) |
|
994 | 4x |
rnms <- rnms_special |
995 | 34x |
} else if (is.null(rnms)) { |
996 | ! |
rnms <- as.character(seq_len(NROW(df))) |
997 |
} |
|
998 |
} |
|
999 | ||
1000 | 48x |
strings <- rbind(colnames(df), bodystrs) |
1001 | ||
1002 | 48x |
rownames(strings) <- NULL |
1003 | 48x |
if (!ignore_rownames) { |
1004 | 38x |
strings <- cbind("rnms" = c("", rnms), strings) |
1005 |
} |
|
1006 |
# colnames(strings) <- NULL # to add after fixing basic_mf for listings |
|
1007 | ||
1008 |
# Spans |
|
1009 | 48x |
spans <- matrix(1, nrow = nrow(strings), ncol = ncol(strings)) |
1010 | ||
1011 |
# Aligns |
|
1012 |
# Default alignment is left for rownames column and center for the rest |
|
1013 | 48x |
aligns <- matrix("center", |
1014 | 48x |
nrow = NROW(strings), |
1015 | 48x |
ncol = NCOL(strings) - as.numeric(!ignore_rownames) |
1016 |
) |
|
1017 | 48x |
if (!ignore_rownames) { |
1018 | 38x |
aligns <- cbind("left", aligns) |
1019 |
} |
|
1020 | ||
1021 |
# Row Info: build up fake pagination df |
|
1022 | 48x |
charcols <- which(sapply(df, is.character)) |
1023 | 48x |
if (length(charcols) > 0) { |
1024 | 11x |
exts <- apply(df[, charcols, drop = FALSE], 1, function(x) max(vapply(x, nlines, fontspec = fontspec, 1L))) |
1025 |
} else { |
|
1026 | 37x |
exts <- rep(1L, NROW(df)) |
1027 |
} |
|
1028 |
# Constructing path roughly |
|
1029 | 48x |
if (!is.null(split_labels)) { |
1030 | 4x |
paths <- lapply( |
1031 | 4x |
seq_along(rnms), |
1032 | 4x |
function(row_path_i) { |
1033 | 24x |
if (row_classes[row_path_i] == "DataRow") { |
1034 | 12x |
c( |
1035 | 12x |
split_labels, |
1036 | 12x |
rnms[row_path_i - 1], # LabelRow before |
1037 | 12x |
data_labels, |
1038 | 12x |
rnms[row_path_i] |
1039 |
) |
|
1040 |
} else { |
|
1041 | 12x |
c(split_labels, rnms[row_path_i]) |
1042 |
} |
|
1043 |
} |
|
1044 |
) |
|
1045 |
} else { |
|
1046 | 44x |
rnms <- row.names(df) |
1047 | 44x |
if (is.null(rnms)) { |
1048 | ! |
rnms <- as.character(seq_len(NROW(df))) |
1049 |
} |
|
1050 | 44x |
paths <- lapply(rnms, function(x) c(parent_path, x)) |
1051 |
} |
|
1052 | 48x |
rowdf <- basic_pagdf( |
1053 | 48x |
rnames = rnms, |
1054 | 48x |
extents = exts, |
1055 | 48x |
rclass = row_classes, |
1056 | 48x |
parent_path = NULL, # Overloaded by above parent_path lapply |
1057 | 48x |
paths = paths |
1058 |
) |
|
1059 | ||
1060 |
# Indentation happens last so to be sure we have all ready (only strings and formats change) |
|
1061 | 48x |
if (indent_rownames && !is.null(split_labels)) { |
1062 | 2x |
where_to_indent <- which(row_classes == "DataRow") + 1 # +1 because of colnames |
1063 | 2x |
strings[where_to_indent, 1] <- paste0(indent_space, strings[where_to_indent, 1]) |
1064 | 2x |
formats[where_to_indent, 1] <- paste0(indent_space, formats[where_to_indent, 1]) # Needs fixing |
1065 | 2x |
rowdf$indent[where_to_indent - 1] <- 1 # -1 because only rows |
1066 |
} |
|
1067 | ||
1068 | 48x |
ret <- MatrixPrintForm( |
1069 | 48x |
strings = strings, |
1070 | 48x |
aligns = aligns, |
1071 | 48x |
spans = spans, |
1072 | 48x |
formats = formats, ## matrix("xx", nrow = fnr, ncol = fnc), |
1073 | 48x |
row_info = rowdf, |
1074 | 48x |
has_topleft = FALSE, |
1075 | 48x |
nlines_header = 1, |
1076 | 48x |
nrow_header = 1, |
1077 | 48x |
has_rowlabs = isFALSE(ignore_rownames), |
1078 | 48x |
fontspec = fontspec, |
1079 | 48x |
col_gap = 3, |
1080 | 48x |
indent_size = indent_size, |
1081 | 48x |
rep_cols = num_rep_cols |
1082 |
) |
|
1083 | ||
1084 |
# Check for ncols |
|
1085 | 48x |
stopifnot(mf_has_rlabels(ret) == isFALSE(ignore_rownames)) |
1086 | ||
1087 | 48x |
ret <- mform_build_refdf(ret) |
1088 | ||
1089 | 48x |
if (add_decoration) { |
1090 | 7x |
main_title(ret) <- "main title" |
1091 | 7x |
main_footer(ret) <- c("main", " footer") |
1092 | 7x |
prov_footer(ret) <- "prov footer" |
1093 | 7x |
subtitles(ret) <- c("sub", "titles") |
1094 |
} |
|
1095 | ||
1096 | 48x |
ret |
1097 |
} |
|
1098 | ||
1099 |
#' @describeIn test_matrix_form Create a `MatrixPrintForm` object from data frame `df` that |
|
1100 |
#' respects the default formats for a listing object. |
|
1101 |
#' |
|
1102 |
#' @param keycols (`character`)\cr a vector of `df` column names that are printed first and for which |
|
1103 |
#' repeated values are assigned `""`. This format is characteristic of a listing matrix form. |
|
1104 |
#' |
|
1105 |
#' @return A valid `MatrixPrintForm` object representing `df` as a listing that is ready for ASCII |
|
1106 |
#' rendering. |
|
1107 |
#' |
|
1108 |
#' @examples |
|
1109 |
#' mform <- basic_listing_mf(mtcars) |
|
1110 |
#' cat(toString(mform)) |
|
1111 |
#' |
|
1112 |
#' @export |
|
1113 |
basic_listing_mf <- function(df, |
|
1114 |
keycols = names(df)[1], |
|
1115 |
add_decoration = TRUE, |
|
1116 |
fontspec = font_spec()) { |
|
1117 | 8x |
checkmate::assert_data_frame(df) |
1118 | 8x |
checkmate::assert_subset(keycols, colnames(df)) |
1119 | ||
1120 | 8x |
dfmf <- basic_matrix_form( |
1121 | 8x |
df = df, |
1122 | 8x |
indent_rownames = FALSE, |
1123 | 8x |
ignore_rownames = TRUE, |
1124 | 8x |
add_decoration = add_decoration, |
1125 | 8x |
num_rep_cols = length(keycols), |
1126 | 8x |
fontspec = fontspec |
1127 |
) |
|
1128 | ||
1129 |
# keycols addition to MatrixPrintForm (should happen in the constructor) |
|
1130 | 8x |
dfmf$listing_keycols <- keycols |
1131 | ||
1132 |
# Modifications needed for making it a listings |
|
1133 | 8x |
mf_strings(dfmf)[1, ] <- colnames(mf_strings(dfmf)) # set colnames |
1134 | ||
1135 | 8x |
if (!is.null(keycols)) { |
1136 | 8x |
str_dfmf <- mf_strings(dfmf)[-1, ] |
1137 |
# Ordering |
|
1138 | 8x |
ord <- do.call( |
1139 | 8x |
order, |
1140 | 8x |
as.list( |
1141 | 8x |
data.frame( |
1142 | 8x |
str_dfmf[, keycols] |
1143 |
) |
|
1144 |
) |
|
1145 |
) |
|
1146 | 8x |
str_dfmf <- str_dfmf[ord, ] |
1147 |
# Making keycols with empties |
|
1148 | 8x |
curkey <- "" |
1149 | 8x |
for (i in seq_along(keycols)) { |
1150 | 15x |
kcol <- keycols[i] |
1151 | 15x |
kcolvec <- str_dfmf[, kcol] # -1 is col label row |
1152 | 15x |
str_dfmf[, kcol] <- "" |
1153 | 15x |
kcolvec <- vapply(kcolvec, format_value, "", format = NULL, na_str = "NA") |
1154 | 15x |
curkey <- paste0(curkey, kcolvec) |
1155 | 15x |
disp <- c(TRUE, tail(curkey, -1) != head(curkey, -1)) |
1156 | 15x |
str_dfmf[disp, kcol] <- kcolvec[disp] |
1157 |
} |
|
1158 | 8x |
mf_strings(dfmf)[-1, ] <- str_dfmf |
1159 |
# keycols as first |
|
1160 | 8x |
mf_strings(dfmf) <- cbind( |
1161 | 8x |
mf_strings(dfmf)[, keycols, drop = FALSE], |
1162 | 8x |
mf_strings(dfmf)[, !colnames(mf_strings(dfmf)) %in% keycols, drop = FALSE] |
1163 |
) |
|
1164 |
} |
|
1165 | ||
1166 | 8x |
dfmf$aligns[seq(2, nrow(dfmf$aligns)), ] <- "center" # the default for listings |
1167 | ||
1168 |
# the default for listings is a 1 double?? |
|
1169 | 8x |
dfmf$formats <- matrix(1, nrow = nrow(dfmf$formats), ncol = ncol(dfmf$formats)) |
1170 | ||
1171 |
# row info |
|
1172 | 8x |
ri <- dfmf$row_info |
1173 | 8x |
rownames(ri) <- ri$abs_rownumber |
1174 | 8x |
ri$label <- ri$name <- "" |
1175 | 8x |
ri$path <- as.list(NA_character_) # same format of listings |
1176 | 8x |
ri$node_class <- "listing_df" |
1177 |
# l_ri$pos_in_siblings # why is it like this in rlistings?? also n_siblings |
|
1178 | 8x |
class(ri$path) <- "AsIs" # Artifact from I() |
1179 | 8x |
dfmf$row_info <- ri |
1180 | ||
1181 |
# colwidths need to be sorted too!! |
|
1182 | 8x |
dfmf$col_widths <- dfmf$col_widths[colnames(mf_strings(dfmf))] |
1183 | ||
1184 | 8x |
if (!add_decoration) { |
1185 |
# This is probably a forced behavior in the original matrix_form in rlistings |
|
1186 | 2x |
main_title(dfmf) <- character() |
1187 | 2x |
main_footer(dfmf) <- character() |
1188 |
} |
|
1189 | ||
1190 | 8x |
dfmf |
1191 |
} |
|
1192 | ||
1193 |
map_to_new <- function(old, map) { |
|
1194 | 412x |
inds <- match(old, map$old_idx) |
1195 | 412x |
map$new_idx[inds] |
1196 |
} |
|
1197 | ||
1198 |
reconstruct_basic_fnote_list <- function(mf) { |
|
1199 | 318x |
refdf <- mf_fnote_df(mf) |
1200 | 318x |
if (NROW(refdf) == 0) { |
1201 | 278x |
return(NULL) |
1202 |
} |
|
1203 | 40x |
refdf <- refdf[!duplicated(refdf$symbol), ] |
1204 | 40x |
paste0("{", refdf$symbol, "} - ", refdf$msg) |
1205 |
} |
|
1206 | ||
1207 |
.mf_subset_core_mats <- function(mf, i, keycols = NULL, row = TRUE) { |
|
1208 | 316x |
fillnum <- if (row) nrow(mf_strings(mf)) - mf_nlheader(mf) else mf_ncol(mf) |
1209 | 316x |
if (is.logical(i) || all(i < 0)) { |
1210 | ! |
i <- seq_len(fillnum)[i] |
1211 |
} |
|
1212 | 316x |
nlh <- mf_nlheader(mf) |
1213 | ||
1214 | 316x |
if (row) { |
1215 | 96x |
ncolrows <- mf_nrheader(mf) |
1216 | 96x |
i_mat <- c(seq_len(nlh), which(mf_lgrouping(mf) %in% (i + ncolrows))) |
1217 | 96x |
j_mat <- seq_len(ncol(mf_strings(mf))) |
1218 |
} else { |
|
1219 | 220x |
nlabcol <- as.integer(mf_has_rlabels(mf)) |
1220 | 220x |
i_mat <- seq_len(nrow(mf_strings(mf))) |
1221 | 220x |
j_mat <- c(seq_len(nlabcol), i + nlabcol) |
1222 |
} |
|
1223 | ||
1224 | 316x |
tmp_strmat <- mf_strings(mf)[i_mat, j_mat, drop = FALSE] |
1225 | ||
1226 |
# Only for listings - Fix pagination with empty values in key columns |
|
1227 | 316x |
if (nrow(tmp_strmat) > 0 && .is_listing_mf(mf)) { # safe check for empty listings |
1228 | 39x |
ind_keycols <- which(colnames(tmp_strmat) %in% keycols) |
1229 | ||
1230 |
# Fix for missing labels in key columns (only for rlistings) |
|
1231 | 39x |
empty_keycols <- !nzchar(tmp_strmat[-seq_len(nlh), ind_keycols, drop = FALSE][1, ]) |
1232 | ||
1233 | 39x |
if (any(empty_keycols)) { # only if there are missing keycol labels |
1234 |
# find the first non-empty label in the key columns |
|
1235 | 6x |
keycols_needed <- mf_strings(mf)[, empty_keycols, drop = FALSE] |
1236 | 6x |
first_nonempty <- apply(keycols_needed, 2, function(x) { |
1237 | 16x |
section_ind <- i_mat[-seq_len(nlh)][1] |
1238 | 16x |
sec_ind_no_header <- seq_len(section_ind)[-seq_len(nlh)] |
1239 | 16x |
tail(x[sec_ind_no_header][nzchar(x[sec_ind_no_header])], 1) |
1240 |
}) |
|
1241 | ||
1242 |
# if there are only "" the previous returns character() |
|
1243 | 6x |
any_chr_empty <- if (length(first_nonempty) > 1) { |
1244 | 6x |
vapply(first_nonempty, length, numeric(1)) |
1245 |
} else { |
|
1246 | ! |
length(first_nonempty) |
1247 |
} |
|
1248 | 6x |
if (any(any_chr_empty == 0L)) { |
1249 | ! |
warning( |
1250 | ! |
"There are empty key columns in the listing. ", |
1251 | ! |
"We keep empty strings for each page." |
1252 |
) |
|
1253 | ! |
first_nonempty[any_chr_empty == 0L] <- "" |
1254 |
} |
|
1255 | ||
1256 |
# replace the empty labels with the first non-empty label |
|
1257 | 6x |
tmp_strmat[nlh + 1, empty_keycols] <- unlist(first_nonempty) |
1258 |
} |
|
1259 |
} |
|
1260 | ||
1261 | 316x |
mf_strings(mf) <- tmp_strmat |
1262 | ||
1263 | 316x |
mf_lgrouping(mf) <- as.integer(as.factor(mf_lgrouping(mf)[i_mat])) |
1264 | ||
1265 | 316x |
if (!row) { |
1266 | 220x |
newspans <- truncate_spans(mf_spans(mf), j_mat) # 'i' is the columns here, bc row is FALSE |
1267 |
} else { |
|
1268 | 96x |
newspans <- mf_spans(mf)[i_mat, j_mat, drop = FALSE] |
1269 |
} |
|
1270 | ||
1271 | 316x |
mf_spans(mf) <- newspans |
1272 | 316x |
mf_formats(mf) <- mf_formats(mf)[i_mat, j_mat, drop = FALSE] |
1273 | ||
1274 | 316x |
mf_aligns(mf) <- mf_aligns(mf)[i_mat, j_mat, drop = FALSE] |
1275 | 316x |
if (!row) { |
1276 | 220x |
mf_ncol(mf) <- length(i) |
1277 | 220x |
if (!is.null(mf_cinfo(mf))) { |
1278 | 220x |
mf_cinfo(mf) <- mf_cinfo(mf)[i, ] |
1279 |
} |
|
1280 | 220x |
if (!is.null(mf_col_widths(mf))) { |
1281 | 220x |
mf_col_widths(mf) <- mf_col_widths(mf)[j_mat] |
1282 |
} |
|
1283 |
} |
|
1284 | 316x |
mf |
1285 |
} |
|
1286 | ||
1287 |
## ugh. spans are **way** more of a pain than I expected x.x |
|
1288 |
truncate_one_span <- function(spanrow, j) { |
|
1289 | 3793x |
i <- 1 |
1290 | 3793x |
len <- length(spanrow) |
1291 | 3793x |
while (i < len) { |
1292 | 41757x |
spnlen <- spanrow[i] |
1293 | 41757x |
inds <- seq(i, i + spnlen - 1) |
1294 | 41757x |
newspnlen <- sum(inds %in% j) |
1295 | 41757x |
spanrow[inds] <- newspnlen |
1296 | 41757x |
i <- i + spnlen |
1297 |
} |
|
1298 | 3793x |
spanrow[j] |
1299 |
} |
|
1300 | ||
1301 |
truncate_spans <- function(spans, j) { |
|
1302 | 220x |
if (length(spans[1, ]) == 1 || length(j) == 1) { |
1303 | ! |
as.matrix(apply(spans, 1, truncate_one_span, j = j)) |
1304 |
} else { |
|
1305 | 220x |
t(apply(spans, 1, truncate_one_span, j = j)) |
1306 |
} |
|
1307 |
} |
|
1308 | ||
1309 |
mpf_subset_rows <- function(mf, i, keycols = NULL) { |
|
1310 | 96x |
nlh <- mf_nlheader(mf) |
1311 | 96x |
lgrps <- mf_lgrouping(mf) |
1312 | 96x |
row_lgrps <- tail(lgrps, -1 * nlh) |
1313 | 96x |
nrs <- length(unique(row_lgrps)) |
1314 | 96x |
ncolrows <- length(unique(lgrps[seq_len(nlh)])) |
1315 | ||
1316 | 96x |
ncs <- mf_ncol(mf) |
1317 | 96x |
mf <- .mf_subset_core_mats(mf, i, keycols = keycols, row = TRUE) |
1318 | 96x |
map <- data.frame( |
1319 | 96x |
old_idx = c(seq_len(ncolrows), i + ncolrows), |
1320 | 96x |
new_idx = c(seq_len(ncolrows), ncolrows + order(i)) |
1321 |
) |
|
1322 | ||
1323 | 96x |
row_map <- data.frame(old_idx = i, new_idx = order(i)) |
1324 | ||
1325 | 96x |
refdf <- mf_fnote_df(mf) |
1326 | ||
1327 | 96x |
old_nas <- is.na(refdf$row) |
1328 | 96x |
refdf$row <- map_to_new(refdf$row, row_map) |
1329 | 96x |
refdf <- refdf[old_nas | !is.na(refdf$row), ] |
1330 | 96x |
mf_fnote_df(mf) <- refdf |
1331 | ||
1332 | 96x |
rinfo <- mf_rinfo(mf) |
1333 | ||
1334 | 96x |
rinfo <- rinfo[rinfo$abs_rownumber %in% i, ] |
1335 | ||
1336 | 96x |
rinfo$abs_rownumber <- map_to_new(rinfo$abs_rownumber, row_map) |
1337 | 96x |
mf_rinfo(mf) <- rinfo |
1338 | ||
1339 | 96x |
mf <- shove_refdf_into_rowinfo(mf) |
1340 | 96x |
mf_rfnotes(mf) <- reconstruct_basic_fnote_list(mf) |
1341 | 96x |
mf |
1342 |
} |
|
1343 | ||
1344 |
## we only care about referential footnotes, cause |
|
1345 |
## they are currently the only place we're tracking |
|
1346 |
## column information that will need to be touched up |
|
1347 |
## but lets be careful and do a bit more anyway |
|
1348 |
mpf_subset_cols <- function(mf, j, keycols = NULL) { |
|
1349 | 220x |
nc <- mf_ncol(mf) |
1350 | 220x |
if (is.logical(j) || all(j < 0)) { |
1351 | ! |
j <- seq_len(nc)[j] |
1352 |
} |
|
1353 | 220x |
if (any(j < 0)) { |
1354 | ! |
stop("cannot mix negative and positive indices") |
1355 |
} |
|
1356 | ||
1357 | 220x |
if (length(unique(j)) != length(j)) { |
1358 | ! |
stop("duplicated columns are not allowed when subsetting a matrix print form objects") |
1359 |
} |
|
1360 | ||
1361 |
# j_mat <- c(if(mf_has_topleft(mf)) seq_len(nlabcol), j + nlabcol) |
|
1362 | 220x |
map <- data.frame(old_idx = j, new_idx = order(j)) |
1363 | ||
1364 |
## this has to happen before the remap inher |
|
1365 | 220x |
refdf <- mf_fnote_df(mf) |
1366 | ||
1367 | 220x |
mf <- .mf_subset_core_mats(mf, j, keycols = keycols, row = FALSE) |
1368 | ||
1369 |
## future proofing (pipe dreams) |
|
1370 |
## uncomment if we ever manage to have col info information on MPFs |
|
1371 |
## if(!is.null(mf_cinfo(mf))) { |
|
1372 |
## cinfo <- mf_cinfo(mf) |
|
1373 |
## cinfo <- cinfo[j, , drop = FALSE] |
|
1374 |
## cinfo$abs_pos <- map_to_new(cinfo$abs_pos, map) |
|
1375 |
## mf_cinfo(mf) <- mf |
|
1376 |
## } |
|
1377 | ||
1378 | 220x |
keep <- is.na(refdf$col) | refdf$col %in% j |
1379 | 220x |
refdf <- refdf[keep, , drop = FALSE] |
1380 | ||
1381 | 220x |
refdf$col <- map_to_new(refdf$col, map) |
1382 | 220x |
mf_fnote_df(mf) <- refdf |
1383 | 220x |
mf <- shove_refdf_into_rowinfo(mf) |
1384 | 220x |
mf_rfnotes(mf) <- reconstruct_basic_fnote_list(mf) |
1385 | 220x |
mf_ncol(mf) <- length(j) |
1386 | 220x |
mf |
1387 |
} |
1 |
#' @import grid |
|
2 |
#' @import grDevices |
|
3 |
NULL |
|
4 |
## https://www.ietf.org/rfc/rfc0678.txt |
|
5 | ||
6 |
times_font_name <- function() { |
|
7 |
## I thought this was going to be OS specific |
|
8 |
## but it seems like it's not... |
|
9 | 4x |
"Times" |
10 |
} |
|
11 | ||
12 |
#' Font size specification |
|
13 |
#' |
|
14 |
#' @param font_family (`character(1)`)\cr font family to use during |
|
15 |
#' string width and lines-per-page calculations. You can specify |
|
16 |
#' "Times New Roman" as "Times" or "serif", regardless of OS. |
|
17 |
#' Beyond that, see `family` entry in [graphics::par()] |
|
18 |
#' for details. |
|
19 |
#' @param font_size (`numeric(1)`)\cr font size to use during string width |
|
20 |
#' calculations and lines-per-page calculations. |
|
21 |
#' @param lineheight (`numeric(1)`)\cr line height to use during |
|
22 |
#' lines-per-page calculations. |
|
23 |
#' |
|
24 |
#' @details Passing the output of this constructor |
|
25 |
#' to the rendering or pagination machinery defines |
|
26 |
#' a font for use when calculating word wrapping and pagination. |
|
27 |
#' |
|
28 |
#' @note Specifying font in this way to, e.g., [export_as_txt()] or |
|
29 |
#' [toString()] will not affect the font size of the output, as these |
|
30 |
#' are both raw text formats. [export_as_pdf()] will use the specified font. |
|
31 |
#' |
|
32 |
#' @seealso [nchar_ttype()], [toString()], [`pagination_algo`], [export_as_pdf()] |
|
33 |
#' |
|
34 |
#' @examples |
|
35 |
#' fspec <- font_spec("Courier", 8, 1) |
|
36 |
#' |
|
37 |
#' lets <- paste(letters, collapse = "") |
|
38 |
#' |
|
39 |
#' nchar_ttype(lets, fspec) |
|
40 |
#' |
|
41 |
#' fspec2 <- font_spec("Times", 8, 1) |
|
42 |
#' |
|
43 |
#' nchar_ttype(lets, fspec2) |
|
44 |
#' |
|
45 |
#' @export |
|
46 |
font_spec <- function(font_family = "Courier", |
|
47 |
font_size = 8, |
|
48 |
lineheight = 1) { |
|
49 | 408x |
if (font_family %in% c("Times New Roman", "Times", "serif")) { |
50 | 4x |
font_family <- times_font_name() |
51 |
} |
|
52 | 408x |
structure( |
53 | 408x |
list( |
54 | 408x |
family = font_family, |
55 | 408x |
size = font_size, |
56 | 408x |
lineheight = lineheight |
57 |
), |
|
58 | 408x |
class = c("font_spec", "list") |
59 |
) |
|
60 |
} |
|
61 |
std_cpi <- 10L |
|
62 |
std_lpi <- 6L |
|
63 | ||
64 |
std_full_pg_wd_in <- 8.5 |
|
65 | ||
66 |
std_full_pg_ht_in <- 11 |
|
67 | ||
68 |
std_log_pg_wd_chars <- 72 |
|
69 | ||
70 |
std_log_pg_ht_lines <- 60 |
|
71 | ||
72 |
std_marg_ht <- round((std_full_pg_ht_in - std_log_pg_ht_lines / std_lpi) / 2, 2) |
|
73 |
std_marg_wd <- round((std_full_pg_wd_in - std_log_pg_wd_chars / std_cpi) / 2, 2) |
|
74 | ||
75 |
std_margins <- list( |
|
76 |
top = std_marg_ht, |
|
77 |
bottom = std_marg_ht, |
|
78 |
left = std_marg_wd, |
|
79 |
right = std_marg_wd |
|
80 |
) |
|
81 | ||
82 |
## does not appear to be used anywhere |
|
83 |
## to_inches_num <- function(x) { |
|
84 |
## if (is(x, "unit")) { |
|
85 |
## x <- unclass(convertUnit(x, "inches")) |
|
86 |
## } |
|
87 |
## x |
|
88 |
## } |
|
89 | ||
90 |
## Physical size, does not take margins into account |
|
91 |
pg_dim_names <- list( |
|
92 |
letter = c(8.5, 11), |
|
93 |
a4 = c(8.27, 11.69), |
|
94 |
legal = c(8.5, 14) |
|
95 |
) |
|
96 | ||
97 |
#' Supported named page types |
|
98 |
#' |
|
99 |
#' List supported named page types. |
|
100 |
#' |
|
101 |
#' @return |
|
102 |
#' * `page_types` returns a character vector of supported page types |
|
103 |
#' * `page_dim` returns the dimensions (width, then height) of the selected page type. |
|
104 |
#' |
|
105 |
#' @export |
|
106 |
#' @examples |
|
107 |
#' page_types() |
|
108 |
#' page_dim("a4") |
|
109 |
page_types <- function() { |
|
110 | 74x |
names(pg_dim_names) |
111 |
} |
|
112 | ||
113 |
#' @param page_type (`string`)\cr the name of a page size specification. Call |
|
114 |
#' [page_types()] for supported values. |
|
115 |
#' |
|
116 |
#' @export |
|
117 |
#' @rdname page_types |
|
118 |
page_dim <- function(page_type) { |
|
119 | 45x |
if (is.null(page_type)) { |
120 | 28x |
return(NULL) |
121 |
} |
|
122 | 17x |
if (!page_type %in% page_types()) { |
123 | 1x |
stop("Unrecognized page-size specification: ", page_type) |
124 |
} |
|
125 | 16x |
pg_dim_names[[page_type]] |
126 |
} |
|
127 | ||
128 |
#' Calculate lines per inch and characters per inch for font |
|
129 |
#' |
|
130 |
#' @inheritParams page_lcpp |
|
131 |
#' |
|
132 |
#' @details |
|
133 |
#' This function opens a PDF graphics device, writes to a temporary file, then |
|
134 |
#' utilizes [grid::convertWidth()] and [grid::convertHeight()] to calculate lines |
|
135 |
#' per inch and characters per inch for the specified font family, size, and |
|
136 |
#' line height. |
|
137 |
#' |
|
138 |
#' An error is thrown if the font is not monospaced (determined by comparing |
|
139 |
#' the effective widths of the `M` and `.` glyphs). |
|
140 |
#' |
|
141 |
#' @return A named list with `cpi` and `lpi`, the characters and lines per |
|
142 |
#' inch, respectively. |
|
143 |
#' |
|
144 |
#' @examples |
|
145 |
#' font_lcpi <- getFromNamespace("font_lcpi", "formatters") |
|
146 |
#' |
|
147 |
#' font_lcpi() |
|
148 |
#' font_lcpi(font_size = 8) |
|
149 |
#' font_lcpi(font_size = 8, lineheight = 1.1) |
|
150 |
#' |
|
151 |
#' @keywords internal |
|
152 |
font_lcpi <- function(font_family = "Courier", |
|
153 |
font_size = 8, |
|
154 |
lineheight = 1, |
|
155 |
fontspec = font_spec(font_family, font_size, lineheight)) { |
|
156 | 58x |
new_dev <- open_font_dev(fontspec) |
157 | 58x |
if (new_dev) { |
158 | 10x |
on.exit(close_font_dev()) |
159 |
} |
|
160 | 58x |
list( |
161 | 58x |
cpi = 1 / convertWidth(unit(1, "strwidth", " "), "inches", valueOnly = TRUE), |
162 | 58x |
lpi = convertHeight(unit(1, "inches"), "lines", valueOnly = TRUE) |
163 |
) |
|
164 |
} |
|
165 | ||
166 |
marg_order <- c("bottom", "left", "top", "right") |
|
167 | ||
168 |
#' Determine lines per page (LPP) and characters per page (CPP) based on font and page type |
|
169 |
#' |
|
170 |
#' @inheritParams open_font_dev |
|
171 |
#' @param page_type (`string`)\cr name of a page type. See [`page_types`]. Ignored |
|
172 |
#' when `pg_width` and `pg_height` are set directly. |
|
173 |
#' @param landscape (`flag`)\cr whether the dimensions of `page_type` should be |
|
174 |
#' inverted for landscape orientation. Defaults to `FALSE`, ignored when `pg_width` and |
|
175 |
#' `pg_height` are set directly. |
|
176 |
#' @param font_family (`string`)\cr name of a font family. An error will be thrown |
|
177 |
#' if the family named is not monospaced. Defaults to `"Courier"`. |
|
178 |
#' @param font_size (`numeric(1)`)\cr font size. Defaults to `12`. |
|
179 |
#' @param lineheight (`numeric(1)`)\cr line height. Defaults to `1`. |
|
180 |
#' @param margins (`numeric(4)`)\cr named numeric vector containing `"bottom"`, `"left"`, |
|
181 |
#' `"top"`, and `"right"` margins in inches. Defaults to `.5` inches for both vertical |
|
182 |
#' margins and `.75` for both horizontal margins. |
|
183 |
#' @param pg_width (`numeric(1)`)\cr page width in inches. |
|
184 |
#' @param pg_height (`numeric(1)`)\cr page height in inches. |
|
185 |
#' |
|
186 |
#' @return A named list containing LPP (lines per page) and CPP (characters per page) |
|
187 |
#' elements suitable for use by the pagination machinery. |
|
188 |
#' |
|
189 |
#' @examples |
|
190 |
#' page_lcpp() |
|
191 |
#' page_lcpp(font_size = 10) |
|
192 |
#' page_lcpp("a4", font_size = 10) |
|
193 |
#' |
|
194 |
#' page_lcpp(margins = c(top = 1, bottom = 1, left = 1, right = 1)) |
|
195 |
#' page_lcpp(pg_width = 10, pg_height = 15) |
|
196 |
#' |
|
197 |
#' @export |
|
198 |
page_lcpp <- function(page_type = page_types(), |
|
199 |
landscape = FALSE, |
|
200 |
font_family = "Courier", |
|
201 |
font_size = 8, |
|
202 |
lineheight = 1, |
|
203 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
204 |
pg_width = NULL, |
|
205 |
pg_height = NULL, |
|
206 |
fontspec = font_spec(font_family, font_size, lineheight)) { |
|
207 | 54x |
if (is.null(page_type)) { |
208 | 19x |
page_type <- page_types()[1] |
209 |
} else { |
|
210 | 35x |
page_type <- match.arg(page_type) |
211 |
} |
|
212 | ||
213 | 54x |
if (is.null(names(margins))) { |
214 | 12x |
names(margins) <- marg_order |
215 |
} else { |
|
216 | 42x |
margins <- margins[marg_order] |
217 |
} |
|
218 | 54x |
if (any(is.na(margins))) { |
219 | ! |
stop("margins argument must have names 'bottom', 'left', 'top' and 'right'.") |
220 |
} |
|
221 | 54x |
lcpi <- font_lcpi(fontspec = fontspec) |
222 | ||
223 | 54x |
wdpos <- ifelse(landscape, 2, 1) |
224 | 54x |
pg_width <- pg_width %||% pg_dim_names[[page_type]][wdpos] |
225 | 54x |
pg_height <- pg_height %||% pg_dim_names[[page_type]][-wdpos] |
226 | ||
227 | 54x |
pg_width <- pg_width - sum(margins[c("left", "right")]) |
228 | 54x |
pg_height <- pg_height - sum(margins[c("top", "bottom")]) |
229 | ||
230 | 54x |
list( |
231 | 54x |
cpp = floor(lcpi[["cpi"]] * pg_width), |
232 | 54x |
lpp = floor(lcpi[["lpi"]] * pg_height) |
233 |
) |
|
234 |
} |
|
235 | ||
236 |
.open_fdev_is_monospace <- function() { |
|
237 |
if (!font_dev_state$open) { |
|
238 |
stop( |
|
239 |
".open_fdev_is_monospace called when font dev state is not open. ", |
|
240 |
"This shouldn't happen, please contact the maintainers." |
|
241 |
) |
|
242 |
} |
|
243 |
font_dev_state$ismonospace |
|
244 |
} |
|
245 | ||
246 |
## safe wrapper around .open_fdev_is_monospace |
|
247 |
is_monospace <- function(font_family = "Courier", |
|
248 |
font_size = 8, |
|
249 |
lineheight = 1, |
|
250 |
fontspec = font_spec( |
|
251 |
font_family, |
|
252 |
font_size, |
|
253 |
lineheight |
|
254 |
)) { |
|
255 |
if (is.null(fontspec)) { |
|
256 |
return(TRUE) |
|
257 |
} |
|
258 |
new_dev <- open_font_dev(fontspec) |
|
259 |
if (new_dev) { |
|
260 |
on.exit(close_font_dev()) |
|
261 |
} |
|
262 |
.open_fdev_is_monospace() |
|
263 |
} |
|
264 | ||
265 |
## pg_types <- list( |
|
266 |
## "fsrp" = c(cpp = 110, lpp = 66), |
|
267 |
## "fsrp8" = c(cpp = 110, lpp = 66), |
|
268 |
## "fsrp7" = c(cpp = 110, lpp = 75), |
|
269 |
## "fsrl" = c(cpp = 149, lpp = 51), |
|
270 |
## "fsrl8" = c(cpp = 149, lpp = 51), |
|
271 |
## "fsrl7" = c(cpp = 150, lpp = 59), |
|
272 |
## "erp" = c(cpp = 96, lpp = 66), |
|
273 |
## "erp8" = c(cpp = 96, lpp = 66), |
|
274 |
## "erl" = c(cpp = 149, lpp = 45), |
|
275 |
## "erl8" = c(cpp = 149, lpp = 45), |
|
276 |
## "sasp" = c(cpp = 93, lpp = 73), |
|
277 |
## "sasp8" = c(cpp = 93, lpp = 73), |
|
278 |
## "sasl" = c(cpp = 134, lpp = 52), |
|
279 |
## "sasl8" = c(cpp = 134, lpp = 52), |
|
280 |
## "sasp7" = c(cpp = 107, lpp = 92), |
|
281 |
## "sasl7" = c(cpp = 154, lpp = 64), |
|
282 |
## "sasp6" = c(cpp = 125, lpp = 108), |
|
283 |
## "sasl6" = c(cpp = 180, lpp = 75), |
|
284 |
## "sasp10" = c(cpp = 78, lpp = 64), |
|
285 |
## "sasl10" = c(cpp = 108, lpp = 45), |
|
286 |
## "sasp9" = c(cpp = 87, lpp = 71), |
|
287 |
## "sasl9" = c(cpp = 120, lpp = 51), |
|
288 |
## "rapidp10" = c(cpp = 78, lpp = 64), |
|
289 |
## "rapidl10" = c(cpp = 108, lpp = 45), |
|
290 |
## "rapidp9" = c(cpp = 87, lpp = 71), |
|
291 |
## "rapidl9" = c(cpp = 120, lpp = 51), |
|
292 |
## "rapidp" = c(cpp = 93, lpp = 73), |
|
293 |
## "rapidp8" = c(cpp = 93, lpp = 73), |
|
294 |
## "rapidl" = c(cpp = 134, lpp = 52), |
|
295 |
## "rapidl8" = c(cpp = 134, lpp = 52), |
|
296 |
## "rapidp7" = c(cpp = 107, lpp = 92), |
|
297 |
## "rapidl7" = c(cpp = 154, lpp = 64), |
|
298 |
## "rapidp6" = c(cpp = 125, lpp = 108), |
|
299 |
## "rapidl6" = c(cpp = 180, lpp = 75), |
|
300 |
## "shibal" = c(cpp = 170, lpp = 48), |
|
301 |
## "shibal10" = c(cpp = 137, lpp = 39), |
|
302 |
## "shibal8" = c(cpp = 170, lpp = 48), |
|
303 |
## "shibal7" = c(cpp = 194, lpp = 56), |
|
304 |
## "shibal6" = c(cpp = 225, lpp = 65), |
|
305 |
## "shibap" = c(cpp = 112, lpp = 78), |
|
306 |
## "shibap10" = c(cpp = 89, lpp = 64), |
|
307 |
## "shibap8" = c(cpp = 112, lpp = 78), |
|
308 |
## "shibap7" = c(cpp = 127, lpp = 92), |
|
309 |
## "shibap6" = c(cpp = 148, lpp = 108)) |
|
310 | ||
311 |
## ~courier_size, ~cpi, ~lpi, |
|
312 |
## 6, floor(129 / pg_dim_names[["letter"]][1]), floor(85 / pg_dim_names[["letter"]][2]), |
|
313 |
## 7, floor(110 / pg_dim_names[["letter"]][1]), floor(76 / pg_dim_names[["letter"]][2]), |
|
314 |
## 8, floor(95 / pg_dim_names[["letter"]][1]), floor(68 / pg_dim_names[["letter"]][2]), |
|
315 |
## 9, floor(84 / pg_dim_names[["letter"]][1]), floor(61 / pg_dim_names[["letter"]][2]), |
|
316 |
## 10, floor(75 / pg_dim_names[["letter"]][1]), floor(56 / pg_dim_names[["letter"]][2]) |
|
317 |
## ) |
|
318 | ||
319 |
## courier_lcpi <- function(size) { |
|
320 |
## grid.newpage() |
|
321 |
## gp <- gpar(fontfamily="Courier New", fontsize = size, lineheight = 1) |
|
322 |
## pushViewport(plotViewport( gp = gp)) |
|
323 |
## list(cpi = round(1/convertWidth(unit(1, "strwidth", "h"), "inches", valueOnly = TRUE), 0), |
|
324 |
## lpi = round(convertHeight(unit(1, "inches"), "lines", valueOnly = TRUE), 0)) |
|
325 |
## } |
1 |
formats_1d <- c( |
|
2 |
"xx", "xx.", "xx.x", "xx.xx", "xx.xxx", "xx.xxxx", |
|
3 |
"xx%", "xx.%", "xx.x%", "xx.xx%", "xx.xxx%", "(N=xx)", "N=xx", ">999.9", ">999.99", |
|
4 |
"x.xxxx | (<0.0001)" |
|
5 |
) |
|
6 | ||
7 |
formats_2d <- c( |
|
8 |
"xx / xx", "xx. / xx.", "xx.x / xx.x", "xx.xx / xx.xx", "xx.xxx / xx.xxx", |
|
9 |
"N=xx (xx%)", "xx (xx%)", "xx (xx.%)", "xx (xx.x%)", "xx (xx.xx%)", |
|
10 |
"xx. (xx.%)", "xx.x (xx.x%)", "xx.xx (xx.xx%)", |
|
11 |
"(xx, xx)", "(xx., xx.)", "(xx.x, xx.x)", "(xx.xx, xx.xx)", |
|
12 |
"(xx.xxx, xx.xxx)", "(xx.xxxx, xx.xxxx)", |
|
13 |
"xx - xx", "xx.x - xx.x", "xx.xx - xx.xx", |
|
14 |
"xx (xx)", "xx. (xx.)", "xx.x (xx.x)", "xx.xx (xx.xx)", |
|
15 |
"xx (xx.)", "xx (xx.x)", "xx (xx.xx)", |
|
16 |
"xx.x, xx.x", |
|
17 |
"xx.x to xx.x" |
|
18 |
) |
|
19 | ||
20 |
formats_3d <- c( |
|
21 |
"xx. (xx. - xx.)", |
|
22 |
"xx.x (xx.x - xx.x)", |
|
23 |
"xx.xx (xx.xx - xx.xx)", |
|
24 |
"xx.xxx (xx.xxx - xx.xxx)" |
|
25 |
) |
|
26 | ||
27 |
#' List of currently supported formats and vertical alignments |
|
28 |
#' |
|
29 |
#' @description We support `xx` style format labels grouped by 1d, 2d, and 3d. |
|
30 |
#' Currently valid format labels cannot be added dynamically. Format functions |
|
31 |
#' must be used for special cases. |
|
32 |
#' |
|
33 |
#' @return |
|
34 |
#' * `list_valid_format_labels()` returns a nested list, with elements listing the supported 1d, 2d, |
|
35 |
#' and 3d format strings. |
|
36 |
#' |
|
37 |
#' @examples |
|
38 |
#' list_valid_format_labels() |
|
39 |
#' |
|
40 |
#' @name list_formats |
|
41 |
#' @export |
|
42 |
list_valid_format_labels <- function() { |
|
43 | 55x |
structure( |
44 | 55x |
list( |
45 | 55x |
"1d" = formats_1d, |
46 | 55x |
"2d" = formats_2d, |
47 | 55x |
"3d" = formats_3d |
48 |
), |
|
49 | 55x |
info = "xx does not modify the element, and xx. rounds a number to 0 digits" |
50 |
) |
|
51 |
} |
|
52 | ||
53 |
#' @return |
|
54 |
#' * `list_valid_aligns()` returns a character vector of valid vertical alignments. |
|
55 |
#' |
|
56 |
#' @examples |
|
57 |
#' list_valid_aligns() |
|
58 |
#' |
|
59 |
#' @name list_formats |
|
60 |
#' @export |
|
61 |
list_valid_aligns <- function() { |
|
62 | 16205x |
c("left", "right", "center", "decimal", "dec_right", "dec_left") |
63 |
} |
|
64 | ||
65 |
#' Check if a format or alignment is supported |
|
66 |
#' |
|
67 |
#' @description Utility functions for checking formats and alignments. |
|
68 |
#' |
|
69 |
#' @param x (`string` or `function`)\cr format string or an object returned by [sprintf_format()] |
|
70 |
#' @param stop_otherwise (`flag`)\cr whether an error should be thrown if `x` is not a valid format. |
|
71 |
#' |
|
72 |
#' @return |
|
73 |
#' * `is_valid_format` returns `TRUE` if `x` is `NULL`, a supported format string, or a function, and |
|
74 |
#' `FALSE` otherwise. |
|
75 |
#' |
|
76 |
#' @note If `x` is a function, no check is performed to verify that it returns a valid format. |
|
77 |
#' |
|
78 |
#' @examples |
|
79 |
#' is_valid_format("xx.x") |
|
80 |
#' is_valid_format("fakeyfake") |
|
81 |
#' |
|
82 |
#' @name check_formats |
|
83 |
#' @export |
|
84 |
is_valid_format <- function(x, stop_otherwise = FALSE) { |
|
85 | 52x |
is_valid <- is.null(x) || (length(x) == 1 && (is.function(x) || x %in% unlist(list_valid_format_labels()))) |
86 | ||
87 | 52x |
if (stop_otherwise && !is_valid) { |
88 | ! |
stop("format needs to be a format label, sprintf_format object, a function, or NULL") |
89 |
} |
|
90 | ||
91 | 52x |
is_valid |
92 |
} |
|
93 | ||
94 |
#' @param algn (`character`)\cr a character vector that indicates the requested cell alignments. |
|
95 |
#' |
|
96 |
#' @return |
|
97 |
#' * `check_aligns` returns `TRUE` if the provided alignments are supported, otherwise, an error is thrown. |
|
98 |
#' |
|
99 |
#' @examples |
|
100 |
#' check_aligns(c("decimal", "dec_right")) |
|
101 |
#' |
|
102 |
#' @name check_formats |
|
103 |
#' @export |
|
104 |
check_aligns <- function(algn) { |
|
105 | ! |
if (anyNA(algn)) { |
106 | ! |
stop("Got missing-value for text alignment.") |
107 |
} |
|
108 | ! |
invalid <- setdiff(algn, list_valid_aligns()) |
109 | ! |
if (length(invalid) > 0) { |
110 | ! |
stop("Unsupported text-alignment(s): ", paste(invalid, collapse = ", ")) |
111 |
} |
|
112 | ! |
invisible(TRUE) |
113 |
} |
|
114 | ||
115 |
#' Specify text format via a `sprintf` format string |
|
116 |
#' |
|
117 |
#' @param format (`string`)\cr a format string passed to [sprintf()]. |
|
118 |
#' |
|
119 |
#' @return A formatting function which wraps and applies the specified `sprintf`-style format |
|
120 |
#' to string `format`. |
|
121 |
#' |
|
122 |
#' @seealso [sprintf()] |
|
123 |
#' |
|
124 |
#' @examples |
|
125 |
#' fmtfun <- sprintf_format("(N=%i") |
|
126 |
#' format_value(100, format = fmtfun) |
|
127 |
#' |
|
128 |
#' fmtfun2 <- sprintf_format("%.4f - %.2f") |
|
129 |
#' format_value(list(12.23456, 2.724)) |
|
130 |
#' |
|
131 |
#' @export |
|
132 |
sprintf_format <- function(format) { |
|
133 | 1x |
function(x, ...) { |
134 | 1x |
do.call(sprintf, c(list(fmt = format), x)) |
135 |
} |
|
136 |
} |
|
137 | ||
138 |
#' Round and prepare a value for display |
|
139 |
#' |
|
140 |
#' This function is used within [format_value()] to prepare numeric values within |
|
141 |
#' cells for formatting and display. |
|
142 |
#' |
|
143 |
#' @param x (`numeric(1)`)\cr value to format. |
|
144 |
#' @param digits (`numeric(1)`)\cr number of digits to round to, or `NA` to convert to a |
|
145 |
#' character value with no rounding. |
|
146 |
#' @param na_str (`string`)\cr the value to return if `x` is `NA`. |
|
147 |
#' |
|
148 |
#' @details |
|
149 |
#' This function combines the rounding behavior of R's standards-compliant [round()] |
|
150 |
#' function (see the Details section of that documentation) with the strict decimal display |
|
151 |
#' of [sprintf()]. The exact behavior is as follows: |
|
152 |
#' |
|
153 |
#' \enumerate{ |
|
154 |
#' \item{If `x` is `NA`, the value of `na_str` is returned.} |
|
155 |
#' \item{If `x` is non-`NA` but `digits` is `NA`, `x` is converted to a character and returned.} |
|
156 |
#' \item{If `x` and `digits` are both non-NA, [round()] is called first, and then [sprintf()] |
|
157 |
#' is used to convert the rounded value to a character with the appropriate number of trailing |
|
158 |
#' zeros enforced.} |
|
159 |
#' } |
|
160 |
#' |
|
161 |
#' @return A character value representing the value after rounding, containing any trailing zeros |
|
162 |
#' required to display *exactly* `digits` elements. |
|
163 |
#' |
|
164 |
#' @note |
|
165 |
#' This differs from the base R [round()] function in that `NA` digits indicate `x` should be converted |
|
166 |
#' to character and returned unchanged whereas `round(x, digits=NA)` returns `NA` for all values of `x`. |
|
167 |
#' |
|
168 |
#' This behavior will differ from `as.character(round(x, digits = digits))` in the case where there are |
|
169 |
#' not at least `digits` significant digits after the decimal that remain after rounding. It *may* differ from |
|
170 |
#' `sprintf("\%.Nf", x)` for values ending in `5` after the decimal place on many popular operating systems |
|
171 |
#' due to `round`'s stricter adherence to the IEC 60559 standard, particularly for R versions > 4.0.0 (see |
|
172 |
#' warning in [round()] documentation). |
|
173 |
#' |
|
174 |
#' @seealso [format_value()], [round()], [sprintf()] |
|
175 |
#' |
|
176 |
#' @examples |
|
177 |
#' round_fmt(0, digits = 3) |
|
178 |
#' round_fmt(.395, digits = 2) |
|
179 |
#' round_fmt(NA, digits = 1) |
|
180 |
#' round_fmt(NA, digits = 1, na_str = "-") |
|
181 |
#' round_fmt(2.765923, digits = NA) |
|
182 |
#' |
|
183 |
#' @export |
|
184 |
#' @aliases rounding |
|
185 |
round_fmt <- function(x, digits, na_str = "NA") { |
|
186 | 208x |
if (!is.na(digits) && digits < 0) { |
187 | ! |
stop("round_fmt currently does not support non-missing values of digits < 0") |
188 |
} |
|
189 | 208x |
if (is.na(x)) { |
190 | 11x |
na_str |
191 | 197x |
} else if (is.na(digits)) { |
192 | 44x |
paste0(x) |
193 |
} else { |
|
194 | 153x |
sprfmt <- paste0("%.", digits, "f") |
195 | 153x |
sprintf(fmt = sprfmt, round(x, digits = digits)) |
196 |
} |
|
197 |
} |
|
198 | ||
199 |
val_pct_helper <- function(x, dig1, dig2, na_str, pct = TRUE) { |
|
200 | 32x |
if (pct) { |
201 | 18x |
x[2] <- x[2] * 100 |
202 |
} |
|
203 | 32x |
if (length(na_str) == 1) { |
204 | ! |
na_str <- rep(na_str, 2) |
205 |
} |
|
206 | 32x |
paste0( |
207 | 32x |
round_fmt(x[1], digits = dig1, na_str = na_str[1]), |
208 |
" (", |
|
209 | 32x |
round_fmt(x[2], digits = dig2, na_str = na_str[2]), |
210 | 32x |
if (pct) "%", ")" |
211 |
) |
|
212 |
} |
|
213 | ||
214 |
sep_2d_helper <- function(x, dig1, dig2, sep, na_str, wrap = NULL) { |
|
215 | 47x |
ret <- paste(mapply(round_fmt, x = x, digits = c(dig1, dig2), na_str = na_str), |
216 | 47x |
collapse = sep |
217 |
) |
|
218 | 47x |
if (!is.null(wrap)) { |
219 | 24x |
ret <- paste(c(wrap[1], ret, wrap[2]), collapse = "") |
220 |
} |
|
221 | 47x |
ret |
222 |
} |
|
223 | ||
224 |
## na_or_round <- function(x, digits, na_str) { |
|
225 |
## if(is.na(x)) |
|
226 |
## na_str |
|
227 |
## else |
|
228 |
## round(x, digits = digits) |
|
229 |
## } |
|
230 | ||
231 |
#' Converts a (possibly compound) value into a string using the `format` information |
|
232 |
#' |
|
233 |
#' @param x (`ANY`)\cr the value to be formatted. |
|
234 |
#' @param format (`string` or `function`)\cr the format label (string) or formatter function to |
|
235 |
#' apply to `x`. |
|
236 |
#' @param na_str (`character`)\cr character vector to display when the values of `x` are missing. |
|
237 |
#' If only one string is provided, it is applied for all missing values. Defaults to `"NA"`. |
|
238 |
#' @param output (`string`)\cr output type. |
|
239 |
#' |
|
240 |
#' @details A length-zero value for `na_str` will be interpreted as `"NA"`. |
|
241 |
#' |
|
242 |
#' @return Formatted text representing the cell `x`. |
|
243 |
#' |
|
244 |
#' @seealso [round_fmt()] |
|
245 |
#' |
|
246 |
#' @examples |
|
247 |
#' x <- format_value(pi, format = "xx.xx") |
|
248 |
#' x |
|
249 |
#' |
|
250 |
#' format_value(x, output = "ascii") |
|
251 |
#' |
|
252 |
#' # na_str works with multiple values |
|
253 |
#' format_value(c(NA, 1, NA), format = "xx.x (xx.x - xx.x)", na_str = c("NE", "<missing>")) |
|
254 |
#' |
|
255 |
#' @export |
|
256 |
format_value <- function(x, format = NULL, output = c("ascii", "html"), na_str = "NA") { |
|
257 |
## if(is(x, "CellValue")) |
|
258 |
## x = x[[1]] |
|
259 | ||
260 | 9137x |
if (length(x) == 0) { |
261 | 1x |
return("") |
262 |
} |
|
263 | ||
264 | 9136x |
output <- match.arg(output) |
265 | ||
266 |
# Checks for NAs in the input |
|
267 | 9136x |
if (length(na_str) == 0) { |
268 | 1x |
na_str <- "NA" |
269 |
} |
|
270 | 9136x |
if (any(is.na(na_str))) { |
271 | 1x |
na_str[is.na(na_str)] <- "NA" |
272 |
} |
|
273 | 9136x |
if (length(na_str) == 1) { |
274 | 9132x |
if (!all(is.na(x))) { |
275 | 9110x |
na_str <- array(na_str, dim = length(x)) |
276 |
} |
|
277 |
} else { # length(na_str) > 1 |
|
278 | 4x |
tmp_na_str <- array("NA", dim = length(x)) |
279 | 4x |
tmp_na_str[is.na(x)] <- na_str[seq(sum(is.na(x)))] |
280 | 4x |
na_str <- tmp_na_str |
281 |
} |
|
282 |
# if (length(na_str) < sum(is.na(x))) { # not a fun of vec recycling |
|
283 |
# na_str <- rep(na_str, length.out = sum(is.na(x))) |
|
284 |
# } |
|
285 | ||
286 | 9136x |
txt <- if (all(is.na(x)) && length(na_str) == 1L) { |
287 | 22x |
na_str |
288 | 9136x |
} else if (is.null(format)) { |
289 | 302x |
toString(x) |
290 | 9136x |
} else if (is.function(format)) { |
291 | 1x |
format(x, output = output) |
292 | 9136x |
} else if (is.character(format)) { |
293 | 8811x |
l <- if (format %in% formats_1d) { |
294 | 8729x |
1 |
295 | 8811x |
} else if (format %in% formats_2d) { |
296 | 69x |
2 |
297 | 8811x |
} else if (format %in% formats_3d) { |
298 | 12x |
3 |
299 |
} else { |
|
300 | 1x |
stop( |
301 | 1x |
"Unknown format label: '", format, |
302 | 1x |
"'. Run `list_valid_format_labels()` to get a list of all available formats." |
303 |
) |
|
304 |
} |
|
305 | 8810x |
if (format != "xx" && length(x) != l) { |
306 | 2x |
stop( |
307 | 2x |
"Cell contents <", paste(x, collapse = ", "), "> and format '", |
308 | 2x |
format, "' are of different lengths (", length(x), " vs ", l, ")." |
309 |
) |
|
310 |
} |
|
311 | 8808x |
switch(format, |
312 | 8688x |
"xx" = as.character(x), |
313 | 3x |
"xx." = round_fmt(x, digits = 0, na_str = na_str), |
314 | 6x |
"xx.x" = round_fmt(x, digits = 1, na_str = na_str), |
315 | 3x |
"xx.xx" = round_fmt(x, digits = 2, na_str = na_str), |
316 | 3x |
"xx.xxx" = round_fmt(x, digits = 3, na_str = na_str), |
317 | 3x |
"xx.xxxx" = round_fmt(x, digits = 4, na_str = na_str), |
318 | 2x |
"xx%" = paste0(round_fmt(x * 100, digits = NA, na_str = na_str), "%"), |
319 | 2x |
"xx.%" = paste0(round_fmt(x * 100, digits = 0, na_str = na_str), "%"), |
320 | 2x |
"xx.x%" = paste0(round_fmt(x * 100, digits = 1, na_str = na_str), "%"), |
321 | 2x |
"xx.xx%" = paste0(round_fmt(x * 100, digits = 2, na_str = na_str), "%"), |
322 | 2x |
"xx.xxx%" = paste0(round_fmt(x * 100, digits = 3, na_str = na_str), "%"), |
323 | 2x |
"(N=xx)" = paste0("(N=", round_fmt(x, digits = NA, na_str = na_str), ")"), |
324 | 2x |
"N=xx" = paste0("N=", round_fmt(x, digits = NA, na_str = na_str)), |
325 | 3x |
">999.9" = ifelse(x > 999.9, ">999.9", round_fmt(x, digits = 1, na_str = na_str)), |
326 | 3x |
">999.99" = ifelse(x > 999.99, ">999.99", round_fmt(x, digits = 2, na_str = na_str)), |
327 | 3x |
"x.xxxx | (<0.0001)" = ifelse(x < 0.0001, "<0.0001", round_fmt(x, digits = 4, na_str = na_str)), |
328 | 2x |
"xx / xx" = sep_2d_helper(x, dig1 = NA, dig2 = NA, sep = " / ", na_str = na_str), |
329 | 2x |
"xx. / xx." = sep_2d_helper(x, dig1 = 0, dig2 = 0, sep = " / ", na_str = na_str), |
330 | 2x |
"xx.x / xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = " / ", na_str = na_str), |
331 | 2x |
"xx.xx / xx.xx" = sep_2d_helper(x, dig1 = 2, dig2 = 2, sep = " / ", na_str = na_str), |
332 | 2x |
"xx.xxx / xx.xxx" = sep_2d_helper(x, dig1 = 3, dig2 = 3, sep = " / ", na_str = na_str), |
333 | 2x |
"N=xx (xx%)" = paste0("N=", val_pct_helper(x, dig1 = NA, dig2 = NA, na_str = na_str)), |
334 | 3x |
"xx (xx%)" = val_pct_helper(x, dig1 = NA, dig2 = NA, na_str = na_str), |
335 | 2x |
"xx (xx.%)" = val_pct_helper(x, dig1 = NA, dig2 = 0, na_str = na_str), |
336 | 2x |
"xx (xx.x%)" = val_pct_helper(x, dig1 = NA, dig2 = 1, na_str = na_str), |
337 | 2x |
"xx (xx.xx%)" = val_pct_helper(x, dig1 = NA, dig2 = 2, na_str = na_str), |
338 | 2x |
"xx. (xx.%)" = val_pct_helper(x, dig1 = 0, dig2 = 0, na_str = na_str), |
339 | 3x |
"xx.x (xx.x%)" = val_pct_helper(x, dig1 = 1, dig2 = 1, na_str = na_str), |
340 | 2x |
"xx.xx (xx.xx%)" = val_pct_helper(x, dig1 = 2, dig2 = 2, na_str = na_str), |
341 | 2x |
"(xx, xx)" = sep_2d_helper(x, |
342 | 2x |
dig1 = NA, dig2 = NA, sep = ", ", |
343 | 2x |
na_str = na_str, wrap = c("(", ")") |
344 |
), |
|
345 | 2x |
"(xx., xx.)" = sep_2d_helper(x, |
346 | 2x |
dig1 = 0, dig2 = 0, sep = ", ", |
347 | 2x |
na_str = na_str, wrap = c("(", ")") |
348 |
), |
|
349 | 2x |
"(xx.x, xx.x)" = sep_2d_helper(x, |
350 | 2x |
dig1 = 1, dig2 = 1, sep = ", ", |
351 | 2x |
na_str = na_str, wrap = c("(", ")") |
352 |
), |
|
353 | 2x |
"(xx.xx, xx.xx)" = sep_2d_helper(x, |
354 | 2x |
dig1 = 2, dig2 = 2, sep = ", ", |
355 | 2x |
na_str = na_str, wrap = c("(", ")") |
356 |
), |
|
357 | 2x |
"(xx.xxx, xx.xxx)" = sep_2d_helper(x, |
358 | 2x |
dig1 = 3, dig2 = 3, sep = ", ", |
359 | 2x |
na_str = na_str, wrap = c("(", ")") |
360 |
), |
|
361 | 2x |
"(xx.xxxx, xx.xxxx)" = sep_2d_helper(x, |
362 | 2x |
dig1 = 4, dig2 = 4, sep = ", ", |
363 | 2x |
na_str = na_str, wrap = c("(", ")") |
364 |
), |
|
365 | 2x |
"xx - xx" = sep_2d_helper(x, dig1 = NA, dig2 = NA, sep = " - ", na_str = na_str), |
366 | 5x |
"xx.x - xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = " - ", na_str = na_str), |
367 | 2x |
"xx.xx - xx.xx" = sep_2d_helper(x, dig1 = 2, dig2 = 2, sep = " - ", na_str = na_str), |
368 | 2x |
"xx (xx)" = val_pct_helper(x, dig1 = NA, dig2 = NA, na_str = na_str, pct = FALSE), |
369 | 2x |
"xx. (xx.)" = val_pct_helper(x, dig1 = 0, dig2 = 0, na_str = na_str, pct = FALSE), |
370 | 2x |
"xx.x (xx.x)" = val_pct_helper(x, dig1 = 1, dig2 = 1, na_str = na_str, pct = FALSE), |
371 | 2x |
"xx.xx (xx.xx)" = val_pct_helper(x, dig1 = 2, dig2 = 2, na_str = na_str, pct = FALSE), |
372 | 2x |
"xx (xx.)" = val_pct_helper(x, dig1 = NA, dig2 = 0, na_str = na_str, pct = FALSE), |
373 | 2x |
"xx (xx.x)" = val_pct_helper(x, dig1 = NA, dig2 = 1, na_str = na_str, pct = FALSE), |
374 | 2x |
"xx (xx.xx)" = val_pct_helper(x, dig1 = NA, dig2 = 2, na_str = na_str, pct = FALSE), |
375 | 2x |
"xx.x, xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = ", ", na_str = na_str), |
376 | 2x |
"xx.x to xx.x" = sep_2d_helper(x, dig1 = 1, dig2 = 1, sep = " to ", na_str = na_str), |
377 | 2x |
"xx.xx (xx.xx - xx.xx)" = paste0( |
378 | 2x |
round_fmt(x[1], digits = 2, na_str = na_str[1]), " ", |
379 | 2x |
sep_2d_helper(x[2:3], |
380 | 2x |
dig1 = 2, dig2 = 2, |
381 | 2x |
sep = " - ", na_str = na_str[2:3], |
382 | 2x |
wrap = c("(", ")") |
383 |
) |
|
384 |
), |
|
385 | 2x |
"xx. (xx. - xx.)" = paste0( |
386 | 2x |
round_fmt(x[1], digits = 0, na_str = na_str[1]), " ", |
387 | 2x |
sep_2d_helper(x[2:3], |
388 | 2x |
dig1 = 0, dig2 = 0, |
389 | 2x |
sep = " - ", na_str = na_str[2:3], |
390 | 2x |
wrap = c("(", ")") |
391 |
) |
|
392 |
), |
|
393 | 6x |
"xx.x (xx.x - xx.x)" = paste0( |
394 | 6x |
round_fmt(x[1], digits = 1, na_str = na_str[1]), " ", |
395 | 6x |
sep_2d_helper(x[2:3], |
396 | 6x |
dig1 = 1, dig2 = 1, |
397 | 6x |
sep = " - ", na_str = na_str[2:3], |
398 | 6x |
wrap = c("(", ")") |
399 |
) |
|
400 |
), |
|
401 | 2x |
"xx.xxx (xx.xxx - xx.xxx)" = paste0( |
402 | 2x |
round_fmt(x[1], digits = 3, na_str = na_str[1]), " ", |
403 | 2x |
sep_2d_helper(x[2:3], |
404 | 2x |
dig1 = 3, dig2 = 3, |
405 | 2x |
sep = " - ", na_str = na_str[2:3], |
406 | 2x |
wrap = c("(", ")") |
407 |
) |
|
408 |
), |
|
409 | ! |
paste("format string", format, "not found") |
410 |
) |
|
411 |
} |
|
412 |
# Check that probably never happens as it is almost always already text |
|
413 | 9133x |
txt[is.na(txt)] <- na_str[1] |
414 | ||
415 | ||
416 | 9133x |
if (output == "ascii") { |
417 | 9132x |
txt |
418 | 1x |
} else if (output == "html") { |
419 |
## convert to tagList |
|
420 |
## convert \n to <br/> |
|
421 | ||
422 | 1x |
if (identical(txt, "")) { |
423 | ! |
txt |
424 |
} else { |
|
425 | 1x |
els <- unlist(strsplit(txt, "\n", fixed = TRUE)) |
426 | 1x |
Map(function(el, is.last) { |
427 | 1x |
tagList(el, if (!is.last) tags$br() else NULL) |
428 | 1x |
}, els, c(rep(FALSE, length(els) - 1), TRUE)) |
429 |
} |
|
430 |
} else { |
|
431 | ! |
txt |
432 |
} |
|
433 |
} |
|
434 | ||
435 |
setClassUnion("FormatSpec", c("NULL", "character", "function", "list")) |
|
436 |
setClassUnion("characterOrNULL", c("NULL", "character")) |
|
437 |
setClass("fmt_config", |
|
438 |
slots = c( |
|
439 |
format = "FormatSpec", |
|
440 |
format_na_str = "characterOrNULL", |
|
441 |
align = "characterOrNULL" |
|
442 |
) |
|
443 |
) |
|
444 | ||
445 |
#' Format configuration |
|
446 |
#' |
|
447 |
#' @param format (`string` or `function`)\cr a format label (string) or formatter function. |
|
448 |
#' @param na_str (`string`)\cr string that should be displayed in place of missing values. |
|
449 |
#' @param align (`string`)\cr alignment values should be rendered with. |
|
450 |
#' |
|
451 |
#' @return An object of class `fmt_config` which contains the following elements: |
|
452 |
#' * `format` |
|
453 |
#' * `na_str` |
|
454 |
#' * `align` |
|
455 |
#' |
|
456 |
#' @examples |
|
457 |
#' fmt_config(format = "xx.xx", na_str = "-", align = "left") |
|
458 |
#' fmt_config(format = "xx.xx - xx.xx", align = "right") |
|
459 |
#' |
|
460 |
#' @export |
|
461 |
fmt_config <- function(format = NULL, na_str = "NA", align = "center") { |
|
462 | 2x |
new("fmt_config", format = format, format_na_str = na_str, align = align) |
463 |
} |
1 |
.need_pag <- function(page_type, pg_width, pg_height, cpp, lpp) { |
|
2 | ! |
!(is.null(page_type) && is.null(pg_width) && is.null(pg_height) && is.null(cpp) && is.null(lpp)) |
3 |
} |
|
4 | ||
5 |
#' Export a table-like object to plain (ASCII) text with page breaks |
|
6 |
#' |
|
7 |
#' This function converts `x` to a `MatrixPrintForm` object via [matrix_form()], paginates it |
|
8 |
#' via [paginate_to_mpfs()], converts each page to ASCII text via [toString()], and outputs |
|
9 |
#' the strings, separated by `page_break`, to `file`. |
|
10 |
#' |
|
11 |
#' @inheritParams paginate_indices |
|
12 |
#' @inheritParams toString |
|
13 |
#' @inheritParams propose_column_widths |
|
14 |
#' @param x (`ANY`)\cr a table-like object to export. Must have an applicable `matrix_form` method. |
|
15 |
#' @param file (`string` or `NULL`)\cr if non-`NULL`, the path to write a text file to |
|
16 |
#' containing `x` rendered as ASCII text. |
|
17 |
#' @param page_break (`string`)\cr page break symbol (defaults to `"\\n\\s"`). |
|
18 |
#' @param paginate (`flag`)\cr whether pagination should be performed. Defaults to `TRUE` |
|
19 |
#' if page size is specified (including the default). |
|
20 |
#' @param ... additional parameters passed to [paginate_to_mpfs()]. |
|
21 |
#' |
|
22 |
#' @details |
|
23 |
#' If `x` has a `num_rep_cols` method, the value returned by it will be used for `rep_cols` by |
|
24 |
#' default. Otherwise, 0 will be used. |
|
25 |
#' |
|
26 |
#' If `x` has an applicable `do_forced_paginate` method, it will be invoked during the |
|
27 |
#' pagination process. |
|
28 |
#' |
|
29 |
#' @return If `file` is `NULL`, the full paginated and concatenated string value is returned, |
|
30 |
#' otherwise the output is written to `file` and no value (invisible `NULL`) is returned. |
|
31 |
#' |
|
32 |
#' @examples |
|
33 |
#' export_as_txt(basic_matrix_form(mtcars), pg_height = 5, pg_width = 4) |
|
34 |
#' |
|
35 |
#' @export |
|
36 |
export_as_txt <- function(x, |
|
37 |
file = NULL, |
|
38 |
page_type = NULL, |
|
39 |
landscape = FALSE, |
|
40 |
pg_width = page_dim(page_type)[if (landscape) 2 else 1], |
|
41 |
pg_height = page_dim(page_type)[if (landscape) 1 else 2], |
|
42 |
font_family = "Courier", |
|
43 |
font_size = 8, # grid parameters |
|
44 |
lineheight = 1L, |
|
45 |
margins = c(top = .5, bottom = .5, left = .75, right = .75), |
|
46 |
paginate = TRUE, |
|
47 |
cpp = NA_integer_, |
|
48 |
lpp = NA_integer_, |
|
49 |
..., |
|
50 |
hsep = NULL, |
|
51 |
indent_size = 2, |
|
52 |
tf_wrap = paginate, |
|
53 |
max_width = NULL, |
|
54 |
colwidths = NULL, |
|
55 |
min_siblings = 2, |
|
56 |
nosplitin = character(), |
|
57 |
rep_cols = NULL, |
|
58 |
verbose = FALSE, |
|
59 |
page_break = "\\s\\n", |
|
60 |
page_num = default_page_number(), |
|
61 |
fontspec = font_spec(font_family, font_size, lineheight), |
|
62 |
col_gap = 3) { |
|
63 |
# Processing lists of tables or listings |
|
64 | 15x |
if (.is_list_of_tables_or_listings(x)) { |
65 | 5x |
if (isFALSE(paginate)) { |
66 | 1x |
warning( |
67 | 1x |
"paginate is FALSE, but x is a list of tables or listings, ", |
68 | 1x |
"so paginate will automatically be updated to TRUE" |
69 |
) |
|
70 |
} |
|
71 | 5x |
paginate <- TRUE |
72 |
} |
|
73 | ||
74 | 15x |
if (paginate) { |
75 | 15x |
pages <- paginate_to_mpfs( |
76 | 15x |
x, |
77 | 15x |
page_type = page_type, |
78 |
## font_family = font_family, |
|
79 |
## font_size = font_size, |
|
80 |
## lineheight = lineheight, |
|
81 | 15x |
landscape = landscape, |
82 | 15x |
pg_width = pg_width, |
83 | 15x |
pg_height = pg_height, |
84 | 15x |
margins = margins, |
85 | 15x |
lpp = lpp, |
86 | 15x |
cpp = cpp, |
87 | 15x |
min_siblings = min_siblings, |
88 | 15x |
nosplitin = nosplitin, |
89 | 15x |
colwidths = colwidths, |
90 | 15x |
tf_wrap = tf_wrap, |
91 | 15x |
max_width = max_width, |
92 | 15x |
indent_size = indent_size, |
93 | 15x |
verbose = verbose, |
94 | 15x |
rep_cols = rep_cols, |
95 | 15x |
page_num = page_num, |
96 | 15x |
fontspec = fontspec, |
97 | 15x |
col_gap = col_gap |
98 |
) |
|
99 |
} else { |
|
100 | ! |
mf <- matrix_form(x, TRUE, TRUE, indent_size = indent_size, fontspec = fontspec, col_gap = col_gap) |
101 | ! |
mf_col_widths(mf) <- colwidths %||% propose_column_widths(mf, fontspec = fontspec) |
102 | ! |
pages <- list(mf) |
103 |
} |
|
104 | ||
105 |
# Needs to be here because of adding cpp if it is not "auto" |
|
106 | 14x |
if (!is.character(max_width)) { |
107 | 14x |
max_width <- .handle_max_width( |
108 | 14x |
tf_wrap = tf_wrap, |
109 | 14x |
max_width = max_width, |
110 | 14x |
cpp = cpp |
111 |
) |
|
112 |
} |
|
113 | ||
114 |
## we don't set widths here because we already put that info in mpf |
|
115 |
## so its on each of the pages. |
|
116 | 14x |
strings <- vapply( |
117 | 14x |
pages, toString, "", |
118 | 14x |
widths = NULL, |
119 | 14x |
hsep = hsep, tf_wrap = tf_wrap, max_width = max_width, col_gap = col_gap |
120 |
) |
|
121 | ||
122 | 14x |
res <- paste(strings, collapse = page_break) |
123 | ||
124 | 14x |
if (is.null(file)) { |
125 | 12x |
res |
126 |
} else { |
|
127 | 2x |
cat(res, file = file) |
128 |
} |
|
129 |
} |
|
130 | ||
131 |
.is_list_of_tables_or_listings <- function(a_list) { |
|
132 | 80x |
if (is(a_list, "list")) { |
133 | 80x |
all_matrix_forms <- FALSE |
134 | 80x |
obj_are_tables_or_listings <- FALSE |
135 | ||
136 | 80x |
if (is(a_list[[1]], "MatrixPrintForm")) { |
137 | 15x |
all_matrix_forms <- all(sapply(a_list, is, class2 = "MatrixPrintForm")) |
138 |
} else { |
|
139 | 65x |
obj_are_tables_or_listings <- all( |
140 | 65x |
sapply(a_list, function(list_i) { |
141 | 1625x |
is(list_i, "listing_df") || is(list_i, "VTableTree") |
142 |
}) |
|
143 |
) |
|
144 |
} |
|
145 | 80x |
out <- obj_are_tables_or_listings || all_matrix_forms |
146 |
} else { |
|
147 | ! |
out <- FALSE |
148 |
} |
|
149 | ||
150 | 80x |
out |
151 |
} |
|
152 | ||
153 |
# RTF support ------------------------------------------------------------------ |
|
154 | ||
155 |
## In use, must be tested |
|
156 |
prep_header_line <- function(mf, i) { |
|
157 | 4x |
ret <- mf$strings[i, mf$display[i, , drop = TRUE], drop = TRUE] |
158 | 4x |
ret |
159 |
} |
|
160 | ||
161 |
## margin_lines_to_in <- function(margins, font_size, font_family) { |
|
162 |
## tmpfile <- tempfile(fileext = ".pdf") |
|
163 |
## gp_plot <- gpar(fontsize = font_size, fontfamily = font_family) |
|
164 |
## pdf(file = tmpfile, width = 20, height = 20) |
|
165 |
## on.exit({ |
|
166 |
## dev.off() |
|
167 |
## file.remove(tmpfile) |
|
168 |
## }) |
|
169 |
## grid.newpage() |
|
170 |
## pushViewport(plotViewport(margins = margins, gp = gp_plot)) |
|
171 |
## c( |
|
172 |
## bottom = convertHeight(unit(margins["bottom"], "lines"), "inches", valueOnly = TRUE), |
|
173 |
## left = convertWidth(unit(1, "strwidth", strrep("m", margins["left"])), "inches", valueOnly = TRUE), |
|
174 |
## top = convertHeight(unit(margins["top"], "lines"), "inches", valueOnly = TRUE), |
|
175 |
## right = convertWidth(unit(1, "strwidth", strrep("m", margins["right"])), "inches", valueOnly = TRUE) |
|
176 |
## ) |
|
177 |
## } |
|
178 | ||
179 |
mpf_to_dfbody <- function(mpf, colwidths, fontspec) { |
|
180 | 4x |
mf <- matrix_form(mpf, indent_rownames = TRUE, fontspec = fontspec) |
181 | 4x |
nlr <- mf_nlheader(mf) |
182 | 4x |
if (is.null(colwidths)) { |
183 | ! |
colwidths <- propose_column_widths(mf, fontspec = fontspec) |
184 |
} |
|
185 | 4x |
mf$strings[1:nlr, 1] <- ifelse(nzchar(mf$strings[1:nlr, 1, drop = TRUE]), |
186 | 4x |
mf$strings[1:nlr, 1, drop = TRUE], |
187 | 4x |
strrep(" ", colwidths) |
188 |
) |
|
189 | ||
190 | ||
191 | 4x |
myfakedf <- as.data.frame(tail(mf$strings, -nlr)) |
192 | 4x |
myfakedf |
193 |
} |
|
194 | ||
195 |
#' Transform `MatrixPrintForm` to RTF |
|
196 |
#' |
|
197 |
#' Experimental export to rich text format (RTF) via the `r2rtf` package. |
|
198 |
#' |
|
199 |
#' @inheritParams page_lcpp |
|
200 |
#' @inheritParams toString |
|
201 |
#' @inheritParams grid::plotViewport |
|
202 |
#' @param mpf (`MatrixPrintForm`)\cr a `MatrixPrintForm` object. |
|
203 |
#' @param colwidths (`numeric`)\cr column widths. |
|
204 |
#' |
|
205 |
#' @details |
|
206 |
#' This function provides a low-level coercion of a `MatrixPrintForm` object into |
|
207 |
#' text containing the corresponding table in RTF. Currently, no pagination is done |
|
208 |
#' at this level, and should be done prior to calling this function, though that |
|
209 |
#' may change in the future. |
|
210 |
#' |
|
211 |
#' @return An RTF object. |
|
212 |
#' |
|
213 |
#' @export |
|
214 |
mpf_to_rtf <- function(mpf, |
|
215 |
colwidths = NULL, |
|
216 |
page_type = "letter", |
|
217 |
pg_width = page_dim(page_type)[if (landscape) 2 else 1], |
|
218 |
pg_height = page_dim(page_type)[if (landscape) 1 else 2], |
|
219 |
landscape = FALSE, |
|
220 |
margins = c(4, 4, 4, 4), |
|
221 |
font_family = "Courier", |
|
222 |
font_size = 8, |
|
223 |
lineheight = 1, |
|
224 |
fontspec = font_spec(font_family, font_size, lineheight), |
|
225 |
...) { |
|
226 | 4x |
if (!requireNamespace("r2rtf")) { |
227 | ! |
stop("RTF export requires the 'r2rtf' package, please install it.") |
228 |
} |
|
229 | 4x |
if (fontspec$family != "Courier") { |
230 | ! |
stop("Experimental RTF export does not currently support fonts other than Courier") |
231 |
} |
|
232 | 4x |
mpf <- matrix_form(mpf, indent_rownames = TRUE, fontspec = fontspec) |
233 | 4x |
nlr <- mf_nlheader(mpf) |
234 | 4x |
if (is.null(colwidths)) { |
235 | ! |
colwidths <- propose_column_widths(mpf, fontspec = fontspec) |
236 |
} |
|
237 | 4x |
mpf$strings[1:nlr, 1] <- ifelse(nzchar(mpf$strings[1:nlr, 1, drop = TRUE]), |
238 | 4x |
mpf$strings[1:nlr, 1, drop = TRUE], |
239 | 4x |
strrep(" ", colwidths) |
240 |
) |
|
241 | ||
242 | 4x |
myfakedf <- mpf_to_dfbody(mpf, colwidths, fontspec = fontspec) |
243 | ||
244 | 4x |
rtfpg <- r2rtf::rtf_page(myfakedf, |
245 | 4x |
width = pg_width, |
246 | 4x |
height = pg_height, |
247 | 4x |
orientation = if (landscape) "landscape" else "portrait", |
248 | 4x |
margin = c(0.1, 0.1, 0.1, 0.1, 0.1, 0.1), |
249 | 4x |
nrow = 10000L |
250 | 4x |
) ## dont allow r2rtf to restrict lines per page beyond actual real eastate |
251 | 4x |
rtfpg <- r2rtf::rtf_title(rtfpg, main_title(mpf), subtitles(mpf), text_font = 1) |
252 | 4x |
for (i in seq_len(nlr)) { |
253 | 4x |
hdrlndat <- prep_header_line(mpf, i) |
254 | 4x |
rtfpg <- r2rtf::rtf_colheader(rtfpg, |
255 | 4x |
paste(hdrlndat, collapse = " | "), |
256 | 4x |
col_rel_width = unlist(tapply(colwidths, |
257 | 4x |
cumsum(mpf$display[i, , drop = TRUE]), |
258 | 4x |
sum, |
259 | 4x |
simplify = FALSE |
260 |
)), |
|
261 | 4x |
border_top = c("", rep(if (i > 1) "single" else "", length(hdrlndat) - 1)), |
262 | 4x |
text_font = 9, ## this means Courier New for some insane reason |
263 | 4x |
text_font_size = font_size |
264 |
) |
|
265 |
} |
|
266 | ||
267 | 4x |
rtfpg <- r2rtf::rtf_body(rtfpg, |
268 | 4x |
col_rel_width = colwidths, |
269 | 4x |
text_justification = c("l", rep("c", ncol(myfakedf) - 1)), |
270 | 4x |
text_format = "", |
271 | 4x |
text_font = 9, |
272 | 4x |
text_font_size = font_size |
273 |
) |
|
274 | ||
275 | 4x |
for (i in seq_along(mpf$ref_footnotes)) { |
276 | 4x |
rtfpg <- r2rtf::rtf_footnote(rtfpg, |
277 | 4x |
mpf$ref_footnotes[i], |
278 | 4x |
border_top = if (i == 1) "single" else "", |
279 | 4x |
border_bottom = if (i == length(mpf$ref_footnotes)) "single" else "", |
280 | 4x |
text_font = 9 |
281 |
) |
|
282 |
} |
|
283 | ||
284 | 4x |
if (length(main_footer(mpf)) > 0) { |
285 | 4x |
rtfpg <- r2rtf::rtf_footnote(rtfpg, main_footer(mpf), text_font = 9) |
286 |
} |
|
287 | 4x |
if (length(prov_footer(mpf)) > 0) { |
288 | 4x |
rtfpg <- r2rtf::rtf_source(rtfpg, prov_footer(mpf), text_font = 9) |
289 |
} |
|
290 | ||
291 | 4x |
rtfpg |
292 |
} |
|
293 | ||
294 |
## Not currently in use, previous alternate ways to get to RTF |
|
295 | ||
296 |
## ## XXX Experimental. Not to be exported without approval |
|
297 |
## mpf_to_huxtable <- function(obj) { |
|
298 |
## if (!requireNamespace("huxtable")) { |
|
299 |
## stop("mpf_to_huxtable requires the huxtable package") |
|
300 |
## } |
|
301 |
## mf <- matrix_form(obj, indent_rownames = TRUE) |
|
302 |
## nlr <- mf_nlheader(mf) |
|
303 |
## myfakedf <- as.data.frame(tail(mf$strings, -nlr)) |
|
304 |
## ret <- huxtable::as_hux(myfakedf, add_colnames = FALSE) |
|
305 |
## mf$strings[!mf$display] <- "" |
|
306 |
## for (i in seq_len(nlr)) { |
|
307 |
## arglist <- c( |
|
308 |
## list(ht = ret, after = i - 1), |
|
309 |
## as.list(mf$strings[i, ]) |
|
310 |
## ) |
|
311 |
## ret <- do.call(huxtable::insert_row, arglist) |
|
312 | ||
313 |
## spanspl <- split( |
|
314 |
## seq_len(ncol(mf$strings)), |
|
315 |
## cumsum(mf$display[i, ]) |
|
316 |
## ) |
|
317 | ||
318 |
## for (j in seq_along(spanspl)) { |
|
319 |
## if (length(spanspl[[j]]) > 1) { |
|
320 |
## ret <- huxtable::merge_cells(ret, row = i, col = spanspl[[j]]) |
|
321 |
## } |
|
322 |
## } |
|
323 |
## } |
|
324 |
## ret <- huxtable::set_header_rows(ret, seq_len(nlr), TRUE) |
|
325 |
## huxtable::font(ret) <- "courier" |
|
326 |
## huxtable::font_size(ret) <- 6 |
|
327 |
## huxtable::align(ret)[ |
|
328 |
## seq_len(nrow(ret)), |
|
329 |
## seq_len(ncol(ret)) |
|
330 |
## ] <- mf$aligns |
|
331 |
## ret |
|
332 |
## } |
|
333 | ||
334 |
## ## XXX Experimental. Not to be exported without approval |
|
335 |
## mpf_to_rtf <- function(obj, ..., file) { |
|
336 |
## huxt <- mpf_to_huxtable(obj) |
|
337 |
## ## a bunch more stuff here |
|
338 |
## huxtable::quick_rtf(huxt, ..., file = file) |
|
339 |
## } |
|
340 | ||
341 |
## ## XXX Experimental. Not to be exported without approval |
|
342 |
## mpf_to_gt <- function(obj) { |
|
343 |
## requireNamespace("gt") |
|
344 |
## mf <- matrix_form(obj, indent_rownames = TRUE) |
|
345 |
## nlh <- mf_nlheader(mf) |
|
346 |
## body_df <- as.data.frame(mf$strings[-1 * seq_len(nlh), ]) |
|
347 |
## varnamerow <- mf_nrheader(mf) |
|
348 |
## ## detect if we have counts |
|
349 |
## if (any(nzchar(mf$formats[seq_len(nlh), ]))) { |
|
350 |
## varnamerow <- varnamerow - 1 |
|
351 |
## } |
|
352 | ||
353 |
## rlbl_lst <- as.list(mf$strings[nlh, , drop = TRUE]) |
|
354 |
## names(rlbl_lst) <- names(body_df) |
|
355 | ||
356 |
## ret <- gt::gt(body_df, rowname_col = "V1") |
|
357 |
## ret <- gt::cols_label(ret, .list = rlbl_lst) |
|
358 |
## if (nlh > 1) { |
|
359 |
## for (i in 1:(nlh - 1)) { |
|
360 |
## linedat <- mf$strings[i, , drop = TRUE] |
|
361 |
## splvec <- cumsum(mf$display[i, , drop = TRUE]) |
|
362 |
## spl <- split(seq_along(linedat), splvec) |
|
363 |
## for (j in seq_along(spl)) { |
|
364 |
## vns <- names(body_df)[spl[[j]]] |
|
365 |
## labval <- linedat[spl[[j]][1]] |
|
366 |
## ret <- gt::tab_spanner(ret, |
|
367 |
## label = labval, |
|
368 |
## columns = {{ vns }}, |
|
369 |
## level = nlh - i, |
|
370 |
## id = paste0(labval, j) |
|
371 |
## ) |
|
372 |
## } |
|
373 |
## } |
|
374 |
## } |
|
375 | ||
376 |
## ret <- gt::opt_css(ret, css = "th.gt_left { white-space:pre;}") |
|
377 | ||
378 |
## ret |
|
379 |
## } |
|
380 | ||
381 |
#' Export as RTF |
|
382 |
#' |
|
383 |
#' Experimental export to the rich text format (RTF) format. |
|
384 |
#' |
|
385 |
#' @details RTF export occurs via the following steps: |
|
386 |
#' * The table is paginated to the specified page size (vertically and horizontally). |
|
387 |
#' * Each separate page is converted to a `MatrixPrintForm` object and then to |
|
388 |
#' RTF-encoded text. |
|
389 |
#' * Separate RTF text chunks are combined and written to a single RTF file. |
|
390 |
#' |
|
391 |
#' Conversion of `MatrixPrintForm` objects to RTF is done via [mpf_to_rtf()]. |
|
392 |
#' |
|
393 |
#' @inheritParams export_as_txt |
|
394 |
#' @inheritParams toString |
|
395 |
#' @inheritParams grid::plotViewport |
|
396 |
#' @inheritParams paginate_to_mpfs |
|
397 |
#' |
|
398 |
#' @export |
|
399 |
export_as_rtf <- function(x, |
|
400 |
file = NULL, |
|
401 |
colwidths = NULL, |
|
402 |
page_type = "letter", |
|
403 |
pg_width = page_dim(page_type)[if (landscape) 2 else 1], |
|
404 |
pg_height = page_dim(page_type)[if (landscape) 1 else 2], |
|
405 |
landscape = FALSE, |
|
406 |
margins = c(bottom = .5, left = .75, top = .5, right = .75), |
|
407 |
font_family = "Courier", |
|
408 |
font_size = 8, |
|
409 |
lineheight = 1, |
|
410 |
fontspec = font_spec(font_family, font_size, lineheight), |
|
411 |
...) { |
|
412 |
# Processing lists of tables or listings |
|
413 | 2x |
if (.is_list_of_tables_or_listings(x)) { |
414 | ! |
if (isFALSE(paginate)) { |
415 | ! |
warning( |
416 | ! |
"paginate is FALSE, but x is a list of tables or listings, ", |
417 | ! |
"so paginate will automatically be updated to TRUE" |
418 |
) |
|
419 |
} |
|
420 | ! |
paginate <- TRUE |
421 |
} |
|
422 | ||
423 | 2x |
if (!requireNamespace("r2rtf")) { |
424 | ! |
stop("RTF export requires the r2rtf package, please install it.") |
425 |
} |
|
426 | 2x |
if (fontspec$family != "Courier") { |
427 | ! |
stop("Experimental RTF export does not currently support fonts other than Courier") |
428 |
} |
|
429 | ||
430 | 2x |
if (is.null(names(margins))) { |
431 | ! |
names(margins) <- marg_order |
432 |
} |
|
433 | ||
434 |
# NEEDS TO BE INTO paginate_to_mpfs so to have this check once for all paginations |
|
435 |
# fullmf <- matrix_form(x, indent_rownames = TRUE, fontspec = fontspec) |
|
436 |
# req_ncols <- ncol(fullmf) + as.numeric(mf_has_rlabels(fullmf)) |
|
437 |
# if (!is.null(colwidths) && length(colwidths) != req_ncols) { |
|
438 |
# stop( |
|
439 |
# "non-null colwidths argument must have length ncol(x) (+ 1 if row labels are present) [", |
|
440 |
# req_ncols, "], got length ", length(colwidths) |
|
441 |
# ) |
|
442 |
# } |
|
443 | ||
444 | 2x |
true_width <- pg_width - sum(margins[c("left", "right")]) |
445 | 2x |
true_height <- pg_height - sum(margins[c("top", "bottom")]) |
446 | ||
447 | 2x |
mpfs <- paginate_to_mpfs( |
448 | 2x |
x, |
449 | 2x |
fontspec = fontspec, |
450 | 2x |
pg_width = true_width, |
451 | 2x |
pg_height = true_height, |
452 | 2x |
margins = c(bottom = 0, left = 0, top = 0, right = 0), |
453 | 2x |
lineheight = 1.25, |
454 | 2x |
colwidths = colwidths, |
455 |
... |
|
456 |
) |
|
457 | ||
458 | 2x |
rtftxts <- lapply(mpfs, function(mf) { |
459 | 4x |
r2rtf::rtf_encode(mpf_to_rtf(mf, |
460 | 4x |
colwidths = mf_col_widths(mf), |
461 | 4x |
page_type = page_type, |
462 | 4x |
pg_width = pg_width, |
463 | 4x |
pg_height = pg_height, |
464 | 4x |
font_size = fontspec$size, |
465 | 4x |
margins = c(top = 0, left = 0, bottom = 0, right = 0) |
466 |
)) |
|
467 |
}) |
|
468 | 2x |
restxt <- paste( |
469 | 2x |
rtftxts[[1]]$start, |
470 | 2x |
paste( |
471 | 2x |
sapply(rtftxts, function(x) x$body), |
472 | 2x |
collapse = "\n{\\pard\\fs2\\par}\\page{\\pard\\fs2\\par}\n" |
473 |
), |
|
474 | 2x |
rtftxts[[1]]$end |
475 |
) |
|
476 | 2x |
if (!is.null(file)) { |
477 | 2x |
cat(restxt, file = file) |
478 |
} else { |
|
479 | ! |
restxt |
480 |
} |
|
481 |
} |
|
482 | ||
483 | ||
484 |
# PDF support ------------------------------------------------------------------ |
|
485 | ||
486 |
#' Export as PDF |
|
487 |
#' |
|
488 |
#' The PDF output from this function is based on the ASCII output created with [toString()]. |
|
489 |
#' |
|
490 |
#' @inheritParams export_as_txt |
|
491 |
#' @inheritParams toString |
|
492 |
#' @param file (`string`)\cr file to write to, must have `.pdf` extension. |
|
493 |
#' @param width `r lifecycle::badge("deprecated")` Please use the `pg_width` argument or specify |
|
494 |
#' `page_type` instead. |
|
495 |
#' @param height `r lifecycle::badge("deprecated")` Please use the `pg_height` argument or |
|
496 |
#' specify `page_type` instead. |
|
497 |
#' @param fontsize `r lifecycle::badge("deprecated")` Please use the `font_size` argument instead. |
|
498 |
#' @param margins (`numeric(4)`)\cr the number of lines/characters of the margin on the bottom, |
|
499 |
#' left, top, and right sides of the page, respectively. |
|
500 |
#' |
|
501 |
#' @importFrom grDevices pdf |
|
502 |
#' @importFrom grid textGrob grid.newpage gpar pushViewport plotViewport unit grid.draw |
|
503 |
#' convertWidth convertHeight grobHeight grobWidth |
|
504 |
#' @importFrom grid textGrob get.gpar |
|
505 |
#' @importFrom grDevices dev.off |
|
506 |
#' @importFrom tools file_ext |
|
507 |
#' |
|
508 |
#' @details |
|
509 |
#' By default, pagination is performed with default `cpp` and `lpp` defined by specified page |
|
510 |
#' dimensions and margins. User-specified `lpp` and `cpp` values override this, and should |
|
511 |
#' be used with caution. |
|
512 |
#' |
|
513 |
#' Title and footer materials are also word-wrapped by default (unlike when printed to the |
|
514 |
#' terminal), with `cpp` (as defined above) as the default `max_width`. |
|
515 |
#' |
|
516 |
#' @seealso [export_as_txt()] |
|
517 |
#' |
|
518 |
#' @examples |
|
519 |
#' \dontrun{ |
|
520 |
#' tf <- tempfile(fileext = ".pdf") |
|
521 |
#' export_as_pdf(basic_matrix_form(mtcars), file = tf, pg_height = 4) |
|
522 |
#' |
|
523 |
#' tf <- tempfile(fileext = ".pdf") |
|
524 |
#' export_as_pdf(basic_matrix_form(mtcars), file = tf, lpp = 8) |
|
525 |
#' } |
|
526 |
#' |
|
527 |
#' @export |
|
528 |
export_as_pdf <- function(x, |
|
529 |
file, |
|
530 |
page_type = "letter", |
|
531 |
landscape = FALSE, |
|
532 |
pg_width = page_dim(page_type)[if (landscape) 2 else 1], |
|
533 |
pg_height = page_dim(page_type)[if (landscape) 1 else 2], |
|
534 |
width = lifecycle::deprecated(), |
|
535 |
height = lifecycle::deprecated(), |
|
536 |
margins = c(4, 4, 4, 4), |
|
537 |
min_siblings = 2, |
|
538 |
font_family = "Courier", |
|
539 |
font_size = 8, |
|
540 |
fontsize = font_size, |
|
541 |
lineheight = 1.2, ## XXX this matches legacy behavior but differs from default everywhere else |
|
542 |
paginate = TRUE, |
|
543 |
page_num = default_page_number(), |
|
544 |
lpp = NULL, |
|
545 |
cpp = NULL, |
|
546 |
hsep = "-", |
|
547 |
indent_size = 2, |
|
548 |
rep_cols = NULL, |
|
549 |
tf_wrap = TRUE, |
|
550 |
max_width = NULL, |
|
551 |
colwidths = NULL, |
|
552 |
fontspec = font_spec(font_family, font_size, lineheight), |
|
553 |
ttype_ok = FALSE) { |
|
554 |
## this has to happen at the very beginning before the first use of fontspec |
|
555 |
## which happens in the default value of colwidths. yay lazy evaluation... |
|
556 | 6x |
if (missing(font_size) && !missing(fontsize)) { |
557 | ! |
font_size <- fontsize |
558 |
} |
|
559 | ||
560 | 6x |
stopifnot(tools::file_ext(file) != ".pdf") |
561 | ||
562 |
# Processing lists of tables or listings |
|
563 | 6x |
if (.is_list_of_tables_or_listings(x)) { |
564 | 2x |
if (isFALSE(paginate)) { |
565 | 2x |
warning( |
566 | 2x |
"paginate is FALSE, but x is a list of tables or listings, ", |
567 | 2x |
"so paginate will automatically be updated to TRUE" |
568 |
) |
|
569 |
} |
|
570 | 2x |
paginate <- TRUE |
571 |
} |
|
572 | ||
573 | 6x |
gp_plot <- gpar_from_fspec(fontspec) |
574 | ||
575 | 6x |
if (lifecycle::is_present(width)) { |
576 | 1x |
lifecycle::deprecate_warn("0.5.5", "export_as_pdf(width)", "export_as_pdf(pg_width)") |
577 | 1x |
pg_width <- width |
578 |
} |
|
579 | 6x |
if (lifecycle::is_present(height)) { |
580 | 1x |
lifecycle::deprecate_warn("0.5.5", "export_as_pdf(height)", "export_as_pdf(pg_height)") |
581 | 1x |
pg_height <- height |
582 |
} |
|
583 | ||
584 | 6x |
gp_plot <- grid::gpar(fontsize = font_size, fontfamily = font_family) |
585 | ||
586 | 6x |
pdf(file = file, width = pg_width, height = pg_height) |
587 | 6x |
out_dev_num <- dev.cur() |
588 | 6x |
on.exit(dev.off(out_dev_num), add = TRUE) |
589 | 6x |
grid::grid.newpage() |
590 | 6x |
grid::pushViewport(grid::plotViewport(margins = margins, gp = gp_plot)) |
591 | ||
592 | 6x |
cur_gpar <- grid::get.gpar() |
593 | 6x |
if (is.null(lpp)) { |
594 | 6x |
lpp <- floor(grid::convertHeight(grid::unit(1, "npc"), "lines", valueOnly = TRUE) / |
595 | 6x |
(cur_gpar$cex * cur_gpar$lineheight)) ## - sum(margins[c(1, 3)]) # bottom, top # nolint |
596 |
} |
|
597 | 6x |
if (is.null(cpp)) { |
598 | 4x |
cpp <- floor(grid::convertWidth(grid::unit(1, "npc"), "inches", valueOnly = TRUE) * |
599 | 4x |
font_lcpi(fontspec$family, fontspec$size, cur_gpar$lineheight)$cpi) - sum(margins[c(2, 4)]) # left, right # nolint |
600 |
} |
|
601 | 6x |
if (tf_wrap && is.null(max_width)) { |
602 | 6x |
max_width <- cpp |
603 |
} |
|
604 | ||
605 | 6x |
newdev <- open_font_dev(fontspec, silent = TRUE) ## cause we know there's another dev open... |
606 | 6x |
if (newdev) { |
607 | 6x |
on.exit(close_font_dev(), add = TRUE) |
608 |
} |
|
609 | ||
610 | 6x |
if (paginate) { |
611 | 4x |
tbls <- paginate_to_mpfs( |
612 | 4x |
x, |
613 | 4x |
page_type = page_type, |
614 | 4x |
fontspec = fontspec, |
615 | 4x |
landscape = landscape, |
616 | 4x |
pg_width = pg_width, |
617 | 4x |
pg_height = pg_height, |
618 | 4x |
margins = margins, |
619 | 4x |
lpp = lpp, |
620 | 4x |
cpp = cpp, |
621 | 4x |
min_siblings = min_siblings, |
622 | 4x |
nosplitin = character(), |
623 | 4x |
colwidths = colwidths, |
624 | 4x |
tf_wrap = tf_wrap, |
625 | 4x |
max_width = max_width, |
626 | 4x |
indent_size = indent_size, |
627 | 4x |
verbose = FALSE, |
628 | 4x |
rep_cols = rep_cols, |
629 | 4x |
page_num = page_num |
630 |
) |
|
631 |
} else { |
|
632 | 2x |
mf <- matrix_form(x, TRUE, TRUE, indent_size = indent_size, fontspec = fontspec) |
633 | 2x |
mf_col_widths(mf) <- colwidths %||% propose_column_widths(mf, fontspec = fontspec) |
634 | 2x |
tbls <- list(mf) |
635 |
} |
|
636 | ||
637 |
# Needs to be here because of adding cpp if it is not "auto" |
|
638 | 6x |
if (!is.character(max_width)) { |
639 | 6x |
max_width <- .handle_max_width( |
640 | 6x |
tf_wrap = tf_wrap, |
641 | 6x |
max_width = max_width, |
642 | 6x |
cpp = cpp |
643 |
) |
|
644 |
} |
|
645 | ||
646 | 6x |
tbl_txts <- lapply(tbls, function(tbli) { |
647 | 10x |
toString( |
648 | 10x |
tbli, |
649 | 10x |
widths = tbli$col_widths + 1, |
650 | 10x |
hsep = hsep, |
651 | 10x |
tf_wrap = tf_wrap, |
652 | 10x |
max_width = max_width, |
653 | 10x |
fontspec = fontspec, |
654 | 10x |
ttype_ok = ttype_ok |
655 |
) |
|
656 |
}) |
|
657 | ||
658 |
## switch back to our output pdf device |
|
659 | 6x |
dev.set(out_dev_num) |
660 | 6x |
gtbls <- lapply(tbl_txts, function(txt) { |
661 | 10x |
grid::textGrob( |
662 | 10x |
txt, |
663 | 10x |
x = grid::unit(0, "npc"), y = grid::unit(1, "npc"), |
664 | 10x |
just = c("left", "top") |
665 |
) |
|
666 |
}) |
|
667 | ||
668 | 6x |
npages <- length(gtbls) |
669 | 6x |
exceeds_width <- rep(FALSE, npages) |
670 | 6x |
exceeds_height <- rep(FALSE, npages) |
671 | ||
672 | 6x |
for (i in seq_along(gtbls)) { |
673 | 10x |
g <- gtbls[[i]] |
674 | ||
675 | 10x |
if (i > 1) { |
676 | 4x |
grid::grid.newpage() |
677 | 4x |
grid::pushViewport(grid::plotViewport(margins = margins, gp = gp_plot)) |
678 |
} |
|
679 | ||
680 | 10x |
if (grid::convertHeight(grid::grobHeight(g), "inches", valueOnly = TRUE) > |
681 | 10x |
grid::convertHeight(grid::unit(1, "npc"), "inches", valueOnly = TRUE)) { # nolint |
682 | 1x |
exceeds_height[i] <- TRUE |
683 | 1x |
warning("height of page ", i, " exceeds the available space") |
684 |
} |
|
685 | 10x |
if (grid::convertWidth(grid::grobWidth(g), "inches", valueOnly = TRUE) > |
686 | 10x |
grid::convertWidth(grid::unit(1, "npc"), "inches", valueOnly = TRUE)) { # nolint |
687 | 4x |
exceeds_width[i] <- TRUE |
688 | 4x |
warning("width of page ", i, " exceeds the available space") |
689 |
} |
|
690 | ||
691 | 10x |
grid::grid.draw(g) |
692 |
} |
|
693 | 6x |
list( |
694 | 6x |
file = file, npages = npages, exceeds_width = exceeds_width, exceeds_height = exceeds_height, |
695 | 6x |
lpp = lpp, cpp = cpp |
696 |
) |
|
697 |
} |
1 |
## credit: rlang, Henry and Wickham. |
|
2 |
## this one tiny utility function is NOT worth a dependency. |
|
3 |
## modified it so any length 0 x grabs y |
|
4 | ||
5 |
#' `%||%` (if length-0) alternative operator |
|
6 |
#' |
|
7 |
#' @param a (`ANY`)\cr element to select *only* if it is not of length 0. |
|
8 |
#' @param b (`ANY`)\cr element to select if `a` has length 0. |
|
9 |
#' |
|
10 |
#' @return `a` if it is not of length 0, otherwise `b`. |
|
11 |
#' |
|
12 |
#' @examples |
|
13 |
#' 6 %||% 10 |
|
14 |
#' |
|
15 |
#' character() %||% "hi" |
|
16 |
#' |
|
17 |
#' NULL %||% "hi" |
|
18 |
#' |
|
19 |
#' @export |
|
20 |
#' @name ifnotlen0 |
|
21 |
`%||%` <- function(a, b) { |
|
22 | 420x |
if (length(a) == 0) { |
23 | 128x |
b |
24 |
} else { |
|
25 | 292x |
a |
26 |
} |
|
27 |
} |
1 |
#' Return an object with a label attribute |
|
2 |
#' |
|
3 |
#' @param x (`ANY`)\cr an object. |
|
4 |
#' @param label (`string`)\cr label attribute to attach to `x`. |
|
5 |
#' |
|
6 |
#' @return `x` labeled by `label`. Note that the exact mechanism of labeling should be considered |
|
7 |
#' an internal implementation detail, but the label can always be retrieved via `obj_label`. |
|
8 |
#' |
|
9 |
#' @examples |
|
10 |
#' x <- with_label(c(1, 2, 3), label = "Test") |
|
11 |
#' obj_label(x) |
|
12 |
#' |
|
13 |
#' @export |
|
14 |
with_label <- function(x, label) { |
|
15 | 1x |
obj_label(x) <- label |
16 | 1x |
x |
17 |
} |
|
18 | ||
19 |
#' Get label attributes of variables in a `data.frame` |
|
20 |
#' |
|
21 |
#' Variable labels can be stored as a `label` attribute for each variable. |
|
22 |
#' This functions returns a named character vector with the variable labels |
|
23 |
#' (or empty strings if not specified). |
|
24 |
#' |
|
25 |
#' @param x (`data.frame`)\cr a data frame object. |
|
26 |
#' @param fill (`flag`)\cr whether variable names should be returned for variables for |
|
27 |
#' which the `label` attribute does not exist. If `FALSE`, these variables are filled with |
|
28 |
#' `NA`s instead. |
|
29 |
#' |
|
30 |
#' @return a named character vector of variable labels from `x`, with names corresponding |
|
31 |
#' to variable names. |
|
32 |
#' |
|
33 |
#' @examples |
|
34 |
#' x <- iris |
|
35 |
#' var_labels(x) |
|
36 |
#' var_labels(x) <- paste("label for", names(iris)) |
|
37 |
#' var_labels(x) |
|
38 |
#' |
|
39 |
#' @export |
|
40 |
var_labels <- function(x, fill = FALSE) { |
|
41 | 5x |
stopifnot(is.data.frame(x)) |
42 | 5x |
if (NCOL(x) == 0) { |
43 | 1x |
return(character()) |
44 |
} |
|
45 | ||
46 | 4x |
y <- Map(function(col, colname) { |
47 | 38x |
label <- attr(col, "label") |
48 | ||
49 | 38x |
if (is.null(label)) { |
50 | 11x |
if (fill) { |
51 | ! |
colname |
52 |
} else { |
|
53 | 4x |
NA_character_ |
54 |
} |
|
55 |
} else { |
|
56 | 27x |
if (!is.character(label) && !(length(label) == 1)) { |
57 | ! |
stop("label for variable ", colname, "is not a character string") |
58 |
} |
|
59 | 27x |
as.vector(label) |
60 |
} |
|
61 | 4x |
}, x, colnames(x)) |
62 | ||
63 | 4x |
labels <- unlist(y, recursive = FALSE, use.names = TRUE) |
64 | ||
65 | 4x |
if (!is.character(labels)) { |
66 | ! |
stop("label extraction failed") |
67 |
} |
|
68 | ||
69 | 4x |
labels |
70 |
} |
|
71 | ||
72 |
#' Set label attributes of all variables in a `data.frame` |
|
73 |
#' |
|
74 |
#' Variable labels can be stored as the `label` attribute for each variable. |
|
75 |
#' This functions sets all non-missing (non-`NA`) variable labels in a `data.frame`. |
|
76 |
#' |
|
77 |
#' @inheritParams var_labels |
|
78 |
#' @param value (`character`)\cr a vector of new variable labels. If any values are `NA`, |
|
79 |
#' the label for that variable is removed. |
|
80 |
#' |
|
81 |
#' @return `x` with modified variable labels. |
|
82 |
#' |
|
83 |
#' @examples |
|
84 |
#' x <- iris |
|
85 |
#' var_labels(x) |
|
86 |
#' var_labels(x) <- paste("label for", names(iris)) |
|
87 |
#' var_labels(x) |
|
88 |
#' |
|
89 |
#' if (interactive()) { |
|
90 |
#' View(x) # in RStudio data viewer labels are displayed |
|
91 |
#' } |
|
92 |
#' |
|
93 |
#' @export |
|
94 |
`var_labels<-` <- function(x, value) { |
|
95 | 3x |
stopifnot( |
96 | 3x |
is.data.frame(x), |
97 | 3x |
is.character(value), |
98 | 3x |
ncol(x) == length(value) |
99 |
) |
|
100 | ||
101 | 3x |
theseq <- if (!is.null(names(value))) names(value) else seq_along(x) |
102 |
# across columns of x |
|
103 | 3x |
for (j in theseq) { |
104 | 21x |
attr(x[[j]], "label") <- if (!is.na(value[j])) { |
105 | 21x |
unname(value[j]) |
106 |
} else { |
|
107 | ! |
NULL |
108 |
} |
|
109 |
} |
|
110 | ||
111 | 3x |
x |
112 |
} |
|
113 | ||
114 |
#' Copy and change variable labels of a `data.frame` |
|
115 |
#' |
|
116 |
#' Relabel a subset of the variables. |
|
117 |
#' |
|
118 |
#' @inheritParams var_labels<- |
|
119 |
#' @param ... name-value pairs, where each name corresponds to a variable name in |
|
120 |
#' `x` and the value to the new variable label. |
|
121 |
#' |
|
122 |
#' @return A copy of `x` with labels modified according to `...` |
|
123 |
#' |
|
124 |
#' @examples |
|
125 |
#' x <- var_relabel(iris, Sepal.Length = "Sepal Length of iris flower") |
|
126 |
#' var_labels(x) |
|
127 |
#' |
|
128 |
#' @export |
|
129 |
var_relabel <- function(x, ...) { |
|
130 |
# todo: make this function more readable / code easier |
|
131 | 1x |
stopifnot(is.data.frame(x)) |
132 | 1x |
if (missing(...)) { |
133 | ! |
return(x) |
134 |
} |
|
135 | 1x |
dots <- list(...) |
136 | 1x |
varnames <- names(dots) |
137 | 1x |
stopifnot(!is.null(varnames)) |
138 | ||
139 | 1x |
map_varnames <- match(varnames, colnames(x)) |
140 | ||
141 | 1x |
if (any(is.na(map_varnames))) { |
142 | ! |
stop("variables: ", paste(varnames[is.na(map_varnames)], collapse = ", "), " not found") |
143 |
} |
|
144 | ||
145 | 1x |
if (any(vapply(dots, Negate(is.character), logical(1)))) { |
146 | ! |
stop("all variable labels must be of type character") |
147 |
} |
|
148 | ||
149 | 1x |
for (i in seq_along(map_varnames)) { |
150 | 1x |
attr(x[[map_varnames[[i]]]], "label") <- dots[[i]] |
151 |
} |
|
152 | ||
153 | 1x |
x |
154 |
} |
|
155 | ||
156 |
#' Remove variable labels of a `data.frame` |
|
157 |
#' |
|
158 |
#' Remove `label` attribute from all variables in a data frame. |
|
159 |
#' |
|
160 |
#' @param x (`data.frame`)\cr a `data.frame` object. |
|
161 |
#' |
|
162 |
#' @return `x` with its variable labels stripped. |
|
163 |
#' |
|
164 |
#' @examples |
|
165 |
#' x <- var_labels_remove(iris) |
|
166 |
#' |
|
167 |
#' @export |
|
168 |
var_labels_remove <- function(x) { |
|
169 | 1x |
stopifnot(is.data.frame(x)) |
170 | ||
171 | 1x |
for (i in seq_len(ncol(x))) { |
172 | 11x |
attr(x[[i]], "label") <- NULL |
173 |
} |
|
174 | ||
175 | 1x |
x |
176 |
} |
1 |
#' Default horizontal separator |
|
2 |
#' |
|
3 |
#' The default horizontal separator character which can be displayed in the current |
|
4 |
#' charset for use in rendering table-like objects. |
|
5 |
#' |
|
6 |
#' @param hsep_char (`string`)\cr character that will be set in the R environment |
|
7 |
#' options as the default horizontal separator. Must be a single character. Use |
|
8 |
#' `getOption("formatters_default_hsep")` to get its current value (`NULL` if not set). |
|
9 |
#' |
|
10 |
#' @return unicode 2014 (long dash for generating solid horizontal line) if in a |
|
11 |
#' locale that uses a UTF character set, otherwise an ASCII hyphen with a |
|
12 |
#' once-per-session warning. |
|
13 |
#' |
|
14 |
#' @examples |
|
15 |
#' default_hsep() |
|
16 |
#' set_default_hsep("o") |
|
17 |
#' default_hsep() |
|
18 |
#' |
|
19 |
#' @name default_horizontal_sep |
|
20 |
#' @export |
|
21 |
default_hsep <- function() { |
|
22 | 52x |
system_default_hsep <- getOption("formatters_default_hsep") |
23 | ||
24 | 52x |
if (is.null(system_default_hsep)) { |
25 | 51x |
if (any(grepl("^UTF", utils::localeToCharset()))) { |
26 | 51x |
hsep <- "\u2014" |
27 |
} else { |
|
28 | ! |
if (interactive()) { |
29 | ! |
warning( |
30 | ! |
"Detected non-UTF charset. Falling back to '-' ", |
31 | ! |
"as default header/body separator. This warning ", |
32 | ! |
"will only be shown once per R session." |
33 | ! |
) # nocov |
34 |
} # nocov |
|
35 |
hsep <- "-" # nocov |
|
36 |
} |
|
37 |
} else { |
|
38 | 1x |
hsep <- system_default_hsep |
39 |
} |
|
40 | 52x |
hsep |
41 |
} |
|
42 | ||
43 |
#' @name default_horizontal_sep |
|
44 |
#' @export |
|
45 |
set_default_hsep <- function(hsep_char) { |
|
46 | 3x |
checkmate::assert_string(hsep_char, n.chars = 1, null.ok = TRUE) |
47 | 2x |
options("formatters_default_hsep" = hsep_char) |
48 |
} |
|
49 | ||
50 |
#' Default page number format |
|
51 |
#' |
|
52 |
#' If set, the default page number string will appear on the bottom right of |
|
53 |
#' every page of a paginated table. The current `cpp` is used to position the string. |
|
54 |
#' |
|
55 |
#' @param page_number (`string`)\cr single string value to set the page number format. |
|
56 |
#' It should be formatted similarly to the following format: `"page {i}/{n}"`. |
|
57 |
#' `{i}` will be replaced with the current page number, and `{n}` will be replaced with the |
|
58 |
#' total page number. Current `cpp` is used to position the string in the bottom right corner. |
|
59 |
#' |
|
60 |
#' @return The page number format string (`NULL` if not set). |
|
61 |
#' |
|
62 |
#' @examples |
|
63 |
#' default_page_number() |
|
64 |
#' set_default_page_number("page {i} of {n}") |
|
65 |
#' default_page_number() |
|
66 |
#' |
|
67 |
#' @name default_page_number |
|
68 |
#' @export |
|
69 |
default_page_number <- function() { |
|
70 | 35x |
getOption("formatter_default_page_number", default = NULL) |
71 |
} |
|
72 | ||
73 |
#' @name default_page_number |
|
74 |
#' @export |
|
75 |
set_default_page_number <- function(page_number) { |
|
76 | 6x |
checkmate::assert_string(page_number, null.ok = TRUE) |
77 | 6x |
options("formatter_default_page_number" = page_number) |
78 |
} |